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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.9! raeburn     4: # $Id: lonnet.pm,v 1.1172.2.8 2012/08/01 04:56:54 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.729     www       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) = @_;
                   1238:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
                   1239:         $offloadto,$otherserver);
                   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') {
                   1264:         my $currbalancer = $result->{'lonhost'};
                   1265:         my $currtargets = $result->{'targets'};
                   1266:         my $currrules = $result->{'rules'};
                   1267:         if ($currbalancer ne '') {
                   1268:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1269:                 $is_balancer = 1;
                   1270:             }
                   1271:         }
                   1272:         if ($is_balancer) {
                   1273:             if (ref($currrules) eq 'HASH') {
                   1274:                 if ($homeintdom) {
                   1275:                     if ($uname ne '') {
                   1276:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1277:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1278:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1279:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1280:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1281:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1282:                             }
                   1283:                         }
                   1284:                         if ($rule_in_effect eq '') {
                   1285:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1286:                             if ($userenv{'inststatus'} ne '') {
                   1287:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1288:                                 my ($othertitle,$usertypes,$types) =
                   1289:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1290:                                 if (ref($types) eq 'ARRAY') {
                   1291:                                     foreach my $type (@{$types}) {
                   1292:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1293:                                             if (exists($currrules->{$type})) {
                   1294:                                                 $rule_in_effect = $currrules->{$type};
                   1295:                                             }
                   1296:                                         }
                   1297:                                     }
                   1298:                                 }
                   1299:                             } else {
                   1300:                                 if (exists($currrules->{'default'})) {
                   1301:                                     $rule_in_effect = $currrules->{'default'};
                   1302:                                 }
                   1303:                             }
                   1304:                         }
                   1305:                     } else {
                   1306:                         if (exists($currrules->{'default'})) {
                   1307:                             $rule_in_effect = $currrules->{'default'};
                   1308:                         }
                   1309:                     }
                   1310:                 } else {
                   1311:                     if ($currrules->{'_LC_external'} ne '') {
                   1312:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1313:                     }
                   1314:                 }
                   1315:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1316:                                                        $uname,$udom);
                   1317:             }
                   1318:         }
                   1319:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1320:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1321:         unless (defined($cached)) {
                   1322:             my %domconfig =
                   1323:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1324:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1325:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1326:             }
                   1327:         }
                   1328:         if (ref($result) eq 'HASH') {
                   1329:             my $currbalancer = $result->{'lonhost'};
                   1330:             my $currtargets = $result->{'targets'};
                   1331:             my $currrules = $result->{'rules'};
                   1332: 
                   1333:             if ($currbalancer eq $lonhost) {
                   1334:                 $is_balancer = 1;
                   1335:                 if (ref($currrules) eq 'HASH') {
                   1336:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1337:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1338:                     }
                   1339:                 }
                   1340:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1341:                                                        $uname,$udom);
                   1342:             }
                   1343:         } else {
                   1344:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1345:                 $is_balancer = 1;
                   1346:                 $offloadto = &this_host_spares($dom_in_use);
                   1347:             }
                   1348:         }
                   1349:     } else {
                   1350:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1351:             $is_balancer = 1;
                   1352:             $offloadto = &this_host_spares($dom_in_use);
                   1353:         }
                   1354:     }
1.1172.2.5  raeburn  1355:     if ($is_balancer) {
                   1356:         my $lowest_load = 30000;
                   1357:         if (ref($offloadto) eq 'HASH') {
                   1358:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1359:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1360:                     ($otherserver,$lowest_load) =
                   1361:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1362:                 }
1.1129    raeburn  1363:             }
1.1172.2.5  raeburn  1364:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1365: 
1.1172.2.5  raeburn  1366:             if (!$found_server) {
                   1367:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1368:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1369:                         ($otherserver,$lowest_load) =
                   1370:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1371:                     }
                   1372:                 }
                   1373:             }
                   1374:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1375:             if (@{$offloadto} == 1) {
                   1376:                 $otherserver = $offloadto->[0];
                   1377:             } elsif (@{$offloadto} > 1) {
                   1378:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1379:                     ($otherserver,$lowest_load) =
                   1380:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1381:                 }
                   1382:             }
                   1383:         }
1.1172.2.5  raeburn  1384:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1385:             $is_balancer = 0;
                   1386:             if ($uname ne '' && $udom ne '') {
                   1387:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1388: 
                   1389:                     &appenv({'user.loadbalexempt'     => $lonhost,
                   1390:                              'user.loadbalcheck.time' => time});
                   1391:                 }
1.1129    raeburn  1392:             }
                   1393:         }
                   1394:     }
                   1395:     return ($is_balancer,$otherserver);
                   1396: }
                   1397: 
                   1398: sub get_loadbalancer_targets {
                   1399:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1400:     my $offloadto;
1.1172.2.4  raeburn  1401:     if ($rule_in_effect eq 'none') {
                   1402:         return [$perlvar{'lonHostID'}];
                   1403:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1404:         $offloadto = $currtargets;
                   1405:     } else {
                   1406:         if ($rule_in_effect eq 'homeserver') {
                   1407:             my $homeserver = &homeserver($uname,$udom);
                   1408:             if ($homeserver ne 'no_host') {
                   1409:                 $offloadto = [$homeserver];
                   1410:             }
                   1411:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1412:             my %domconfig =
                   1413:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1414:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1415:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1416:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1417:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1418:                     }
                   1419:                 }
                   1420:             } else {
1.1172.2.7  raeburn  1421:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1422:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1423:                 if (&hostname($remotebalancer) ne '') {
                   1424:                     $offloadto = [$remotebalancer];
                   1425:                 }
                   1426:             }
                   1427:         } elsif (&hostname($rule_in_effect) ne '') {
                   1428:             $offloadto = [$rule_in_effect];
                   1429:         }
                   1430:     }
                   1431:     return $offloadto;
                   1432: }
                   1433: 
1.1127    raeburn  1434: sub internet_dom_servers {
                   1435:     my ($dom) = @_;
                   1436:     my (%uniqservers,%servers);
                   1437:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1438:     my @machinedoms = &machine_domains($primaryserver);
                   1439:     foreach my $mdom (@machinedoms) {
                   1440:         my %currservers = %servers;
                   1441:         my %server = &get_servers($mdom);
                   1442:         %servers = (%currservers,%server);
                   1443:     }
                   1444:     my %by_hostname;
                   1445:     foreach my $id (keys(%servers)) {
                   1446:         push(@{$by_hostname{$servers{$id}}},$id);
                   1447:     }
                   1448:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1449:         if (@{$by_hostname{$hostname}} > 1) {
                   1450:             my $match = 0;
                   1451:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1452:                 if (&host_domain($id) eq $dom) {
                   1453:                     $uniqservers{$id} = $hostname;
                   1454:                     $match = 1;
                   1455:                 }
                   1456:             }
                   1457:             unless ($match) {
                   1458:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1459:             }
                   1460:         } else {
                   1461:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1462:         }
                   1463:     }
                   1464:     return %uniqservers;
                   1465: }
                   1466: 
1.1       albertel 1467: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1468: 
1.599     albertel 1469: my %homecache;
1.1       albertel 1470: sub homeserver {
1.230     stredwic 1471:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1472:     my $index="$uname:$udom";
1.426     albertel 1473: 
1.599     albertel 1474:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1475: 
                   1476:     my %servers = &get_servers($udom,'library');
                   1477:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1478:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1479: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1480: 
                   1481: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1482: 	if ($answer eq 'found') {
                   1483: 	    delete($badServerCache{$tryserver}); 
                   1484: 	    return $homecache{$index}=$tryserver;
                   1485: 	} elsif ($answer eq 'no_host') {
                   1486: 	    $badServerCache{$tryserver}=1;
                   1487: 	}
1.1       albertel 1488:     }    
                   1489:     return 'no_host';
1.70      www      1490: }
                   1491: 
                   1492: # ------------------------------------- Find the usernames behind a list of IDs
                   1493: 
                   1494: sub idget {
                   1495:     my ($udom,@ids)=@_;
                   1496:     my %returnhash=();
                   1497:     
1.841     albertel 1498:     my %servers = &get_servers($udom,'library');
                   1499:     foreach my $tryserver (keys(%servers)) {
                   1500: 	my $idlist=join('&',@ids);
                   1501: 	$idlist=~tr/A-Z/a-z/; 
                   1502: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1503: 	my @answer=();
                   1504: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1505: 	    @answer=split(/\&/,$reply);
                   1506: 	}                    ;
                   1507: 	my $i;
                   1508: 	for ($i=0;$i<=$#ids;$i++) {
                   1509: 	    if ($answer[$i]) {
                   1510: 		$returnhash{$ids[$i]}=$answer[$i];
                   1511: 	    } 
                   1512: 	}
                   1513:     } 
1.70      www      1514:     return %returnhash;
                   1515: }
                   1516: 
                   1517: # ------------------------------------- Find the IDs behind a list of usernames
                   1518: 
                   1519: sub idrget {
                   1520:     my ($udom,@unames)=@_;
                   1521:     my %returnhash=();
1.800     albertel 1522:     foreach my $uname (@unames) {
                   1523:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1524:     }
1.70      www      1525:     return %returnhash;
                   1526: }
                   1527: 
                   1528: # ------------------------------- Store away a list of names and associated IDs
                   1529: 
                   1530: sub idput {
                   1531:     my ($udom,%ids)=@_;
                   1532:     my %servers=();
1.800     albertel 1533:     foreach my $uname (keys(%ids)) {
                   1534: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1535:         my $uhom=&homeserver($uname,$udom);
1.70      www      1536:         if ($uhom ne 'no_host') {
1.800     albertel 1537:             my $id=&escape($ids{$uname});
1.70      www      1538:             $id=~tr/A-Z/a-z/;
1.800     albertel 1539:             my $esc_unam=&escape($uname);
1.70      www      1540: 	    if ($servers{$uhom}) {
1.800     albertel 1541: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1542:             } else {
1.800     albertel 1543:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1544:             }
                   1545:         }
1.191     harris41 1546:     }
1.800     albertel 1547:     foreach my $server (keys(%servers)) {
                   1548:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1549:     }
1.344     www      1550: }
                   1551: 
1.1023    raeburn  1552: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1553: sub dump_dom {
1.1165    droeschl 1554:     my ($namespace, $udom, $regexp) = @_;
                   1555: 
                   1556:     $udom ||= $env{'user.domain'};
                   1557: 
                   1558:     return () unless $udom;
                   1559: 
                   1560:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1561: }
                   1562: 
1.1023    raeburn  1563: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1564: 
                   1565: sub get_dom {
1.860     raeburn  1566:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1567:     my $items='';
                   1568:     foreach my $item (@$storearr) {
                   1569:         $items.=&escape($item).'&';
                   1570:     }
                   1571:     $items=~s/\&$//;
1.860     raeburn  1572:     if (!$udom) {
                   1573:         $udom=$env{'user.domain'};
                   1574:         if (defined(&domain($udom,'primary'))) {
                   1575:             $uhome=&domain($udom,'primary');
                   1576:         } else {
1.874     albertel 1577:             undef($uhome);
1.860     raeburn  1578:         }
                   1579:     } else {
                   1580:         if (!$uhome) {
                   1581:             if (defined(&domain($udom,'primary'))) {
                   1582:                 $uhome=&domain($udom,'primary');
                   1583:             }
                   1584:         }
                   1585:     }
                   1586:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1587:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1588:         my %returnhash;
1.875     albertel 1589:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1590:             return %returnhash;
                   1591:         }
1.806     raeburn  1592:         my @pairs=split(/\&/,$rep);
                   1593:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1594:             return @pairs;
                   1595:         }
                   1596:         my $i=0;
                   1597:         foreach my $item (@$storearr) {
                   1598:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1599:             $i++;
                   1600:         }
                   1601:         return %returnhash;
                   1602:     } else {
1.880     banghart 1603:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1604:     }
                   1605: }
                   1606: 
                   1607: # -------------------------------------------- put items in domain db files 
                   1608: 
                   1609: sub put_dom {
1.860     raeburn  1610:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1611:     if (!$udom) {
                   1612:         $udom=$env{'user.domain'};
                   1613:         if (defined(&domain($udom,'primary'))) {
                   1614:             $uhome=&domain($udom,'primary');
                   1615:         } else {
1.874     albertel 1616:             undef($uhome);
1.860     raeburn  1617:         }
                   1618:     } else {
                   1619:         if (!$uhome) {
                   1620:             if (defined(&domain($udom,'primary'))) {
                   1621:                 $uhome=&domain($udom,'primary');
                   1622:             }
                   1623:         }
                   1624:     } 
                   1625:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1626:         my $items='';
                   1627:         foreach my $item (keys(%$storehash)) {
                   1628:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1629:         }
                   1630:         $items=~s/\&$//;
                   1631:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1632:     } else {
1.860     raeburn  1633:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1634:     }
                   1635: }
                   1636: 
1.1023    raeburn  1637: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1638: sub newput_dom {
1.1023    raeburn  1639:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1640:     my $result;
                   1641:     if (!$udom) {
                   1642:         $udom=$env{'user.domain'};
                   1643:     }
1.1023    raeburn  1644:     if ($udom) {
                   1645:         my $uname = &get_domainconfiguser($udom);
                   1646:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1647:     }
                   1648:     return $result;
                   1649: }
                   1650: 
1.1023    raeburn  1651: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1652: sub del_dom {
1.1023    raeburn  1653:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1654:     if (ref($storearr) eq 'ARRAY') {
                   1655:         if (!$udom) {
                   1656:             $udom=$env{'user.domain'};
                   1657:         }
1.1023    raeburn  1658:         if ($udom) {
                   1659:             my $uname = &get_domainconfiguser($udom); 
                   1660:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1661:         }
                   1662:     }
                   1663: }
                   1664: 
1.1023    raeburn  1665: # ----------------------------------construct domainconfig user for a domain 
                   1666: sub get_domainconfiguser {
                   1667:     my ($udom) = @_;
                   1668:     return $udom.'-domainconfig';
                   1669: }
                   1670: 
1.837     raeburn  1671: sub retrieve_inst_usertypes {
                   1672:     my ($udom) = @_;
                   1673:     my (%returnhash,@order);
1.989     raeburn  1674:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1675:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1676:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1677:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1678:         @order = @{$domdefs{'inststatusorder'}};
                   1679:     } else {
                   1680:         if (defined(&domain($udom,'primary'))) {
                   1681:             my $uhome=&domain($udom,'primary');
                   1682:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1683:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1684:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1685:                 return (\%returnhash,\@order);
                   1686:             }
                   1687:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1688:             my @pairs=split(/\&/,$hashitems);
                   1689:             foreach my $item (@pairs) {
                   1690:                 my ($key,$value)=split(/=/,$item,2);
                   1691:                 $key = &unescape($key);
                   1692:                 next if ($key =~ /^error: 2 /);
                   1693:                 $returnhash{$key}=&thaw_unescape($value);
                   1694:             }
                   1695:             my @esc_order = split(/\&/,$orderitems);
                   1696:             foreach my $item (@esc_order) {
                   1697:                 push(@order,&unescape($item));
                   1698:             }
                   1699:         } else {
                   1700:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1701:         }
                   1702:     }
                   1703:     return (\%returnhash,\@order);
                   1704: }
                   1705: 
1.868     raeburn  1706: sub is_domainimage {
                   1707:     my ($url) = @_;
                   1708:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1709:         if (&domain($1) ne '') {
                   1710:             return '1';
                   1711:         }
                   1712:     }
                   1713:     return;
                   1714: }
                   1715: 
1.899     raeburn  1716: sub inst_directory_query {
                   1717:     my ($srch) = @_;
                   1718:     my $udom = $srch->{'srchdomain'};
                   1719:     my %results;
                   1720:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1721:     my $outcome;
1.899     raeburn  1722:     if ($homeserver ne '') {
1.904     albertel 1723: 	my $queryid=&reply("querysend:instdirsearch:".
                   1724: 			   &escape($srch->{'srchby'}).':'.
                   1725: 			   &escape($srch->{'srchterm'}).':'.
                   1726: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1727: 	my $host=&hostname($homeserver);
                   1728: 	if ($queryid !~/^\Q$host\E\_/) {
                   1729: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1730: 	    return;
                   1731: 	}
                   1732: 	my $response = &get_query_reply($queryid);
                   1733: 	my $maxtries = 5;
                   1734: 	my $tries = 1;
                   1735: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1736: 	    $response = &get_query_reply($queryid);
                   1737: 	    $tries ++;
                   1738: 	}
                   1739: 
                   1740:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1741:             if ($response eq 'unavailable') {
                   1742:                 $outcome = $response;
                   1743:             } else {
                   1744:                 $outcome = 'ok';
                   1745:                 my @matches = split(/\n/,$response);
                   1746:                 foreach my $match (@matches) {
                   1747:                     my ($key,$value) = split(/=/,$match);
                   1748:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1749:                 }
1.899     raeburn  1750:             }
                   1751:         }
                   1752:     }
1.909     raeburn  1753:     return ($outcome,%results);
1.899     raeburn  1754: }
                   1755: 
                   1756: sub usersearch {
                   1757:     my ($srch) = @_;
                   1758:     my $dom = $srch->{'srchdomain'};
                   1759:     my %results;
                   1760:     my %libserv = &all_library();
                   1761:     my $query = 'usersearch';
                   1762:     foreach my $tryserver (keys(%libserv)) {
                   1763:         if (&host_domain($tryserver) eq $dom) {
                   1764:             my $host=&hostname($tryserver);
                   1765:             my $queryid=
1.911     raeburn  1766:                 &reply("querysend:".&escape($query).':'.
                   1767:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1768:                        &escape($srch->{'srchtype'}).':'.
                   1769:                        &escape($srch->{'srchterm'}),$tryserver);
                   1770:             if ($queryid !~/^\Q$host\E\_/) {
                   1771:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1772:                 next;
1.899     raeburn  1773:             }
                   1774:             my $reply = &get_query_reply($queryid);
                   1775:             my $maxtries = 1;
                   1776:             my $tries = 1;
                   1777:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1778:                 $reply = &get_query_reply($queryid);
                   1779:                 $tries ++;
                   1780:             }
                   1781:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1782:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1783:             } else {
1.911     raeburn  1784:                 my @matches;
                   1785:                 if ($reply =~ /\n/) {
                   1786:                     @matches = split(/\n/,$reply);
                   1787:                 } else {
                   1788:                     @matches = split(/\&/,$reply);
                   1789:                 }
1.899     raeburn  1790:                 foreach my $match (@matches) {
                   1791:                     my ($uname,$udom,%userhash);
1.911     raeburn  1792:                     foreach my $entry (split(/:/,$match)) {
                   1793:                         my ($key,$value) =
                   1794:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1795:                         $userhash{$key} = $value;
                   1796:                         if ($key eq 'username') {
                   1797:                             $uname = $value;
                   1798:                         } elsif ($key eq 'domain') {
                   1799:                             $udom = $value;
1.911     raeburn  1800:                         }
1.899     raeburn  1801:                     }
                   1802:                     $results{$uname.':'.$udom} = \%userhash;
                   1803:                 }
                   1804:             }
                   1805:         }
                   1806:     }
                   1807:     return %results;
                   1808: }
                   1809: 
1.912     raeburn  1810: sub get_instuser {
                   1811:     my ($udom,$uname,$id) = @_;
                   1812:     my $homeserver = &domain($udom,'primary');
                   1813:     my ($outcome,%results);
                   1814:     if ($homeserver ne '') {
                   1815:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1816:                            &escape($id).':'.&escape($udom),$homeserver);
                   1817:         my $host=&hostname($homeserver);
                   1818:         if ($queryid !~/^\Q$host\E\_/) {
                   1819:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1820:             return;
                   1821:         }
                   1822:         my $response = &get_query_reply($queryid);
                   1823:         my $maxtries = 5;
                   1824:         my $tries = 1;
                   1825:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1826:             $response = &get_query_reply($queryid);
                   1827:             $tries ++;
                   1828:         }
                   1829:         if (!&error($response) && $response ne 'refused') {
                   1830:             if ($response eq 'unavailable') {
                   1831:                 $outcome = $response;
                   1832:             } else {
                   1833:                 $outcome = 'ok';
                   1834:                 my @matches = split(/\n/,$response);
                   1835:                 foreach my $match (@matches) {
                   1836:                     my ($key,$value) = split(/=/,$match);
                   1837:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1838:                 }
                   1839:             }
                   1840:         }
                   1841:     }
                   1842:     my %userinfo;
                   1843:     if (ref($results{$uname}) eq 'HASH') {
                   1844:         %userinfo = %{$results{$uname}};
                   1845:     } 
                   1846:     return ($outcome,%userinfo);
                   1847: }
                   1848: 
                   1849: sub inst_rulecheck {
1.923     raeburn  1850:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1851:     my %returnhash;
                   1852:     if ($udom ne '') {
                   1853:         if (ref($rules) eq 'ARRAY') {
                   1854:             @{$rules} = map {&escape($_);} (@{$rules});
                   1855:             my $rulestr = join(':',@{$rules});
                   1856:             my $homeserver=&domain($udom,'primary');
                   1857:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1858:                 my $response;
                   1859:                 if ($item eq 'username') {                
                   1860:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1861:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1862:                                               $homeserver));
1.923     raeburn  1863:                 } elsif ($item eq 'id') {
                   1864:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1865:                                               ':'.&escape($id).':'.$rulestr,
                   1866:                                               $homeserver));
1.945     raeburn  1867:                 } elsif ($item eq 'selfcreate') {
                   1868:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1869:                                                &escape($udom).':'.&escape($uname).
                   1870:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1871:                 }
1.912     raeburn  1872:                 if ($response ne 'refused') {
                   1873:                     my @pairs=split(/\&/,$response);
                   1874:                     foreach my $item (@pairs) {
                   1875:                         my ($key,$value)=split(/=/,$item,2);
                   1876:                         $key = &unescape($key);
                   1877:                         next if ($key =~ /^error: 2 /);
                   1878:                         $returnhash{$key}=&thaw_unescape($value);
                   1879:                     }
                   1880:                 }
                   1881:             }
                   1882:         }
                   1883:     }
                   1884:     return %returnhash;
                   1885: }
                   1886: 
                   1887: sub inst_userrules {
1.923     raeburn  1888:     my ($udom,$check) = @_;
1.912     raeburn  1889:     my (%ruleshash,@ruleorder);
                   1890:     if ($udom ne '') {
                   1891:         my $homeserver=&domain($udom,'primary');
                   1892:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1893:             my $response;
                   1894:             if ($check eq 'id') {
                   1895:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1896:                                  $homeserver);
1.943     raeburn  1897:             } elsif ($check eq 'email') {
                   1898:                 $response=&reply('instemailrules:'.&escape($udom),
                   1899:                                  $homeserver);
1.923     raeburn  1900:             } else {
                   1901:                 $response=&reply('instuserrules:'.&escape($udom),
                   1902:                                  $homeserver);
                   1903:             }
1.912     raeburn  1904:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1905:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1906:                 ($response ne 'no_such_host')) {
                   1907:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1908:                 my @pairs=split(/\&/,$hashitems);
                   1909:                 foreach my $item (@pairs) {
                   1910:                     my ($key,$value)=split(/=/,$item,2);
                   1911:                     $key = &unescape($key);
                   1912:                     next if ($key =~ /^error: 2 /);
                   1913:                     $ruleshash{$key}=&thaw_unescape($value);
                   1914:                 }
                   1915:                 my @esc_order = split(/\&/,$orderitems);
                   1916:                 foreach my $item (@esc_order) {
                   1917:                     push(@ruleorder,&unescape($item));
                   1918:                 }
                   1919:             }
                   1920:         }
                   1921:     }
                   1922:     return (\%ruleshash,\@ruleorder);
                   1923: }
                   1924: 
1.976     raeburn  1925: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1926: 
                   1927: sub get_domain_defaults {
                   1928:     my ($domain) = @_;
                   1929:     my $cachetime = 60*60*24;
                   1930:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1931:     if (defined($cached)) {
                   1932:         if (ref($result) eq 'HASH') {
                   1933:             return %{$result};
                   1934:         }
                   1935:     }
                   1936:     my %domdefaults;
                   1937:     my %domconfig =
1.989     raeburn  1938:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1939:                                   'requestcourses','inststatus',
1.1172.2.9! raeburn  1940:                                   'coursedefaults','usersessions',
        !          1941:                                   'requestauthor'],$domain);
1.943     raeburn  1942:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1943:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1944:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1945:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1946:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1947:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  1948:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1949:     } else {
                   1950:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1951:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1952:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1953:     }
1.976     raeburn  1954:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1955:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1956:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1957:         } else {
                   1958:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1959:         } 
1.1172.2.6  raeburn  1960:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  1961:         foreach my $item (@usertools) {
                   1962:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1963:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1964:             }
                   1965:         }
                   1966:     }
1.985     raeburn  1967:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1968:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1969:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1970:         }
                   1971:     }
1.1172.2.9! raeburn  1972:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
        !          1973:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
        !          1974:     }
1.989     raeburn  1975:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1976:         foreach my $item ('inststatustypes','inststatusorder') {
                   1977:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1978:         }
                   1979:     }
1.1047    raeburn  1980:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1981:         foreach my $item ('canuse_pdfforms') {
                   1982:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1983:         }
                   1984:     }
1.1073    raeburn  1985:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1986:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1987:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1988:         }
                   1989:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1990:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1991:         }
                   1992:     }
1.943     raeburn  1993:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1994:                                   $cachetime);
                   1995:     return %domdefaults;
                   1996: }
                   1997: 
1.344     www      1998: # --------------------------------------------------- Assign a key to a student
                   1999: 
                   2000: sub assign_access_key {
1.364     www      2001: #
                   2002: # a valid key looks like uname:udom#comments
                   2003: # comments are being appended
                   2004: #
1.498     www      2005:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2006:     $kdom=
1.620     albertel 2007:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2008:     $knum=
1.620     albertel 2009:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2010:     $cdom=
1.620     albertel 2011:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2012:     $cnum=
1.620     albertel 2013:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2014:     $udom=$env{'user.name'} unless (defined($udom));
                   2015:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2016:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2017:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2018:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2019:                                                   # assigned to this person
                   2020:                                                   # - this should not happen,
1.345     www      2021:                                                   # unless something went wrong
                   2022:                                                   # the first time around
                   2023: # ready to assign
1.364     www      2024:         $logentry=$1.'; '.$logentry;
1.496     www      2025:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2026:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2027: # key now belongs to user
1.346     www      2028: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2029:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2030:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2031:                 return 'ok';
                   2032:             } else {
                   2033:                 return 
                   2034:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2035: 	    }
                   2036:         } else {
                   2037:             return 'error: Could not assign key, try again later.';
                   2038:         }
1.364     www      2039:     } elsif (!$existing{$ckey}) {
1.345     www      2040: # the key does not exist
                   2041: 	return 'error: The key does not exist';
                   2042:     } else {
                   2043: # the key is somebody else's
                   2044: 	return 'error: The key is already in use';
                   2045:     }
1.344     www      2046: }
                   2047: 
1.364     www      2048: # ------------------------------------------ put an additional comment on a key
                   2049: 
                   2050: sub comment_access_key {
                   2051: #
                   2052: # a valid key looks like uname:udom#comments
                   2053: # comments are being appended
                   2054: #
                   2055:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2056:     $cdom=
1.620     albertel 2057:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2058:     $cnum=
1.620     albertel 2059:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2060:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2061:     if ($existing{$ckey}) {
                   2062:         $existing{$ckey}.='; '.$logentry;
                   2063: # ready to assign
1.367     www      2064:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2065:                                                  $cdom,$cnum) eq 'ok') {
                   2066: 	    return 'ok';
                   2067:         } else {
                   2068: 	    return 'error: Count not store comment.';
                   2069:         }
                   2070:     } else {
                   2071: # the key does not exist
                   2072: 	return 'error: The key does not exist';
                   2073:     }
                   2074: }
                   2075: 
1.344     www      2076: # ------------------------------------------------------ Generate a set of keys
                   2077: 
                   2078: sub generate_access_keys {
1.364     www      2079:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2080:     $cdom=
1.620     albertel 2081:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2082:     $cnum=
1.620     albertel 2083:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2084:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2085:     unless (($cdom) && ($cnum)) { return 0; }
                   2086:     if ($number>10000) { return 0; }
                   2087:     sleep(2); # make sure don't get same seed twice
                   2088:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2089:     my $total=0;
                   2090:     for (my $i=1;$i<=$number;$i++) {
                   2091:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2092:                   sprintf("%lx",int(100000*rand)).'-'.
                   2093:                   sprintf("%lx",int(100000*rand));
                   2094:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2095:        $newkey=~s/0/h/g; # and also 0 and O
                   2096:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2097:        if ($existing{$newkey}) {
                   2098:            $i--;
                   2099:        } else {
1.364     www      2100: 	  if (&put('accesskeys',
                   2101:               { $newkey => '# generated '.localtime().
1.620     albertel 2102:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2103:                            '; '.$logentry },
                   2104: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2105:               $total++;
                   2106: 	  }
                   2107:        }
                   2108:     }
1.620     albertel 2109:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2110:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2111:     return $total;
                   2112: }
                   2113: 
                   2114: # ------------------------------------------------------- Validate an accesskey
                   2115: 
                   2116: sub validate_access_key {
                   2117:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2118:     $cdom=
1.620     albertel 2119:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2120:     $cnum=
1.620     albertel 2121:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2122:     $udom=$env{'user.domain'} unless (defined($udom));
                   2123:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2124:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2125:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2126: }
                   2127: 
                   2128: # ------------------------------------- Find the section of student in a course
1.652     albertel 2129: sub devalidate_getsection_cache {
                   2130:     my ($udom,$unam,$courseid)=@_;
                   2131:     my $hashid="$udom:$unam:$courseid";
                   2132:     &devalidate_cache_new('getsection',$hashid);
                   2133: }
1.298     matthew  2134: 
1.815     albertel 2135: sub courseid_to_courseurl {
                   2136:     my ($courseid) = @_;
                   2137:     #already url style courseid
                   2138:     return $courseid if ($courseid =~ m{^/});
                   2139: 
                   2140:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2141: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2142: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2143: 	return "/$cdom/$cnum";
                   2144:     }
                   2145: 
                   2146:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2147:     if (exists($courseinfo{'num'})) {
                   2148: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2149:     }
                   2150: 
                   2151:     return undef;
                   2152: }
                   2153: 
1.298     matthew  2154: sub getsection {
                   2155:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2156:     my $cachetime=1800;
1.551     albertel 2157: 
                   2158:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2159:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2160:     if (defined($cached)) { return $result; }
                   2161: 
1.298     matthew  2162:     my %Pending; 
                   2163:     my %Expired;
                   2164:     #
                   2165:     # Each role can either have not started yet (pending), be active, 
                   2166:     #    or have expired.
                   2167:     #
                   2168:     # If there is an active role, we are done.
                   2169:     #
                   2170:     # If there is more than one role which has not started yet, 
                   2171:     #     choose the one which will start sooner
                   2172:     # If there is one role which has not started yet, return it.
                   2173:     #
                   2174:     # If there is more than one expired role, choose the one which ended last.
                   2175:     # If there is a role which has expired, return it.
                   2176:     #
1.815     albertel 2177:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2178:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2179:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2180:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2181:         my $section=$1;
                   2182:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2183:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2184:         my $now=time;
1.548     albertel 2185:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2186:             $Expired{$end}=$section;
                   2187:             next;
                   2188:         }
1.548     albertel 2189:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2190:             $Pending{$start}=$section;
                   2191:             next;
                   2192:         }
1.599     albertel 2193:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2194:     }
                   2195:     #
                   2196:     # Presumedly there will be few matching roles from the above
                   2197:     # loop and the sorting time will be negligible.
                   2198:     if (scalar(keys(%Pending))) {
                   2199:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2200:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2201:     } 
                   2202:     if (scalar(keys(%Expired))) {
                   2203:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2204:         my $time = pop(@sorted);
1.599     albertel 2205:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2206:     }
1.599     albertel 2207:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2208: }
1.70      www      2209: 
1.599     albertel 2210: sub save_cache {
                   2211:     &purge_remembered();
1.722     albertel 2212:     #&Apache::loncommon::validate_page();
1.620     albertel 2213:     undef(%env);
1.780     albertel 2214:     undef($env_loaded);
1.599     albertel 2215: }
1.452     albertel 2216: 
1.599     albertel 2217: my $to_remember=-1;
                   2218: my %remembered;
                   2219: my %accessed;
                   2220: my $kicks=0;
                   2221: my $hits=0;
1.849     albertel 2222: sub make_key {
                   2223:     my ($name,$id) = @_;
1.872     albertel 2224:     if (length($id) > 65 
                   2225: 	&& length(&escape($id)) > 200) {
                   2226: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2227:     }
1.849     albertel 2228:     return &escape($name.':'.$id);
                   2229: }
                   2230: 
1.599     albertel 2231: sub devalidate_cache_new {
                   2232:     my ($name,$id,$debug) = @_;
                   2233:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2234:     $id=&make_key($name,$id);
1.599     albertel 2235:     $memcache->delete($id);
                   2236:     delete($remembered{$id});
                   2237:     delete($accessed{$id});
                   2238: }
                   2239: 
                   2240: sub is_cached_new {
                   2241:     my ($name,$id,$debug) = @_;
1.849     albertel 2242:     $id=&make_key($name,$id);
1.599     albertel 2243:     if (exists($remembered{$id})) {
1.1133    foxr     2244: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2245: 	$accessed{$id}=[&gettimeofday()];
                   2246: 	$hits++;
                   2247: 	return ($remembered{$id},1);
                   2248:     }
                   2249:     my $value = $memcache->get($id);
                   2250:     if (!(defined($value))) {
                   2251: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2252: 	return (undef,undef);
1.416     albertel 2253:     }
1.599     albertel 2254:     if ($value eq '__undef__') {
                   2255: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2256: 	$value=undef;
                   2257:     }
                   2258:     &make_room($id,$value,$debug);
                   2259:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2260:     return ($value,1);
                   2261: }
                   2262: 
                   2263: sub do_cache_new {
                   2264:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2265:     $id=&make_key($name,$id);
1.599     albertel 2266:     my $setvalue=$value;
                   2267:     if (!defined($setvalue)) {
                   2268: 	$setvalue='__undef__';
                   2269:     }
1.623     albertel 2270:     if (!defined($time) ) {
                   2271: 	$time=600;
                   2272:     }
1.599     albertel 2273:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2274:     my $result = $memcache->set($id,$setvalue,$time);
                   2275:     if (! $result) {
1.872     albertel 2276: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2277: 	$memcache->disconnect_all();
1.872     albertel 2278:     }
1.600     albertel 2279:     # need to make a copy of $value
1.919     albertel 2280:     &make_room($id,$value,$debug);
1.599     albertel 2281:     return $value;
                   2282: }
                   2283: 
                   2284: sub make_room {
                   2285:     my ($id,$value,$debug)=@_;
1.919     albertel 2286: 
                   2287:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2288:                                     : $value;
1.599     albertel 2289:     if ($to_remember<0) { return; }
                   2290:     $accessed{$id}=[&gettimeofday()];
                   2291:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2292:     my $to_kick;
                   2293:     my $max_time=0;
                   2294:     foreach my $other (keys(%accessed)) {
                   2295: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2296: 	    $to_kick=$other;
                   2297: 	    $max_time=&tv_interval($accessed{$other});
                   2298: 	}
                   2299:     }
                   2300:     delete($remembered{$to_kick});
                   2301:     delete($accessed{$to_kick});
                   2302:     $kicks++;
                   2303:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2304:     return;
                   2305: }
                   2306: 
1.599     albertel 2307: sub purge_remembered {
1.604     albertel 2308:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2309:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2310:     undef(%remembered);
                   2311:     undef(%accessed);
1.428     albertel 2312: }
1.70      www      2313: # ------------------------------------- Read an entry from a user's environment
                   2314: 
                   2315: sub userenvironment {
                   2316:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2317:     my $items;
                   2318:     foreach my $item (@what) {
                   2319:         $items.=&escape($item).'&';
                   2320:     }
                   2321:     $items=~s/\&$//;
1.70      www      2322:     my %returnhash=();
1.1009    raeburn  2323:     my $uhome = &homeserver($unam,$udom);
                   2324:     unless ($uhome eq 'no_host') {
                   2325:         my @answer=split(/\&/, 
                   2326:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2327:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2328:             return %returnhash;
                   2329:         }
1.1009    raeburn  2330:         my $i;
                   2331:         for ($i=0;$i<=$#what;$i++) {
                   2332: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2333:         }
1.70      www      2334:     }
                   2335:     return %returnhash;
1.1       albertel 2336: }
                   2337: 
1.617     albertel 2338: # ---------------------------------------------------------- Get a studentphoto
                   2339: sub studentphoto {
                   2340:     my ($udom,$unam,$ext) = @_;
                   2341:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2342:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2343:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2344:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2345:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2346:             } else {
                   2347:                 my ($result,$perm_reqd)=
1.707     albertel 2348: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2349:                 if ($result eq 'ok') {
                   2350:                     if (!($perm_reqd eq 'yes')) {
                   2351:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2352:                     }
                   2353:                 }
                   2354:             }
                   2355:         }
                   2356:     } else {
                   2357:         my ($result,$perm_reqd) = 
1.707     albertel 2358: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2359:         if ($result eq 'ok') {
                   2360:             if (!($perm_reqd eq 'yes')) {
                   2361:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2362:             }
                   2363:         }
                   2364:     }
                   2365:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2366: }
                   2367: 
                   2368: sub retrievestudentphoto {
                   2369:     my ($udom,$unam,$ext,$type) = @_;
                   2370:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2371:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2372:     if ($ret eq 'ok') {
                   2373:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2374:         if ($type eq 'thumbnail') {
                   2375:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2376:         }
                   2377:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2378:         return $tokenurl;
                   2379:     } else {
                   2380:         if ($type eq 'thumbnail') {
                   2381:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2382:         } else { 
                   2383:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2384:         }
1.617     albertel 2385:     }
                   2386: }
                   2387: 
1.263     www      2388: # -------------------------------------------------------------------- New chat
                   2389: 
                   2390: sub chatsend {
1.724     raeburn  2391:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2392:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2393:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2394:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2395:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2396: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2397: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2398: }
                   2399: 
                   2400: # ------------------------------------------ Find current version of a resource
                   2401: 
                   2402: sub getversion {
                   2403:     my $fname=&clutter(shift);
                   2404:     unless ($fname=~/^\/res\//) { return -1; }
                   2405:     return &currentversion(&filelocation('',$fname));
                   2406: }
                   2407: 
                   2408: sub currentversion {
                   2409:     my $fname=shift;
                   2410:     my $author=$fname;
                   2411:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2412:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2413:     my $home=&homeserver($uname,$udom);
1.292     www      2414:     if ($home eq 'no_host') { 
                   2415:         return -1; 
                   2416:     }
1.1112    www      2417:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2418:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2419: 	return -1;
                   2420:     }
1.1112    www      2421:     return $answer;
1.263     www      2422: }
                   2423: 
1.1111    www      2424: #
                   2425: # Return special version number of resource if set by override, empty otherwise
                   2426: #
                   2427: sub usedversion {
                   2428:     my $fname=shift;
                   2429:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2430:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2431:     if ($urlversion) { return $urlversion; }
                   2432:     return '';
                   2433: }
                   2434: 
1.1       albertel 2435: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2436: 
1.1       albertel 2437: sub subscribe {
                   2438:     my $fname=shift;
1.761     raeburn  2439:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2440:     $fname=~s/[\n\r]//g;
1.1       albertel 2441:     my $author=$fname;
                   2442:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2443:     my ($udom,$uname)=split(/\//,$author);
                   2444:     my $home=homeserver($uname,$udom);
1.335     albertel 2445:     if ($home eq 'no_host') {
                   2446:         return 'not_found';
1.1       albertel 2447:     }
                   2448:     my $answer=reply("sub:$fname",$home);
1.64      www      2449:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2450: 	$answer.=' by '.$home;
                   2451:     }
1.1       albertel 2452:     return $answer;
                   2453: }
                   2454:     
1.8       www      2455: # -------------------------------------------------------------- Replicate file
                   2456: 
                   2457: sub repcopy {
                   2458:     my $filename=shift;
1.23      www      2459:     $filename=~s/\/+/\//g;
1.1142    raeburn  2460:     my $londocroot = $perlvar{'lonDocRoot'};
                   2461:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2462:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2463:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2464: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2465: 	return &repcopy_userfile($filename);
                   2466:     }
1.532     albertel 2467:     $filename=~s/[\n\r]//g;
1.8       www      2468:     my $transname="$filename.in.transfer";
1.828     www      2469: # FIXME: this should flock
1.607     raeburn  2470:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2471:     my $remoteurl=subscribe($filename);
1.64      www      2472:     if ($remoteurl =~ /^con_lost by/) {
                   2473: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2474:            return 'unavailable';
1.8       www      2475:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2476: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2477: 	   return 'not_found';
1.64      www      2478:     } elsif ($remoteurl =~ /^rejected by/) {
                   2479: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2480:            return 'forbidden';
1.20      www      2481:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2482:            return 'ok';
1.8       www      2483:     } else {
1.290     www      2484:         my $author=$filename;
                   2485:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2486:         my ($udom,$uname)=split(/\//,$author);
                   2487:         my $home=homeserver($uname,$udom);
                   2488:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2489:            my @parts=split(/\//,$filename);
                   2490:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2491:            if ($path ne "$londocroot/res") {
1.8       www      2492:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2493: 	       return 'bad_request';
1.8       www      2494:            }
                   2495:            my $count;
                   2496:            for ($count=5;$count<$#parts;$count++) {
                   2497:                $path.="/$parts[$count]";
                   2498:                if ((-e $path)!=1) {
                   2499: 		   mkdir($path,0777);
                   2500:                }
                   2501:            }
                   2502:            my $ua=new LWP::UserAgent;
                   2503:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2504:            my $response=$ua->request($request,$transname);
                   2505:            if ($response->is_error()) {
                   2506: 	       unlink($transname);
                   2507:                my $message=$response->status_line;
1.672     albertel 2508:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2509:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2510:                return 'unavailable';
1.8       www      2511:            } else {
1.16      www      2512: 	       if ($remoteurl!~/\.meta$/) {
                   2513:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2514:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2515:                   if ($mresponse->is_error()) {
                   2516: 		      unlink($filename.'.meta');
                   2517:                       &logthis(
1.672     albertel 2518:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2519:                   }
                   2520: 	       }
1.8       www      2521:                rename($transname,$filename);
1.607     raeburn  2522:                return 'ok';
1.8       www      2523:            }
1.290     www      2524:        }
1.8       www      2525:     }
1.330     www      2526: }
                   2527: 
                   2528: # ------------------------------------------------ Get server side include body
                   2529: sub ssi_body {
1.381     albertel 2530:     my ($filelink,%form)=@_;
1.606     matthew  2531:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2532:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2533:     }
1.953     www      2534:     my $output='';
                   2535:     my $response;
1.980     raeburn  2536:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2537:        ($output,$response)=&externalssi($filelink);
1.953     www      2538:     } else {
1.1004    droeschl 2539:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2540:        $filelink .= 'inhibitmenu=yes';
1.953     www      2541:        ($output,$response)=&ssi($filelink,%form);
                   2542:     }
1.778     albertel 2543:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2544:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2545:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2546:     if (wantarray) {
                   2547:         return ($output, $response);
                   2548:     } else {
                   2549:         return $output;
                   2550:     }
1.8       www      2551: }
                   2552: 
1.15      www      2553: # --------------------------------------------------------- Server Side Include
                   2554: 
1.782     albertel 2555: sub absolute_url {
                   2556:     my ($host_name) = @_;
                   2557:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2558:     if ($host_name eq '') {
                   2559: 	$host_name = $ENV{'SERVER_NAME'};
                   2560:     }
                   2561:     return $protocol.$host_name;
                   2562: }
                   2563: 
1.942     foxr     2564: #
                   2565: #   Server side include.
                   2566: # Parameters:
                   2567: #  fn     Possibly encrypted resource name/id.
                   2568: #  form   Hash that describes how the rendering should be done
                   2569: #         and other things.
1.944     foxr     2570: # Returns:
1.950     raeburn  2571: #   Scalar context: The content of the response.
                   2572: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2573: #     
1.15      www      2574: sub ssi {
                   2575: 
1.944     foxr     2576:     my ($fn,%form)=@_;
1.15      www      2577:     my $ua=new LWP::UserAgent;
1.23      www      2578:     my $request;
1.711     albertel 2579: 
                   2580:     $form{'no_update_last_known'}=1;
1.895     albertel 2581:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2582:     if (%form) {
1.782     albertel 2583:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2584:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2585:     } else {
1.782     albertel 2586:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2587:     }
                   2588: 
1.15      www      2589:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.2  raeburn  2590:     my $response= $ua->request($request);
1.944     foxr     2591:     if (wantarray) {
1.1172.2.3  raeburn  2592: 	return ($response->content, $response);
1.944     foxr     2593:     } else {
1.1172.2.3  raeburn  2594: 	return $response->content;
1.942     foxr     2595:     }
1.324     www      2596: }
                   2597: 
                   2598: sub externalssi {
                   2599:     my ($url)=@_;
                   2600:     my $ua=new LWP::UserAgent;
                   2601:     my $request=new HTTP::Request('GET',$url);
                   2602:     my $response=$ua->request($request);
1.954     raeburn  2603:     if (wantarray) {
                   2604:         return ($response->content, $response);
                   2605:     } else {
                   2606:         return $response->content;
                   2607:     }
1.15      www      2608: }
1.254     www      2609: 
1.492     albertel 2610: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2611: 
                   2612: sub allowuploaded {
                   2613:     my ($srcurl,$url)=@_;
                   2614:     $url=&clutter(&declutter($url));
                   2615:     my $dir=$url;
                   2616:     $dir=~s/\/[^\/]+$//;
                   2617:     my %httpref=();
                   2618:     my $httpurl=&hreflocation('',$url);
                   2619:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2620:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2621: }
1.477     raeburn  2622: 
1.478     albertel 2623: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2624: # input: action, courseID, current domain, intended
1.637     raeburn  2625: #        path to file, source of file, instruction to parse file for objects,
                   2626: #        ref to hash for embedded objects,
                   2627: #        ref to hash for codebase of java objects.
1.1095    raeburn  2628: #        reference to scalar to accommodate mime type determined
                   2629: #          from File::MMagic if $parser = parse.
1.637     raeburn  2630: #
1.485     raeburn  2631: # output: url to file (if action was uploaddoc), 
                   2632: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2633: #
1.478     albertel 2634: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2635: # course.
1.477     raeburn  2636: #
1.478     albertel 2637: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2638: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2639: #          course's home server.
1.477     raeburn  2640: #
1.478     albertel 2641: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2642: #          be copied from $source (current location) to 
                   2643: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2644: #         and will then be copied to
                   2645: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2646: #         course's home server.
1.485     raeburn  2647: #
1.481     raeburn  2648: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2649: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2650: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2651: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2652: #         in course's home server.
1.637     raeburn  2653: #
1.477     raeburn  2654: 
                   2655: sub process_coursefile {
1.1095    raeburn  2656:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2657:         $mimetype)=@_;
1.477     raeburn  2658:     my $fetchresult;
1.638     albertel 2659:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2660:     if ($action eq 'propagate') {
1.638     albertel 2661:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2662: 			     $home);
1.481     raeburn  2663:     } else {
1.477     raeburn  2664:         my $fpath = '';
                   2665:         my $fname = $file;
1.478     albertel 2666:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2667:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2668:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2669:         if ($action eq 'copy') {
                   2670:             if ($source eq '') {
                   2671:                 $fetchresult = 'no source file';
                   2672:                 return $fetchresult;
                   2673:             } else {
                   2674:                 my $destination = $filepath.'/'.$fname;
                   2675:                 rename($source,$destination);
                   2676:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2677:                                  $home);
1.481     raeburn  2678:             }
                   2679:         } elsif ($action eq 'uploaddoc') {
                   2680:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2681:             print $fh $env{'form.'.$source};
1.481     raeburn  2682:             close($fh);
1.637     raeburn  2683:             if ($parser eq 'parse') {
1.1024    raeburn  2684:                 my $mm = new File::MMagic;
1.1095    raeburn  2685:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2686:                 if ($type eq 'text/html') {
1.1024    raeburn  2687:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2688:                     unless ($parse_result eq 'ok') {
                   2689:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2690:                     }
1.637     raeburn  2691:                 }
1.1095    raeburn  2692:                 if (ref($mimetype)) {
                   2693:                     $$mimetype = $type;
                   2694:                 } 
1.637     raeburn  2695:             }
1.477     raeburn  2696:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2697:                                  $home);
1.481     raeburn  2698:             if ($fetchresult eq 'ok') {
                   2699:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2700:             } else {
                   2701:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2702:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2703:                 return '/adm/notfound.html';
                   2704:             }
1.477     raeburn  2705:         }
                   2706:     }
1.485     raeburn  2707:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2708:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2709:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2710:     }
                   2711:     return $fetchresult;
                   2712: }
                   2713: 
1.637     raeburn  2714: sub build_filepath {
                   2715:     my ($fpath) = @_;
                   2716:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2717:     unless ($fpath eq '') {
                   2718:         my @parts=split('/',$fpath);
                   2719:         foreach my $part (@parts) {
                   2720:             $filepath.= '/'.$part;
                   2721:             if ((-e $filepath)!=1) {
                   2722:                 mkdir($filepath,0777);
                   2723:             }
                   2724:         }
                   2725:     }
                   2726:     return $filepath;
                   2727: }
                   2728: 
                   2729: sub store_edited_file {
1.638     albertel 2730:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2731:     my $file = $primary_url;
                   2732:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2733:     my $fpath = '';
                   2734:     my $fname = $file;
                   2735:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2736:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2737:     my $filepath = &build_filepath($fpath);
                   2738:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2739:     print $fh $content;
                   2740:     close($fh);
1.638     albertel 2741:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2742:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2743: 			  $home);
1.637     raeburn  2744:     if ($$fetchresult eq 'ok') {
                   2745:         return '/uploaded/'.$fpath.'/'.$fname;
                   2746:     } else {
1.638     albertel 2747:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2748: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2749:         return '/adm/notfound.html';
                   2750:     }
                   2751: }
                   2752: 
1.531     albertel 2753: sub clean_filename {
1.831     albertel 2754:     my ($fname,$args)=@_;
1.315     www      2755: # Replace Windows backslashes by forward slashes
1.257     www      2756:     $fname=~s/\\/\//g;
1.831     albertel 2757:     if (!$args->{'keep_path'}) {
                   2758:         # Get rid of everything but the actual filename
                   2759: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2760:     }
1.315     www      2761: # Replace spaces by underscores
                   2762:     $fname=~s/\s+/\_/g;
                   2763: # Replace all other weird characters by nothing
1.831     albertel 2764:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2765: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2766: # numbers
                   2767:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2768:     return $fname;
                   2769: }
1.1051    raeburn  2770: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2771: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2772: # image with the same aspect ratio as the original, but with dimensions which do 
                   2773: # not exceed $resizewidth and $resizeheight.
                   2774:  
1.984     neumanie 2775: sub resizeImage {
1.1051    raeburn  2776:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2777:     my $ima = Image::Magick->new;
                   2778:     my $resized;
                   2779:     if (-e $img_path) {
                   2780:         $ima->Read($img_path);
                   2781:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2782:             my $width = $ima->Get('width');
                   2783:             my $height = $ima->Get('height');
                   2784:             if ($width > $resizewidth) {
                   2785: 	        my $factor = $width/$resizewidth;
                   2786:                 my $newheight = $height/$factor;
                   2787:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2788:                 $resized = 1;
                   2789:             }
                   2790:         }
                   2791:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2792:             my $width = $ima->Get('width');
                   2793:             my $height = $ima->Get('height');
                   2794:             if ($height > $resizeheight) {
                   2795:                 my $factor = $height/$resizeheight;
                   2796:                 my $newwidth = $width/$factor;
                   2797:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2798:                 $resized = 1;
                   2799:             }
                   2800:         }
                   2801:         if ($resized) {
                   2802:             $ima->Write($img_path);
                   2803:         }
                   2804:     }
                   2805:     return;
1.977     amueller 2806: }
                   2807: 
1.608     albertel 2808: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2809: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2810: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2811: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2812: #                                    canceloverwrite, or ''. 
                   2813: #                   if 'coursedoc': upload to the current course
                   2814: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2815: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2816: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2817: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2818: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2819: #        $allfiles - reference to hash for embedded objects
                   2820: #        $codebase - reference to hash for codebase of java objects
                   2821: #        $desuname - username for permanent storage of uploaded file
                   2822: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2823: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2824: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2825: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2826: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2827: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  2828: #                    from File::MMagic.
1.858     raeburn  2829: # 
1.686     albertel 2830: # output: url of file in userspace, or error: <message> 
                   2831: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2832: 
1.531     albertel 2833: sub userfileupload {
1.1090    raeburn  2834:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2835:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2836:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2837:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2838:     $fname=&clean_filename($fname);
1.1090    raeburn  2839:     # See if there is anything left
1.257     www      2840:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2841:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2842:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2843:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2844:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2845:         my $now = time;
1.1090    raeburn  2846:         my $filepath;
1.1095    raeburn  2847:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2848:              $filepath = 'tmp/helprequests/'.$now;
                   2849:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2850:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2851:                          '_'.$env{'user.domain'}.'/pending';
                   2852:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2853:             my ($docuname,$docudom);
                   2854:             if ($destudom) {
                   2855:                 $docudom = $destudom;
                   2856:             } else {
                   2857:                 $docudom = $env{'user.domain'};
                   2858:             }
                   2859:             if ($destuname) {
                   2860:                 $docuname = $destuname;
                   2861:             } else {
                   2862:                 $docuname = $env{'user.name'};
                   2863:             }
                   2864:             if (exists($env{'form.group'})) {
                   2865:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2866:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2867:             }
                   2868:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2869:             if ($context eq 'canceloverwrite') {
                   2870:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2871:                 if (-e  $tempfile) {
                   2872:                     my @info = stat($tempfile);
                   2873:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2874:                         unlink($tempfile);
                   2875:                     }
                   2876:                 }
                   2877:                 return;
1.523     raeburn  2878:             }
                   2879:         }
1.1090    raeburn  2880:         # Create the directory if not present
1.741     raeburn  2881:         my @parts=split(/\//,$filepath);
                   2882:         my $fullpath = $perlvar{'lonDaemons'};
                   2883:         for (my $i=0;$i<@parts;$i++) {
                   2884:             $fullpath .= '/'.$parts[$i];
                   2885:             if ((-e $fullpath)!=1) {
                   2886:                 mkdir($fullpath,0777);
                   2887:             }
                   2888:         }
                   2889:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2890:         print $fh $env{'form.'.$formname};
                   2891:         close($fh);
1.1090    raeburn  2892:         if ($context eq 'existingfile') {
                   2893:             my @info = stat($fullpath.'/'.$fname);
                   2894:             return ($fullpath.'/'.$fname,$info[9]);
                   2895:         } else {
                   2896:             return $fullpath.'/'.$fname;
                   2897:         }
1.523     raeburn  2898:     }
1.995     raeburn  2899:     if ($subdir eq 'scantron') {
                   2900:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2901:     } else {
1.995     raeburn  2902:         $fname="$subdir/$fname";
                   2903:     }
1.1090    raeburn  2904:     if ($context eq 'coursedoc') {
1.638     albertel 2905: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2906: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2907:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2908:             return &finishuserfileupload($docuname,$docudom,
                   2909: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2910: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2911:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2912:         } else {
1.620     albertel 2913:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2914:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2915: 				       $fname,$formname,$parser,
1.1095    raeburn  2916: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2917:         }
1.719     banghart 2918:     } elsif (defined($destuname)) {
                   2919:         my $docuname=$destuname;
                   2920:         my $docudom=$destudom;
1.860     raeburn  2921: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2922: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2923:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2924:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2925:     } else {
1.638     albertel 2926:         my $docuname=$env{'user.name'};
                   2927:         my $docudom=$env{'user.domain'};
1.714     raeburn  2928:         if (exists($env{'form.group'})) {
                   2929:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2930:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2931:         }
1.860     raeburn  2932: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2933: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2934:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2935:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2936:     }
1.271     www      2937: }
                   2938: 
                   2939: sub finishuserfileupload {
1.860     raeburn  2940:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2941:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2942:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2943:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2944:   
1.860     raeburn  2945:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2946:     $file=$fname;
                   2947:     if ($fname=~m|/|) {
                   2948:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2949: 	$path.=$fnamepath.'/';
                   2950:     }
1.259     www      2951:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2952:     my $count;
                   2953:     for ($count=4;$count<=$#parts;$count++) {
                   2954:         $filepath.="/$parts[$count]";
                   2955:         if ((-e $filepath)!=1) {
                   2956: 	    mkdir($filepath,0777);
                   2957:         }
                   2958:     }
1.984     neumanie 2959: 
1.258     www      2960: # Save the file
                   2961:     {
1.701     albertel 2962: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2963: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2964: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2965: 	    return '/adm/notfound.html';
                   2966: 	}
1.1090    raeburn  2967:         if ($context eq 'overwrite') {
1.1117    foxr     2968:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2969:             my $target = $filepath.'/'.$file;
                   2970:             if (-e $source) {
                   2971:                 my @info = stat($source);
                   2972:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2973:                     unless (&File::Copy::move($source,$target)) {
                   2974:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2975:                         return "Moving from $source failed";
                   2976:                     }
                   2977:                 } else {
                   2978:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2979:                 }
                   2980:             } else {
                   2981:                 return "Temporary file: $source missing";
                   2982:             }
                   2983:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2984: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2985: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2986: 	    return '/adm/notfound.html';
                   2987: 	}
1.570     albertel 2988: 	close(FH);
1.1051    raeburn  2989:         if ($resizewidth && $resizeheight) {
                   2990:             my $mm = new File::MMagic;
                   2991:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2992:             if ($mime_type =~ m{^image/}) {
                   2993: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2994:             }  
1.977     amueller 2995: 	}
1.258     www      2996:     }
1.1152    raeburn  2997:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   2998:         if (ref($mimetype)) {
                   2999:             if ($$mimetype eq '') {
                   3000:                 my $mm = new File::MMagic;
                   3001:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3002:                 $$mimetype = $type;
                   3003:             }
                   3004:         }
                   3005:     }
1.637     raeburn  3006:     if ($parser eq 'parse') {
1.1152    raeburn  3007:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3008:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3009:                                                        $allfiles,$codebase);
                   3010:             unless ($parse_result eq 'ok') {
                   3011:                 &logthis('Failed to parse '.$filepath.$file.
                   3012: 	   	         ' for embedded media: '.$parse_result); 
                   3013:             }
1.637     raeburn  3014:         }
                   3015:     }
1.860     raeburn  3016:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3017:         my $input = $filepath.'/'.$file;
                   3018:         my $output = $filepath.'/'.'tn-'.$file;
                   3019:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3020:         system("convert -sample $thumbsize $input $output");
                   3021:         if (-e $filepath.'/'.'tn-'.$file) {
                   3022:             $fetchthumb  = 1; 
                   3023:         }
                   3024:     }
1.858     raeburn  3025:  
1.259     www      3026: # Notify homeserver to grep it
                   3027: #
1.984     neumanie 3028:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3029:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3030:     if ($fetchresult eq 'ok') {
1.860     raeburn  3031:         if ($fetchthumb) {
                   3032:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3033:             if ($thumbresult ne 'ok') {
                   3034:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3035:                          $docuhome.': '.$thumbresult);
                   3036:             }
                   3037:         }
1.259     www      3038: #
1.258     www      3039: # Return the URL to it
1.494     albertel 3040:         return '/uploaded/'.$path.$file;
1.263     www      3041:     } else {
1.494     albertel 3042:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3043: 		 ': '.$fetchresult);
1.263     www      3044:         return '/adm/notfound.html';
1.858     raeburn  3045:     }
1.493     albertel 3046: }
                   3047: 
1.637     raeburn  3048: sub extract_embedded_items {
1.961     raeburn  3049:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3050:     my @state = ();
1.1164    raeburn  3051:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3052:     my %javafiles = (
                   3053:                       codebase => '',
                   3054:                       code => '',
                   3055:                       archive => ''
                   3056:                     );
                   3057:     my %mediafiles = (
                   3058:                       src => '',
                   3059:                       movie => '',
                   3060:                      );
1.648     raeburn  3061:     my $p;
                   3062:     if ($content) {
                   3063:         $p = HTML::LCParser->new($content);
                   3064:     } else {
1.961     raeburn  3065:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3066:     }
1.641     albertel 3067:     while (my $t=$p->get_token()) {
1.640     albertel 3068: 	if ($t->[0] eq 'S') {
                   3069: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3070: 	    push(@state, $tagname);
1.648     raeburn  3071:             if (lc($tagname) eq 'allow') {
                   3072:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3073:             }
1.640     albertel 3074: 	    if (lc($tagname) eq 'img') {
                   3075: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3076: 	    }
1.886     albertel 3077: 	    if (lc($tagname) eq 'a') {
                   3078: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3079: 	    }
1.645     raeburn  3080:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3081:                 my $src;
1.645     raeburn  3082:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3083:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3084:                 } else {
1.1164    raeburn  3085:                     if ($attr->{'src'} ne '') {
                   3086:                         $src = $attr->{'src'};
                   3087:                         &add_filetype($allfiles,$src,'src');
                   3088:                     }
                   3089:                 }
                   3090:                 my $text = $p->get_trimmed_text();
                   3091:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3092:                     my @swfargs = split(/,/,$1);
                   3093:                     foreach my $item (@swfargs) {
                   3094:                         $item =~ s/["']//g;
                   3095:                         $item =~ s/^\s+//;
                   3096:                         $item =~ s/\s+$//;
                   3097:                     }
                   3098:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3099:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3100:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3101:                         } else {
                   3102:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3103:                         }
                   3104:                     }
1.645     raeburn  3105:                 }
                   3106:             }
                   3107:             if (lc($tagname) eq 'link') {
                   3108:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3109:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3110:                 }
                   3111:             }
1.640     albertel 3112: 	    if (lc($tagname) eq 'object' ||
                   3113: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3114: 		foreach my $item (keys(%javafiles)) {
                   3115: 		    $javafiles{$item} = '';
                   3116: 		}
1.1164    raeburn  3117:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3118:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3119:                 }
1.640     albertel 3120: 	    }
                   3121: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3122: 		my $name = lc($attr->{'name'});
                   3123: 		foreach my $item (keys(%javafiles)) {
                   3124: 		    if ($name eq $item) {
                   3125: 			$javafiles{$item} = $attr->{'value'};
                   3126: 			last;
                   3127: 		    }
                   3128: 		}
1.1164    raeburn  3129:                 my $pathfrom;
1.640     albertel 3130: 		foreach my $item (keys(%mediafiles)) {
                   3131: 		    if ($name eq $item) {
1.1164    raeburn  3132:                         $pathfrom = $attr->{'value'};
                   3133:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3134: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3135: 			last;
                   3136: 		    }
                   3137: 		}
1.1164    raeburn  3138:                 if ($name eq 'flashvars') {
                   3139:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3140:                 }
                   3141:                 if ($pathfrom ne '') {
                   3142:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3143:                                          $pathfrom);
                   3144:                 }
1.640     albertel 3145: 	    }
                   3146: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3147: 		foreach my $item (keys(%javafiles)) {
                   3148: 		    if ($attr->{$item}) {
                   3149: 			$javafiles{$item} = $attr->{$item};
                   3150: 			last;
                   3151: 		    }
                   3152: 		}
                   3153: 		foreach my $item (keys(%mediafiles)) {
                   3154: 		    if ($attr->{$item}) {
                   3155: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3156: 			last;
                   3157: 		    }
                   3158: 		}
1.1164    raeburn  3159:                 if (lc($tagname) eq 'embed') {
                   3160:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3161:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3162:                                              $attr->{'src'});
                   3163:                     }
                   3164:                 }
1.640     albertel 3165: 	    }
1.1164    raeburn  3166:             if ($t->[4] =~ m{/>$}) {
                   3167:                 pop(@state);  
                   3168:             }
1.640     albertel 3169: 	} elsif ($t->[0] eq 'E') {
                   3170: 	    my ($tagname) = ($t->[1]);
                   3171: 	    if ($javafiles{'codebase'} ne '') {
                   3172: 		$javafiles{'codebase'} .= '/';
                   3173: 	    }  
                   3174: 	    if (lc($tagname) eq 'applet' ||
                   3175: 		lc($tagname) eq 'object' ||
                   3176: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3177: 		) {
                   3178: 		foreach my $item (keys(%javafiles)) {
                   3179: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3180: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3181: 			&add_filetype($allfiles,$file,$item);
                   3182: 		    }
                   3183: 		}
                   3184: 	    } 
                   3185: 	    pop @state;
                   3186: 	}
                   3187:     }
1.1164    raeburn  3188:     foreach my $id (sort(keys(%flashvars))) {
                   3189:         if ($shockwave{$id} ne '') {
                   3190:             my @pairs = split(/\&/,$flashvars{$id});
                   3191:             foreach my $pair (@pairs) {
                   3192:                 my ($key,$value) = split(/\=/,$pair);
                   3193:                 if ($key eq 'thumb') {
                   3194:                     &add_filetype($allfiles,$value,$key);
                   3195:                 } elsif ($key eq 'content') {
                   3196:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3197:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3198:                     if ($ext ne '') {
                   3199:                         &add_filetype($allfiles,$path.$value,$ext);
                   3200:                     }
                   3201:                 }
                   3202:             }
                   3203:         }
                   3204:     }
1.637     raeburn  3205:     return 'ok';
                   3206: }
                   3207: 
1.639     albertel 3208: sub add_filetype {
                   3209:     my ($allfiles,$file,$type)=@_;
                   3210:     if (exists($allfiles->{$file})) {
                   3211: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3212: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3213: 	}
                   3214:     } else {
                   3215: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3216:     }
                   3217: }
                   3218: 
1.1164    raeburn  3219: sub embedded_dependency {
                   3220:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3221:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3222:         if (($identifier ne '') &&
                   3223:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3224:             ($pathfrom ne '')) {
                   3225:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3226:             foreach my $dep (@{$related->{$identifier}}) {
                   3227:                 &add_filetype($allfiles,$path.$dep,'object');
                   3228:             }
                   3229:         }
                   3230:     }
                   3231:     return;
                   3232: }
                   3233: 
1.493     albertel 3234: sub removeuploadedurl {
1.984     neumanie 3235:     my ($url)=@_;	
                   3236:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3237:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3238: }
                   3239: 
                   3240: sub removeuserfile {
                   3241:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3242:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3243:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3244:     if ($result eq 'ok') {	
1.798     raeburn  3245:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3246:             my $metafile = $fname.'.meta';
                   3247:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3248: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3249:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3250:             my $sqlresult = 
1.823     albertel 3251:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3252:                                         'portfolio_metadata',$group,
                   3253:                                         'delete');
1.798     raeburn  3254:         }
                   3255:     }
                   3256:     return $result;
1.257     www      3257: }
1.15      www      3258: 
1.530     albertel 3259: sub mkdiruserfile {
                   3260:     my ($docuname,$docudom,$dir)=@_;
                   3261:     my $home=&homeserver($docuname,$docudom);
                   3262:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3263: }
                   3264: 
1.531     albertel 3265: sub renameuserfile {
                   3266:     my ($docuname,$docudom,$old,$new)=@_;
                   3267:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3268:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3269:                         &escape("$old").':'.&escape("$new"),$home);
                   3270:     if ($result eq 'ok') {
                   3271:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3272:             my $oldmeta = $old.'.meta';
                   3273:             my $newmeta = $new.'.meta';
                   3274:             my $metaresult = 
                   3275:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3276: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3277:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3278:             my $sqlresult = 
1.823     albertel 3279:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3280:                                         'portfolio_metadata',$group,
                   3281:                                         'delete');
1.798     raeburn  3282:         }
                   3283:     }
                   3284:     return $result;
1.531     albertel 3285: }
                   3286: 
1.14      www      3287: # ------------------------------------------------------------------------- Log
                   3288: 
                   3289: sub log {
                   3290:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3291:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3292: }
                   3293: 
                   3294: # ------------------------------------------------------------------ Course Log
1.352     www      3295: #
                   3296: # This routine flushes several buffers of non-mission-critical nature
                   3297: #
1.157     www      3298: 
                   3299: sub flushcourselogs {
1.352     www      3300:     &logthis('Flushing log buffers');
                   3301: #
                   3302: # course logs
                   3303: # This is a log of all transactions in a course, which can be used
                   3304: # for data mining purposes
                   3305: #
                   3306: # It also collects the courseid database, which lists last transaction
                   3307: # times and course titles for all courseids
                   3308: #
                   3309:     my %courseidbuffer=();
1.921     raeburn  3310:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3311:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3312: 		          &escape($courselogs{$crsid}),
                   3313: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3314: 	    delete $courselogs{$crsid};
                   3315:         } else {
                   3316:             &logthis('Failed to flush log buffer for '.$crsid);
                   3317:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3318:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3319:                         " exceeded maximum size, deleting.</font>");
                   3320:                delete $courselogs{$crsid};
                   3321:             }
1.352     www      3322:         }
1.920     raeburn  3323:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3324:             'description' => $coursedescrbuf{$crsid},
                   3325:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3326:             'type'        => $coursetypebuf{$crsid},
                   3327:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3328:         };
1.191     harris41 3329:     }
1.352     www      3330: #
                   3331: # Write course id database (reverse lookup) to homeserver of courses 
                   3332: # Is used in pickcourse
                   3333: #
1.840     albertel 3334:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3335:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3336:                                     $courseidbuffer{$crs_home},
                   3337:                                     $crs_home,'timeonly');
1.352     www      3338:     }
                   3339: #
                   3340: # File accesses
                   3341: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3342: #
1.449     matthew  3343:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3344:         if ($entry =~ /___count$/) {
                   3345:             my ($dom,$name);
1.807     albertel 3346:             ($dom,$name,undef)=
1.811     albertel 3347: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3348:             if (! defined($dom) || $dom eq '' || 
                   3349:                 ! defined($name) || $name eq '') {
1.620     albertel 3350:                 my $cid = $env{'request.course.id'};
                   3351:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3352:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3353:             }
1.450     matthew  3354:             my $value = $accesshash{$entry};
                   3355:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3356:             my %temphash=($url => $value);
1.449     matthew  3357:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3358:             if ($result eq 'ok') {
                   3359:                 delete $accesshash{$entry};
                   3360:             }
                   3361:         } else {
1.811     albertel 3362:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3363:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3364:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3365:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3366:                 delete $accesshash{$entry};
                   3367:             }
1.185     www      3368:         }
1.191     harris41 3369:     }
1.352     www      3370: #
                   3371: # Roles
                   3372: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3373: #
1.800     albertel 3374:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3375:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3376: 	    split(/\:/,$entry);
                   3377:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3378:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3379:                 $rudom,$runame) eq 'ok') {
                   3380: 	    delete $userrolehash{$entry};
                   3381:         }
                   3382:     }
1.662     raeburn  3383: #
                   3384: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3385: #
                   3386:     my %domrolebuffer = ();
1.1000    raeburn  3387:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3388:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3389:         if ($domrolebuffer{$rudom}) {
                   3390:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3391:                       '='.&escape($domainrolehash{$entry});
                   3392:         } else {
                   3393:             $domrolebuffer{$rudom}.=&escape($entry).
                   3394:                       '='.&escape($domainrolehash{$entry});
                   3395:         }
                   3396:         delete $domainrolehash{$entry};
                   3397:     }
                   3398:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3399: 	my %servers = &get_servers($dom,'library');
                   3400: 	foreach my $tryserver (keys(%servers)) {
                   3401: 	    unless (&reply('domroleput:'.$dom.':'.
                   3402: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3403: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3404: 	    }
1.662     raeburn  3405:         }
                   3406:     }
1.186     www      3407:     $dumpcount++;
1.157     www      3408: }
                   3409: 
                   3410: sub courselog {
                   3411:     my $what=shift;
1.158     www      3412:     $what=time.':'.$what;
1.620     albertel 3413:     unless ($env{'request.course.id'}) { return ''; }
                   3414:     $coursedombuf{$env{'request.course.id'}}=
                   3415:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3416:     $coursenumbuf{$env{'request.course.id'}}=
                   3417:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3418:     $coursehombuf{$env{'request.course.id'}}=
                   3419:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3420:     $coursedescrbuf{$env{'request.course.id'}}=
                   3421:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3422:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3423:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3424:     $courseownerbuf{$env{'request.course.id'}}=
                   3425:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3426:     $coursetypebuf{$env{'request.course.id'}}=
                   3427:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3428:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3429: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3430:     } else {
1.620     albertel 3431: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3432:     }
1.620     albertel 3433:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3434: 	&flushcourselogs();
                   3435:     }
1.158     www      3436: }
                   3437: 
                   3438: sub courseacclog {
                   3439:     my $fnsymb=shift;
1.620     albertel 3440:     unless ($env{'request.course.id'}) { return ''; }
                   3441:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3442:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3443:         $what.=':POST';
1.583     matthew  3444:         # FIXME: Probably ought to escape things....
1.800     albertel 3445: 	foreach my $key (keys(%env)) {
                   3446:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3447:                 my $formitem = $1;
                   3448:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3449:                     $what.=':'.$formitem.'='.$env{$key};
                   3450:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3451:                     $what.=':'.$formitem.'='.$env{$key};
                   3452:                 }
1.158     www      3453:             }
1.191     harris41 3454:         }
1.583     matthew  3455:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3456:         # FIXME: We should not be depending on a form parameter that someone
                   3457:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3458:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3459:             $what.= ':POST';
                   3460:             # FIXME: Probably ought to escape things....
                   3461:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3462:                                  'crsdiscuss') {
1.620     albertel 3463:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3464:             }
                   3465:         }
1.158     www      3466:     }
                   3467:     &courselog($what);
1.149     www      3468: }
                   3469: 
1.185     www      3470: sub countacc {
                   3471:     my $url=&declutter(shift);
1.458     matthew  3472:     return if (! defined($url) || $url eq '');
1.620     albertel 3473:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3474: #
                   3475: # Mark that this url was used in this course
                   3476: #
1.620     albertel 3477:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3478: #
                   3479: # Increase the access count for this resource in this child process
                   3480: #
1.281     www      3481:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3482:     $accesshash{$key}++;
1.185     www      3483: }
1.349     www      3484: 
1.361     www      3485: sub linklog {
                   3486:     my ($from,$to)=@_;
                   3487:     $from=&declutter($from);
                   3488:     $to=&declutter($to);
                   3489:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3490:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3491: }
1.1160    www      3492: 
                   3493: sub statslog {
                   3494:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3495:     if ($users<2) { return; }
                   3496:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3497:             'course'       => $env{'request.course.id'},
                   3498:             'sections'     => '"all"',
                   3499:             'num_students' => $users,
                   3500:             'part'         => $part,
                   3501:             'symb'         => $symb,
                   3502:             'mean_tries'   => $av_attempts,
                   3503:             'deg_of_diff'  => $degdiff});
                   3504:     foreach my $key (keys(%dynstore)) {
                   3505:         $accesshash{$key}=$dynstore{$key};
                   3506:     }
                   3507: }
1.361     www      3508:   
1.349     www      3509: sub userrolelog {
                   3510:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3511:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3512:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3513:        $userrolehash
                   3514:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3515:                     =$tend.':'.$tstart;
1.662     raeburn  3516:     }
1.1169    droeschl 3517:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3518:        $userrolehash
                   3519:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3520:                     =$tend.':'.$tstart;
                   3521:     }
1.1169    droeschl 3522:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3523:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3524:        $domainrolehash
                   3525:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3526:                     = $tend.':'.$tstart;
                   3527:     }
1.351     www      3528: }
                   3529: 
1.957     raeburn  3530: sub courserolelog {
                   3531:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9! raeburn  3532:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
        !          3533:         my $cdom = $1;
        !          3534:         my $cnum = $2;
        !          3535:         my $sec = $3;
        !          3536:         my $namespace = 'rolelog';
        !          3537:         my %storehash = (
        !          3538:                            role    => $trole,
        !          3539:                            start   => $tstart,
        !          3540:                            end     => $tend,
        !          3541:                            selfenroll => $selfenroll,
        !          3542:                            context    => $context,
        !          3543:                         );
        !          3544:         if ($trole eq 'gr') {
        !          3545:             $namespace = 'groupslog';
        !          3546:             $storehash{'group'} = $sec;
        !          3547:         } else {
        !          3548:             $storehash{'section'} = $sec;
        !          3549:         }
        !          3550:         &write_log('course',$namespace,\%storehash,$delflag,$username,
        !          3551:                    $domain,$cnum,$cdom);
        !          3552:         if (($trole ne 'st') || ($sec ne '')) {
        !          3553:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  3554:         }
                   3555:     }
                   3556:     return;
                   3557: }
                   3558: 
1.1172.2.9! raeburn  3559: sub domainrolelog {
        !          3560:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
        !          3561:     if ($area =~ m{^/($match_domain)/$}) {
        !          3562:         my $cdom = $1;
        !          3563:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
        !          3564:         my $namespace = 'rolelog';
        !          3565:         my %storehash = (
        !          3566:                            role    => $trole,
        !          3567:                            start   => $tstart,
        !          3568:                            end     => $tend,
        !          3569:                            context => $context,
        !          3570:                         );
        !          3571:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
        !          3572:                    $domain,$domconfiguser,$cdom);
        !          3573:     }
        !          3574:     return;
        !          3575: 
        !          3576: }
        !          3577: 
        !          3578: sub coauthorrolelog {
        !          3579:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
        !          3580:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
        !          3581:         my $audom = $1;
        !          3582:         my $auname = $2;
        !          3583:         my $namespace = 'rolelog';
        !          3584:         my %storehash = (
        !          3585:                            role    => $trole,
        !          3586:                            start   => $tstart,
        !          3587:                            end     => $tend,
        !          3588:                            context => $context,
        !          3589:                         );
        !          3590:         &write_log('author',$namespace,\%storehash,$delflag,$username,
        !          3591:                    $domain,$auname,$audom);
        !          3592:     }
        !          3593:     return;
        !          3594: }
        !          3595: 
1.351     www      3596: sub get_course_adv_roles {
1.948     raeburn  3597:     my ($cid,$codes) = @_;
1.620     albertel 3598:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3599:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3600:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3601:     my %nothide=();
1.800     albertel 3602:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3603:         if ($user !~ /:/) {
                   3604: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3605:         } else {
                   3606:             $nothide{$user}=1;
                   3607:         }
1.470     www      3608:     }
1.351     www      3609:     my %returnhash=();
                   3610:     my %dumphash=
                   3611:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3612:     my $now=time;
1.997     raeburn  3613:     my %privileged;
1.1000    raeburn  3614:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3615: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3616:         if (($tstart) && ($tstart<0)) { next; }
                   3617:         if (($tend) && ($tend<$now)) { next; }
                   3618:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3619:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3620: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3621:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3622:             my %dompersonnel =
1.998     raeburn  3623:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3624:             $privileged{$domain} = {};
                   3625:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3626:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3627:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3628:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3629:                         $privileged{$udom}{$uname} = 1;
                   3630:                     }
                   3631:                 }
                   3632:             }
                   3633:         }
                   3634:         if ((exists($privileged{$domain}{$username})) && 
                   3635:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3636: 	if ($role eq 'cr') { next; }
1.948     raeburn  3637:         if ($codes) {
                   3638:             if ($section) { $role .= ':'.$section; }
                   3639:             if ($returnhash{$role}) {
                   3640:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3641:             } else {
                   3642:                 $returnhash{$role}=$username.':'.$domain;
                   3643:             }
1.351     www      3644:         } else {
1.988     raeburn  3645:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3646:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3647:             if ($returnhash{$key}) {
                   3648: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3649:             } else {
                   3650:                 $returnhash{$key}=$username.':'.$domain;
                   3651:             }
1.351     www      3652:         }
1.948     raeburn  3653:     }
1.400     www      3654:     return %returnhash;
                   3655: }
                   3656: 
                   3657: sub get_my_roles {
1.937     raeburn  3658:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3659:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3660:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3661:     my (%dumphash,%nothide);
1.1086    raeburn  3662:     if ($context eq 'userroles') {
1.1166    raeburn  3663:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3664:     } else {
                   3665:         %dumphash=
1.400     www      3666:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3667:         if ($hidepriv) {
                   3668:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3669:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3670:                 if ($user !~ /:/) {
                   3671:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3672:                 } else {
                   3673:                     $nothide{$user} = 1;
                   3674:                 }
                   3675:             }
                   3676:         }
1.858     raeburn  3677:     }
1.400     www      3678:     my %returnhash=();
                   3679:     my $now=time;
1.999     raeburn  3680:     my %privileged;
1.800     albertel 3681:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3682:         my ($role,$tend,$tstart);
                   3683:         if ($context eq 'userroles') {
1.1149    raeburn  3684:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3685: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3686:         } else {
                   3687:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3688:         }
1.400     www      3689:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3690:         my $status = 'active';
1.939     raeburn  3691:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3692:             $status = 'previous';
                   3693:         } 
                   3694:         if (($tstart) && ($now<$tstart)) {
                   3695:             $status = 'future';
                   3696:         }
                   3697:         if (ref($types) eq 'ARRAY') {
                   3698:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3699:                 next;
                   3700:             } 
                   3701:         } else {
                   3702:             if ($status ne 'active') {
                   3703:                 next;
                   3704:             }
                   3705:         }
1.867     raeburn  3706:         my ($rolecode,$username,$domain,$section,$area);
                   3707:         if ($context eq 'userroles') {
1.1172.2.9! raeburn  3708:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  3709:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3710:         } else {
                   3711:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3712:         }
1.832     raeburn  3713:         if (ref($roledoms) eq 'ARRAY') {
                   3714:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3715:                 next;
                   3716:             }
                   3717:         }
                   3718:         if (ref($roles) eq 'ARRAY') {
                   3719:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3720:                 if ($role =~ /^cr\//) {
                   3721:                     if (!grep(/^cr$/,@{$roles})) {
                   3722:                         next;
                   3723:                     }
1.1104    raeburn  3724:                 } elsif ($role =~ /^gr\//) {
                   3725:                     if (!grep(/^gr$/,@{$roles})) {
                   3726:                         next;
                   3727:                     }
1.922     raeburn  3728:                 } else {
                   3729:                     next;
                   3730:                 }
1.832     raeburn  3731:             }
1.867     raeburn  3732:         }
1.937     raeburn  3733:         if ($hidepriv) {
1.999     raeburn  3734:             if ($context eq 'userroles') {
                   3735:                 if ((&privileged($username,$domain)) &&
                   3736:                     (!$nothide{$username.':'.$domain})) {
                   3737:                     next;
                   3738:                 }
                   3739:             } else {
                   3740:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3741:                     my %dompersonnel =
                   3742:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3743:                     $privileged{$domain} = {};
                   3744:                     if (keys(%dompersonnel)) {
                   3745:                         foreach my $server (keys(%dompersonnel)) {
                   3746:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3747:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3748:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3749:                                     $privileged{$udom}{$uname} = $trole;
                   3750:                                 }
                   3751:                             }
                   3752:                         }
                   3753:                     }
                   3754:                 }
                   3755:                 if (exists($privileged{$domain}{$username})) {
                   3756:                     if (!$nothide{$username.':'.$domain}) {
                   3757:                         next;
                   3758:                     }
                   3759:                 }
1.937     raeburn  3760:             }
                   3761:         }
1.933     raeburn  3762:         if ($withsec) {
                   3763:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3764:                 $tstart.':'.$tend;
                   3765:         } else {
                   3766:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3767:         }
1.832     raeburn  3768:     }
1.373     www      3769:     return %returnhash;
1.399     www      3770: }
                   3771: 
                   3772: # ----------------------------------------------------- Frontpage Announcements
                   3773: #
                   3774: #
                   3775: 
                   3776: sub postannounce {
                   3777:     my ($server,$text)=@_;
1.844     albertel 3778:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3779:     unless ($text=~/\w/) { $text=''; }
                   3780:     return &reply('setannounce:'.&escape($text),$server);
                   3781: }
                   3782: 
                   3783: sub getannounce {
1.448     albertel 3784: 
                   3785:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3786: 	my $announcement='';
1.800     albertel 3787: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3788: 	close($fh);
1.399     www      3789: 	if ($announcement=~/\w/) { 
                   3790: 	    return 
                   3791:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3792:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3793: 	} else {
                   3794: 	    return '';
                   3795: 	}
                   3796:     } else {
                   3797: 	return '';
                   3798:     }
1.351     www      3799: }
1.353     www      3800: 
                   3801: # ---------------------------------------------------------- Course ID routines
                   3802: # Deal with domain's nohist_courseid.db files
                   3803: #
                   3804: 
                   3805: sub courseidput {
1.921     raeburn  3806:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3807:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3808:     my $outcome;
                   3809:     if ($caller eq 'timeonly') {
                   3810:         my $cids = '';
                   3811:         foreach my $item (keys(%$storehash)) {
                   3812:             $cids.=&escape($item).'&';
                   3813:         }
                   3814:         $cids=~s/\&$//;
                   3815:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3816:                           $coursehome);       
                   3817:     } else {
                   3818:         my $items = '';
                   3819:         foreach my $item (keys(%$storehash)) {
                   3820:             $items.= &escape($item).'='.
                   3821:                      &freeze_escape($$storehash{$item}).'&';
                   3822:         }
                   3823:         $items=~s/\&$//;
                   3824:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3825:                           $coursehome);
1.918     raeburn  3826:     }
                   3827:     if ($outcome eq 'unknown_cmd') {
                   3828:         my $what;
                   3829:         foreach my $cid (keys(%$storehash)) {
                   3830:             $what .= &escape($cid).'=';
1.921     raeburn  3831:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3832:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3833:             }
                   3834:             $what =~ s/\:$/&/;
                   3835:         }
                   3836:         $what =~ s/\&$//;  
                   3837:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3838:     } else {
                   3839:         return $outcome;
                   3840:     }
1.353     www      3841: }
                   3842: 
                   3843: sub courseiddump {
1.921     raeburn  3844:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3845:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3846:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3847:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3848:     my $as_hash = 1;
                   3849:     my %returnhash;
                   3850:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3851:     my %libserv = &all_library();
                   3852:     foreach my $tryserver (keys(%libserv)) {
                   3853:         if ( (  $hostidflag == 1 
                   3854: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3855: 	     || (!defined($hostidflag)) ) {
                   3856: 
1.918     raeburn  3857: 	    if (($domfilter eq '') ||
                   3858: 		(&host_domain($tryserver) eq $domfilter)) {
                   3859:                 my $rep = 
                   3860:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3861:                          $sincefilter.':'.&escape($descfilter).':'.
                   3862:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3863:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3864:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3865:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3866:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3867:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3868:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3869:                          &escape($creationcontext).':'.$domcloner,
                   3870:                          $tryserver);
1.918     raeburn  3871:                 my @pairs=split(/\&/,$rep);
                   3872:                 foreach my $item (@pairs) {
                   3873:                     my ($key,$value)=split(/\=/,$item,2);
                   3874:                     $key = &unescape($key);
                   3875:                     next if ($key =~ /^error: 2 /);
                   3876:                     my $result = &thaw_unescape($value);
                   3877:                     if (ref($result) eq 'HASH') {
                   3878:                         $returnhash{$key}=$result;
                   3879:                     } else {
1.921     raeburn  3880:                         my @responses = split(/:/,$value);
                   3881:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3882:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3883:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3884:                         }
1.1008    raeburn  3885:                     }
1.353     www      3886:                 }
                   3887:             }
                   3888:         }
                   3889:     }
                   3890:     return %returnhash;
                   3891: }
                   3892: 
1.1055    raeburn  3893: sub courselastaccess {
                   3894:     my ($cdom,$cnum,$hostidref) = @_;
                   3895:     my %returnhash;
                   3896:     if ($cdom && $cnum) {
                   3897:         my $chome = &homeserver($cnum,$cdom);
                   3898:         if ($chome ne 'no_host') {
                   3899:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3900:             &extract_lastaccess(\%returnhash,$rep);
                   3901:         }
                   3902:     } else {
                   3903:         if (!$cdom) { $cdom=''; }
                   3904:         my %libserv = &all_library();
                   3905:         foreach my $tryserver (keys(%libserv)) {
                   3906:             if (ref($hostidref) eq 'ARRAY') {
                   3907:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3908:             } 
                   3909:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3910:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3911:                 &extract_lastaccess(\%returnhash,$rep);
                   3912:             }
                   3913:         }
                   3914:     }
                   3915:     return %returnhash;
                   3916: }
                   3917: 
                   3918: sub extract_lastaccess {
                   3919:     my ($returnhash,$rep) = @_;
                   3920:     if (ref($returnhash) eq 'HASH') {
                   3921:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3922:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3923:                  $rep eq '') {
                   3924:             my @pairs=split(/\&/,$rep);
                   3925:             foreach my $item (@pairs) {
                   3926:                 my ($key,$value)=split(/\=/,$item,2);
                   3927:                 $key = &unescape($key);
                   3928:                 next if ($key =~ /^error: 2 /);
                   3929:                 $returnhash->{$key} = &thaw_unescape($value);
                   3930:             }
                   3931:         }
                   3932:     }
                   3933:     return;
                   3934: }
                   3935: 
1.658     raeburn  3936: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3937: 
                   3938: sub dcmailput {
1.685     raeburn  3939:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3940:     my $status = &Apache::lonnet::critical(
1.740     www      3941:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3942:        &escape($message),$server);
1.662     raeburn  3943:     return $status;
                   3944: }
                   3945: 
1.658     raeburn  3946: sub dcmaildump {
                   3947:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3948:     my %returnhash=();
1.846     albertel 3949: 
                   3950:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3951:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3952:                                                          &escape($enddate).':';
                   3953: 	my @esc_senders=map { &escape($_)} @$senders;
                   3954: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3955: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3956:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3957:             if (($key) && ($value)) {
                   3958:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3959:             }
                   3960:         }
                   3961:     }
                   3962:     return %returnhash;
                   3963: }
1.662     raeburn  3964: # ---------------------------------------------------------- Domain roles
                   3965: 
                   3966: sub get_domain_roles {
                   3967:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3968:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3969:         $startdate = '.';
                   3970:     }
1.1018    raeburn  3971:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3972:         $enddate = '.';
                   3973:     }
1.922     raeburn  3974:     my $rolelist;
                   3975:     if (ref($roles) eq 'ARRAY') {
                   3976:         $rolelist = join(':',@{$roles});
                   3977:     }
1.662     raeburn  3978:     my %personnel = ();
1.841     albertel 3979: 
                   3980:     my %servers = &get_servers($dom,'library');
                   3981:     foreach my $tryserver (keys(%servers)) {
                   3982: 	%{$personnel{$tryserver}}=();
                   3983: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3984: 					    &escape($startdate).':'.
                   3985: 					    &escape($enddate).':'.
                   3986: 					    &escape($rolelist), $tryserver))) {
                   3987: 	    my ($key,$value) = split(/\=/,$line,2);
                   3988: 	    if (($key) && ($value)) {
                   3989: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3990: 	    }
                   3991: 	}
1.662     raeburn  3992:     }
                   3993:     return %personnel;
                   3994: }
1.658     raeburn  3995: 
1.1057    www      3996: # ----------------------------------------------------------- Interval timing 
1.149     www      3997: 
1.1153    www      3998: {
                   3999: # Caches needed for speedup of navmaps
                   4000: # We don't want to cache this for very long at all (5 seconds at most)
                   4001: # 
                   4002: # The user for whom we cache
                   4003: my $cachedkey='';
                   4004: # The cached times for this user
                   4005: my %cachedtimes=();
                   4006: # When this was last done
                   4007: my $cachedtime=();
                   4008: 
                   4009: sub load_all_first_access {
1.1154    raeburn  4010:     my ($uname,$udom)=@_;
1.1156    www      4011:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.2  raeburn  4012:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4013:         return;
                   4014:     }
                   4015:     $cachedtime=time;
                   4016:     $cachedkey=$uname.':'.$udom;
                   4017:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4018: }
                   4019: 
1.504     albertel 4020: sub get_first_access {
1.1162    raeburn  4021:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4022:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4023:     if ($argsymb) { $symb=$argsymb; }
                   4024:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4025:     if ($argmap) { $map = $argmap; }
1.926     albertel 4026:     if ($type eq 'course') {
                   4027: 	$res='course';
                   4028:     } elsif ($type eq 'map') {
1.588     albertel 4029: 	$res=&symbread($map);
                   4030:     } else {
                   4031: 	$res=$symb;
                   4032:     }
1.1153    www      4033:     &load_all_first_access($uname,$udom);
                   4034:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4035: }
                   4036: 
                   4037: sub set_first_access {
1.1162    raeburn  4038:     my ($type,$interval)=@_;
1.790     albertel 4039:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4040:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4041:     if ($type eq 'course') {
                   4042: 	$res='course';
                   4043:     } elsif ($type eq 'map') {
1.588     albertel 4044: 	$res=&symbread($map);
                   4045:     } else {
                   4046: 	$res=$symb;
                   4047:     }
1.1153    www      4048:     $cachedkey='';
1.1162    raeburn  4049:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4050:     if (!$firstaccess) {
1.1162    raeburn  4051:         my $start = time;
                   4052: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4053:                           $udom,$uname);
                   4054:         if ($putres eq 'ok') {
                   4055:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4056:                  $udom,$uname); 
                   4057:             &appenv(
                   4058:                      {
                   4059:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4060:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4061:                      }
                   4062:                   );
                   4063:         }
                   4064:         return $putres;
1.505     albertel 4065:     }
                   4066:     return 'already_set';
1.504     albertel 4067: }
1.1153    www      4068: }
1.110     www      4069: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4070: 
                   4071: sub expirespread {
                   4072:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4073:     my $cid=$env{'request.course.id'}; 
1.110     www      4074:     if ($cid) {
                   4075:        my $now=time;
                   4076:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4077:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4078:                             $env{'course.'.$cid.'.num'}.
1.110     www      4079: 	        	    ':nohist_expirationdates:'.
                   4080:                             &escape($key).'='.$now,
1.620     albertel 4081:                             $env{'course.'.$cid.'.home'})
1.110     www      4082:     }
                   4083:     return 'ok';
1.14      www      4084: }
                   4085: 
1.109     www      4086: # ----------------------------------------------------- Devalidate Spreadsheets
                   4087: 
                   4088: sub devalidate {
1.325     www      4089:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4090:     my $cid=$env{'request.course.id'}; 
1.109     www      4091:     if ($cid) {
1.391     matthew  4092:         # delete the stored spreadsheets for
                   4093:         # - the student level sheet of this user in course's homespace
                   4094:         # - the assessment level sheet for this resource 
                   4095:         #   for this user in user's homespace
1.553     albertel 4096: 	# - current conditional state info
1.325     www      4097: 	my $key=$uname.':'.$udom.':';
1.109     www      4098:         my $status=
1.299     matthew  4099: 	    &del('nohist_calculatedsheets',
1.391     matthew  4100: 		 [$key.'studentcalc:'],
1.620     albertel 4101: 		 $env{'course.'.$cid.'.domain'},
                   4102: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4103: 		.' '.
                   4104: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4105: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4106:         unless ($status eq 'ok ok') {
                   4107:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4108:                     $uname.' at '.$udom.' for '.
1.109     www      4109: 		    $symb.': '.$status);
1.133     albertel 4110:         }
1.553     albertel 4111: 	&delenv('user.state.'.$cid);
1.109     www      4112:     }
                   4113: }
                   4114: 
1.265     albertel 4115: sub get_scalar {
                   4116:     my ($string,$end) = @_;
                   4117:     my $value;
                   4118:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4119: 	$value = $1;
                   4120:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4121: 	$value = $1;
                   4122:     }
                   4123:     return &unescape($value);
                   4124: }
                   4125: 
                   4126: sub array2str {
                   4127:   my (@array) = @_;
                   4128:   my $result=&arrayref2str(\@array);
                   4129:   $result=~s/^__ARRAY_REF__//;
                   4130:   $result=~s/__END_ARRAY_REF__$//;
                   4131:   return $result;
                   4132: }
                   4133: 
1.204     albertel 4134: sub arrayref2str {
                   4135:   my ($arrayref) = @_;
1.265     albertel 4136:   my $result='__ARRAY_REF__';
1.204     albertel 4137:   foreach my $elem (@$arrayref) {
1.265     albertel 4138:     if(ref($elem) eq 'ARRAY') {
                   4139:       $result.=&arrayref2str($elem).'&';
                   4140:     } elsif(ref($elem) eq 'HASH') {
                   4141:       $result.=&hashref2str($elem).'&';
                   4142:     } elsif(ref($elem)) {
                   4143:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4144:     } else {
                   4145:       $result.=&escape($elem).'&';
                   4146:     }
                   4147:   }
                   4148:   $result=~s/\&$//;
1.265     albertel 4149:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4150:   return $result;
                   4151: }
                   4152: 
1.168     albertel 4153: sub hash2str {
1.204     albertel 4154:   my (%hash) = @_;
                   4155:   my $result=&hashref2str(\%hash);
1.265     albertel 4156:   $result=~s/^__HASH_REF__//;
                   4157:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4158:   return $result;
                   4159: }
                   4160: 
                   4161: sub hashref2str {
                   4162:   my ($hashref)=@_;
1.265     albertel 4163:   my $result='__HASH_REF__';
1.800     albertel 4164:   foreach my $key (sort(keys(%$hashref))) {
                   4165:     if (ref($key) eq 'ARRAY') {
                   4166:       $result.=&arrayref2str($key).'=';
                   4167:     } elsif (ref($key) eq 'HASH') {
                   4168:       $result.=&hashref2str($key).'=';
                   4169:     } elsif (ref($key)) {
1.265     albertel 4170:       $result.='=';
1.800     albertel 4171:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4172:     } else {
1.1132    raeburn  4173: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4174:     }
                   4175: 
1.800     albertel 4176:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4177:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4178:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4179:       $result.=&hashref2str($hashref->{$key}).'&';
                   4180:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4181:        $result.='&';
1.800     albertel 4182:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4183:     } else {
1.800     albertel 4184:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4185:     }
                   4186:   }
1.168     albertel 4187:   $result=~s/\&$//;
1.265     albertel 4188:   $result .= '__END_HASH_REF__';
1.168     albertel 4189:   return $result;
                   4190: }
                   4191: 
                   4192: sub str2hash {
1.265     albertel 4193:     my ($string)=@_;
                   4194:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4195:     return %$hash;
                   4196: }
                   4197: 
                   4198: sub str2hashref {
1.168     albertel 4199:   my ($string) = @_;
1.265     albertel 4200: 
                   4201:   my %hash;
                   4202: 
                   4203:   if($string !~ /^__HASH_REF__/) {
                   4204:       if (! ($string eq '' || !defined($string))) {
                   4205: 	  $hash{'error'}='Not hash reference';
                   4206:       }
                   4207:       return (\%hash, $string);
                   4208:   }
                   4209: 
                   4210:   $string =~ s/^__HASH_REF__//;
                   4211: 
                   4212:   while($string !~ /^__END_HASH_REF__/) {
                   4213:       #key
                   4214:       my $key='';
                   4215:       if($string =~ /^__HASH_REF__/) {
                   4216:           ($key, $string)=&str2hashref($string);
                   4217:           if(defined($key->{'error'})) {
                   4218:               $hash{'error'}='Bad data';
                   4219:               return (\%hash, $string);
                   4220:           }
                   4221:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4222:           ($key, $string)=&str2arrayref($string);
                   4223:           if($key->[0] eq 'Array reference error') {
                   4224:               $hash{'error'}='Bad data';
                   4225:               return (\%hash, $string);
                   4226:           }
                   4227:       } else {
                   4228:           $string =~ s/^(.*?)=//;
1.267     albertel 4229: 	  $key=&unescape($1);
1.265     albertel 4230:       }
                   4231:       $string =~ s/^=//;
                   4232: 
                   4233:       #value
                   4234:       my $value='';
                   4235:       if($string =~ /^__HASH_REF__/) {
                   4236:           ($value, $string)=&str2hashref($string);
                   4237:           if(defined($value->{'error'})) {
                   4238:               $hash{'error'}='Bad data';
                   4239:               return (\%hash, $string);
                   4240:           }
                   4241:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4242:           ($value, $string)=&str2arrayref($string);
                   4243:           if($value->[0] eq 'Array reference error') {
                   4244:               $hash{'error'}='Bad data';
                   4245:               return (\%hash, $string);
                   4246:           }
                   4247:       } else {
                   4248: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4249:       }
                   4250:       $string =~ s/^&//;
                   4251: 
                   4252:       $hash{$key}=$value;
1.204     albertel 4253:   }
1.265     albertel 4254: 
                   4255:   $string =~ s/^__END_HASH_REF__//;
                   4256: 
                   4257:   return (\%hash, $string);
1.204     albertel 4258: }
                   4259: 
                   4260: sub str2array {
1.265     albertel 4261:     my ($string)=@_;
                   4262:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4263:     return @$array;
                   4264: }
                   4265: 
                   4266: sub str2arrayref {
1.204     albertel 4267:   my ($string) = @_;
1.265     albertel 4268:   my @array;
                   4269: 
                   4270:   if($string !~ /^__ARRAY_REF__/) {
                   4271:       if (! ($string eq '' || !defined($string))) {
                   4272: 	  $array[0]='Array reference error';
                   4273:       }
                   4274:       return (\@array, $string);
                   4275:   }
                   4276: 
                   4277:   $string =~ s/^__ARRAY_REF__//;
                   4278: 
                   4279:   while($string !~ /^__END_ARRAY_REF__/) {
                   4280:       my $value='';
                   4281:       if($string =~ /^__HASH_REF__/) {
                   4282:           ($value, $string)=&str2hashref($string);
                   4283:           if(defined($value->{'error'})) {
                   4284:               $array[0] ='Array reference error';
                   4285:               return (\@array, $string);
                   4286:           }
                   4287:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4288:           ($value, $string)=&str2arrayref($string);
                   4289:           if($value->[0] eq 'Array reference error') {
                   4290:               $array[0] ='Array reference error';
                   4291:               return (\@array, $string);
                   4292:           }
                   4293:       } else {
                   4294: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4295:       }
                   4296:       $string =~ s/^&//;
                   4297: 
                   4298:       push(@array, $value);
1.191     harris41 4299:   }
1.265     albertel 4300: 
                   4301:   $string =~ s/^__END_ARRAY_REF__//;
                   4302: 
                   4303:   return (\@array, $string);
1.168     albertel 4304: }
                   4305: 
1.167     albertel 4306: # -------------------------------------------------------------------Temp Store
                   4307: 
1.168     albertel 4308: sub tmpreset {
                   4309:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4310:   if (!$symb) {
                   4311:     $symb=&symbread();
1.620     albertel 4312:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4313:   }
                   4314:   $symb=escape($symb);
                   4315: 
1.620     albertel 4316:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4317:   $namespace=~s/\//\_/g;
                   4318:   $namespace=~s/\W//g;
                   4319: 
1.620     albertel 4320:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4321:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4322:   if ($domain eq 'public' && $stuname eq 'public') {
                   4323:       $stuname=$ENV{'REMOTE_ADDR'};
                   4324:   }
1.1117    foxr     4325:   my $path=LONCAPA::tempdir();
1.168     albertel 4326:   my %hash;
                   4327:   if (tie(%hash,'GDBM_File',
                   4328: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4329: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4330:     foreach my $key (keys(%hash)) {
1.180     albertel 4331:       if ($key=~ /:$symb/) {
1.168     albertel 4332: 	delete($hash{$key});
                   4333:       }
                   4334:     }
                   4335:   }
                   4336: }
                   4337: 
1.167     albertel 4338: sub tmpstore {
1.168     albertel 4339:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4340: 
                   4341:   if (!$symb) {
                   4342:     $symb=&symbread();
1.620     albertel 4343:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4344:   }
                   4345:   $symb=escape($symb);
                   4346: 
                   4347:   if (!$namespace) {
                   4348:     # I don't think we would ever want to store this for a course.
                   4349:     # it seems this will only be used if we don't have a course.
1.620     albertel 4350:     #$namespace=$env{'request.course.id'};
1.168     albertel 4351:     #if (!$namespace) {
1.620     albertel 4352:       $namespace=$env{'request.state'};
1.168     albertel 4353:     #}
                   4354:   }
                   4355:   $namespace=~s/\//\_/g;
                   4356:   $namespace=~s/\W//g;
1.620     albertel 4357:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4358:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4359:   if ($domain eq 'public' && $stuname eq 'public') {
                   4360:       $stuname=$ENV{'REMOTE_ADDR'};
                   4361:   }
1.168     albertel 4362:   my $now=time;
                   4363:   my %hash;
1.1117    foxr     4364:   my $path=LONCAPA::tempdir();
1.168     albertel 4365:   if (tie(%hash,'GDBM_File',
                   4366: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4367: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4368:     $hash{"version:$symb"}++;
                   4369:     my $version=$hash{"version:$symb"};
                   4370:     my $allkeys=''; 
                   4371:     foreach my $key (keys(%$storehash)) {
                   4372:       $allkeys.=$key.':';
1.591     albertel 4373:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4374:     }
                   4375:     $hash{"$version:$symb:timestamp"}=$now;
                   4376:     $allkeys.='timestamp';
                   4377:     $hash{"$version:keys:$symb"}=$allkeys;
                   4378:     if (untie(%hash)) {
                   4379:       return 'ok';
                   4380:     } else {
                   4381:       return "error:$!";
                   4382:     }
                   4383:   } else {
                   4384:     return "error:$!";
                   4385:   }
                   4386: }
1.167     albertel 4387: 
1.168     albertel 4388: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4389: 
1.168     albertel 4390: sub tmprestore {
                   4391:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4392: 
1.168     albertel 4393:   if (!$symb) {
                   4394:     $symb=&symbread();
1.620     albertel 4395:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4396:   }
                   4397:   $symb=escape($symb);
                   4398: 
1.620     albertel 4399:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4400: 
1.620     albertel 4401:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4402:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4403:   if ($domain eq 'public' && $stuname eq 'public') {
                   4404:       $stuname=$ENV{'REMOTE_ADDR'};
                   4405:   }
1.168     albertel 4406:   my %returnhash;
                   4407:   $namespace=~s/\//\_/g;
                   4408:   $namespace=~s/\W//g;
                   4409:   my %hash;
1.1117    foxr     4410:   my $path=LONCAPA::tempdir();
1.168     albertel 4411:   if (tie(%hash,'GDBM_File',
                   4412: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4413: 	  &GDBM_READER(),0640)) {
1.168     albertel 4414:     my $version=$hash{"version:$symb"};
                   4415:     $returnhash{'version'}=$version;
                   4416:     my $scope;
                   4417:     for ($scope=1;$scope<=$version;$scope++) {
                   4418:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4419:       my @keys=split(/:/,$vkeys);
                   4420:       my $key;
                   4421:       $returnhash{"$scope:keys"}=$vkeys;
                   4422:       foreach $key (@keys) {
1.591     albertel 4423: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4424: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4425:       }
                   4426:     }
1.168     albertel 4427:     if (!(untie(%hash))) {
                   4428:       return "error:$!";
                   4429:     }
                   4430:   } else {
                   4431:     return "error:$!";
                   4432:   }
                   4433:   return %returnhash;
1.167     albertel 4434: }
                   4435: 
1.9       www      4436: # ----------------------------------------------------------------------- Store
                   4437: 
                   4438: sub store {
1.124     www      4439:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4440:     my $home='';
                   4441: 
1.168     albertel 4442:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4443: 
1.213     www      4444:     $symb=&symbclean($symb);
1.122     albertel 4445:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4446: 
1.620     albertel 4447:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4448:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4449: 
                   4450:     &devalidate($symb,$stuname,$domain);
1.109     www      4451: 
                   4452:     $symb=escape($symb);
1.187     www      4453:     if (!$namespace) { 
1.620     albertel 4454:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4455:           return ''; 
                   4456:        } 
                   4457:     }
1.620     albertel 4458:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4459: 
                   4460:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4461:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4462: 
1.12      www      4463:     my $namevalue='';
1.800     albertel 4464:     foreach my $key (keys(%$storehash)) {
                   4465:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4466:     }
1.12      www      4467:     $namevalue=~s/\&$//;
1.187     www      4468:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4469:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4470: }
                   4471: 
1.47      www      4472: # -------------------------------------------------------------- Critical Store
                   4473: 
                   4474: sub cstore {
1.124     www      4475:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4476:     my $home='';
                   4477: 
1.168     albertel 4478:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4479: 
1.213     www      4480:     $symb=&symbclean($symb);
1.122     albertel 4481:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4482: 
1.620     albertel 4483:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4484:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4485: 
                   4486:     &devalidate($symb,$stuname,$domain);
1.109     www      4487: 
                   4488:     $symb=escape($symb);
1.187     www      4489:     if (!$namespace) { 
1.620     albertel 4490:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4491:           return ''; 
                   4492:        } 
                   4493:     }
1.620     albertel 4494:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4495: 
                   4496:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4497:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4498: 
1.47      www      4499:     my $namevalue='';
1.800     albertel 4500:     foreach my $key (keys(%$storehash)) {
                   4501:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4502:     }
1.47      www      4503:     $namevalue=~s/\&$//;
1.187     www      4504:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4505:     return critical
                   4506:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4507: }
                   4508: 
1.9       www      4509: # --------------------------------------------------------------------- Restore
                   4510: 
                   4511: sub restore {
1.124     www      4512:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4513:     my $home='';
                   4514: 
1.168     albertel 4515:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4516: 
1.122     albertel 4517:     if (!$symb) {
                   4518:       unless ($symb=escape(&symbread())) { return ''; }
                   4519:     } else {
1.213     www      4520:       $symb=&escape(&symbclean($symb));
1.122     albertel 4521:     }
1.188     www      4522:     if (!$namespace) { 
1.620     albertel 4523:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4524:           return ''; 
                   4525:        } 
                   4526:     }
1.620     albertel 4527:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4528:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4529:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4530:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4531: 
1.12      www      4532:     my %returnhash=();
1.800     albertel 4533:     foreach my $line (split(/\&/,$answer)) {
                   4534: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4535:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4536:     }
1.75      www      4537:     my $version;
                   4538:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4539:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4540:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4541:        }
1.75      www      4542:     }
1.13      www      4543:     return %returnhash;
1.34      www      4544: }
                   4545: 
                   4546: # ---------------------------------------------------------- Course Description
1.1118    foxr     4547: #
                   4548: #  
1.34      www      4549: 
                   4550: sub coursedescription {
1.731     albertel 4551:     my ($courseid,$args)=@_;
1.34      www      4552:     $courseid=~s/^\///;
1.49      www      4553:     $courseid=~s/\_/\//g;
1.34      www      4554:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4555:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4556:     my $normalid=$cdomain.'_'.$cnum;
                   4557:     # need to always cache even if we get errors otherwise we keep 
                   4558:     # trying and trying and trying to get the course description.
                   4559:     my %envhash=();
                   4560:     my %returnhash=();
1.731     albertel 4561:     
                   4562:     my $expiretime=600;
                   4563:     if ($env{'request.course.id'} eq $normalid) {
                   4564: 	$expiretime=120;
                   4565:     }
                   4566: 
                   4567:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4568:     if (!$args->{'freshen_cache'}
                   4569: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4570: 	foreach my $key (keys(%env)) {
                   4571: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4572: 	    my ($setting) = $1;
                   4573: 	    $returnhash{$setting} = $env{$key};
                   4574: 	}
                   4575: 	return %returnhash;
                   4576:     }
                   4577: 
1.1118    foxr     4578:     # get the data again
                   4579: 
1.731     albertel 4580:     if (!$args->{'one_time'}) {
                   4581: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4582:     }
1.811     albertel 4583: 
1.34      www      4584:     if ($chome ne 'no_host') {
1.302     albertel 4585:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4586:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4587: 	   my $username = $env{'user.name'}; # Defult username
                   4588: 	   if(defined $args->{'user'}) {
                   4589: 	       $username = $args->{'user'};
                   4590: 	   }
1.129     albertel 4591:            $returnhash{'home'}= $chome;
                   4592: 	   $returnhash{'domain'} = $cdomain;
                   4593: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4594:            if (!defined($returnhash{'type'})) {
                   4595:                $returnhash{'type'} = 'Course';
                   4596:            }
1.130     albertel 4597:            while (my ($name,$value) = each %returnhash) {
1.53      www      4598:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4599:            }
1.270     www      4600:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4601:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4602: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4603:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4604:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4605:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4606:        }
                   4607:     }
1.731     albertel 4608:     if (!$args->{'one_time'}) {
1.949     raeburn  4609: 	&appenv(\%envhash);
1.731     albertel 4610:     }
1.302     albertel 4611:     return %returnhash;
1.461     www      4612: }
                   4613: 
1.1080    raeburn  4614: sub update_released_required {
                   4615:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4616:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4617:         $cid = $env{'request.course.id'};
                   4618:         $cdom = $env{'course.'.$cid.'.domain'};
                   4619:         $cnum = $env{'course.'.$cid.'.num'};
                   4620:         $chome = $env{'course.'.$cid.'.home'};
                   4621:     }
                   4622:     if ($needsrelease) {
                   4623:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4624:         my $needsupdate;
                   4625:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4626:             $needsupdate = 1;
                   4627:         } else {
                   4628:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4629:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4630:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4631:                 $needsupdate = 1;
                   4632:             }
                   4633:         }
                   4634:         if ($needsupdate) {
                   4635:             my %needshash = (
                   4636:                              'internal.releaserequired' => $needsrelease,
                   4637:                             );
                   4638:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4639:             if ($putresult eq 'ok') {
                   4640:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4641:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4642:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4643:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4644:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4645:                 }
                   4646:             }
                   4647:         }
                   4648:     }
                   4649:     return;
                   4650: }
                   4651: 
1.461     www      4652: # -------------------------------------------------See if a user is privileged
                   4653: 
                   4654: sub privileged {
                   4655:     my ($username,$domain)=@_;
1.1170    droeschl 4656: 
                   4657:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4658:     my $now = time;
                   4659: 
                   4660:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
                   4661:             my ($trole, $tend, $tstart) = split(/_/, $role);
                   4662:             if (($trole eq 'dc') || ($trole eq 'su')) {
                   4663:                 return 1 unless ($tend && $tend < $now) 
                   4664:                     or ($tstart && $tstart > $now);
                   4665:             }
1.461     www      4666: 	}
1.1170    droeschl 4667: 
1.461     www      4668:     return 0;
1.9       www      4669: }
1.1       albertel 4670: 
1.103     harris41 4671: # -------------------------------------------------------- Get user privileges
1.11      www      4672: 
                   4673: sub rolesinit {
1.1169    droeschl 4674:     my ($domain, $username) = @_;
                   4675:     my %userroles = ('user.login.time' => time);
                   4676:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   4677: 
                   4678:     # firstaccess and timerinterval are related to timed maps/resources. 
                   4679:     # also, blocking can be triggered by an activating timer
                   4680:     # it's saved in the user's %env.
                   4681:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   4682:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   4683:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   4684:         %timerintchk, %timerintenv);
                   4685: 
1.1162    raeburn  4686:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 4687:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  4688:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4689:     }
1.1169    droeschl 4690: 
1.1162    raeburn  4691:     foreach my $key (keys(%timerinterval)) {
                   4692:         my ($cid,$rest) = split(/\0/,$key);
                   4693:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4694:     }
1.1169    droeschl 4695: 
1.11      www      4696:     my %allroles=();
1.1162    raeburn  4697:     my %allgroups=();
1.11      www      4698: 
1.1169    droeschl 4699:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   4700:         my $role = $rolesdump{$area};
                   4701:         $area =~ s/\_\w\w$//;
                   4702: 
                   4703:         my ($trole, $tend, $tstart, $group_privs);
                   4704: 
                   4705:         if ($role =~ /^cr/) {
                   4706:         # Custom role, defined by a user 
                   4707:         # e.g., user.role.cr/msu/smith/mynewrole
                   4708:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4709:                 $trole = $1;
                   4710:                 ($tend, $tstart) = split('_', $2);
                   4711:             } else {
                   4712:                 $trole = $role;
                   4713:             }
                   4714:         } elsif ($role =~ m|^gr/|) {
                   4715:         # Role of member in a group, defined within a course/community
                   4716:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   4717:             ($trole, $tend, $tstart) = split(/_/, $role);
                   4718:             next if $tstart eq '-1';
                   4719:             ($trole, $group_privs) = split(/\//, $trole);
                   4720:             $group_privs = &unescape($group_privs);
                   4721:         } else {
                   4722:         # Just a normal role, defined in roles.tab
                   4723:             ($trole, $tend, $tstart) = split(/_/,$role);
                   4724:         }
                   4725: 
                   4726:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4727:                  $username);
                   4728:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   4729: 
                   4730:         # role expired or not available yet?
                   4731:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   4732:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   4733: 
                   4734:         next if $area eq '' or $trole eq '';
                   4735: 
                   4736:         my $spec = "$trole.$area";
                   4737:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   4738: 
                   4739:         if ($trole =~ /^cr\//) {
                   4740:         # Custom role, defined by a user
                   4741:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4742:         } elsif ($trole eq 'gr') {
                   4743:         # Role of a member in a group, defined within a course/community
                   4744:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   4745:             next;
                   4746:         } else {
                   4747:         # Normal role, defined in roles.tab
                   4748:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4749:         }
                   4750: 
                   4751:         my $cid = $tdomain.'_'.$trest;
                   4752:         unless ($firstaccchk{$cid}) {
                   4753:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   4754:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   4755:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   4756:                         $coursetimerstarts{$cid}{$item}; 
                   4757:                 }
                   4758:             }
                   4759:             $firstaccchk{$cid} = 1;
                   4760:         }
                   4761:         unless ($timerintchk{$cid}) {
                   4762:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   4763:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   4764:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   4765:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  4766:                 }
1.12      www      4767:             }
1.1169    droeschl 4768:             $timerintchk{$cid} = 1;
1.191     harris41 4769:         }
1.11      www      4770:     }
1.1169    droeschl 4771: 
                   4772:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   4773:         \%allroles, \%allgroups);
                   4774:     $env{'user.adv'} = $userroles{'user.adv'};
                   4775: 
1.1162    raeburn  4776:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      4777: }
                   4778: 
1.567     raeburn  4779: sub set_arearole {
                   4780:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4781: # log the associated role with the area
                   4782:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4783:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4784: }
                   4785: 
                   4786: sub custom_roleprivs {
                   4787:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4788:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4789:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4790:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4791:         my ($rdummy,$roledef)=
                   4792:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4793:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4794:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4795:             if (defined($syspriv)) {
1.1043    raeburn  4796:                 if ($trest =~ /^$match_community$/) {
                   4797:                     $syspriv =~ s/bre\&S//; 
                   4798:                 }
1.567     raeburn  4799:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4800:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4801:             }
                   4802:             if ($tdomain ne '') {
                   4803:                 if (defined($dompriv)) {
                   4804:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4805:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4806:                 }
                   4807:                 if (($trest ne '') && (defined($coursepriv))) {
                   4808:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4809:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4810:                 }
                   4811:             }
                   4812:         }
                   4813:     }
                   4814: }
                   4815: 
1.678     raeburn  4816: sub group_roleprivs {
                   4817:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4818:     my $access = 1;
                   4819:     my $now = time;
                   4820:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4821:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4822:     if ($access) {
1.811     albertel 4823:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4824:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4825:     }
                   4826: }
1.567     raeburn  4827: 
                   4828: sub standard_roleprivs {
                   4829:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4830:     if (defined($pr{$trole.':s'})) {
                   4831:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4832:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4833:     }
                   4834:     if ($tdomain ne '') {
                   4835:         if (defined($pr{$trole.':d'})) {
                   4836:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4837:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4838:         }
                   4839:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4840:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4841:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4842:         }
                   4843:     }
                   4844: }
                   4845: 
                   4846: sub set_userprivs {
1.1064    raeburn  4847:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4848:     my $author=0;
                   4849:     my $adv=0;
1.678     raeburn  4850:     my %grouproles = ();
                   4851:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4852:         my @groupkeys; 
1.1000    raeburn  4853:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4854:             push(@groupkeys,$role);
                   4855:         }
                   4856:         if (ref($groups_roles) eq 'HASH') {
                   4857:             foreach my $key (keys(%{$groups_roles})) {
                   4858:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4859:                     push(@groupkeys,$key);
                   4860:                 }
                   4861:             }
                   4862:         }
                   4863:         if (@groupkeys > 0) {
                   4864:             foreach my $role (@groupkeys) {
                   4865:                 my ($trole,$area,$sec,$extendedarea);
                   4866:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4867:                     $trole = $1;
                   4868:                     $area = $2;
                   4869:                     $sec = $3;
                   4870:                     $extendedarea = $area.$sec;
                   4871:                     if (exists($$allgroups{$area})) {
                   4872:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4873:                             my $spec = $trole.'.'.$extendedarea;
                   4874:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4875:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4876:                         }
1.678     raeburn  4877:                     }
                   4878:                 }
                   4879:             }
                   4880:         }
                   4881:     }
1.800     albertel 4882:     foreach my $group (keys(%grouproles)) {
                   4883:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4884:     }
1.800     albertel 4885:     foreach my $role (keys(%{$allroles})) {
                   4886:         my %thesepriv;
1.941     raeburn  4887:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4888:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4889:             if ($item ne '') {
                   4890:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4891:                 if ($restrictions eq '') {
                   4892:                     $thesepriv{$privilege}='F';
                   4893:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4894:                     $thesepriv{$privilege}.=$restrictions;
                   4895:                 }
                   4896:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4897:             }
                   4898:         }
                   4899:         my $thesestr='';
1.1104    raeburn  4900:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4901: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4902: 	}
                   4903:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4904:     }
                   4905:     return ($author,$adv);
                   4906: }
                   4907: 
1.994     raeburn  4908: sub role_status {
1.1104    raeburn  4909:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4910:     my @pwhere = ();
                   4911:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4912:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4913:         unless (!defined($$role) || $$role eq '') {
                   4914:             $$where=join('.',@pwhere);
                   4915:             $$trolecode=$$role.'.'.$$where;
                   4916:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4917:             $$tstatus='is';
1.1104    raeburn  4918:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4919:                 $$tstatus='future';
1.1034    raeburn  4920:                 if ($$tstart<$now) {
                   4921:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4922:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4923:                             my (%allroles,%allgroups,$group_privs,
                   4924:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4925:                             my %userroles = (
                   4926:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4927:                             );
1.1064    raeburn  4928:                             @rolecodes = ('cm'); 
1.1002    raeburn  4929:                             my $spec=$$role.'.'.$$where;
                   4930:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4931:                             if ($$role =~ /^cr\//) {
                   4932:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4933:                                 push(@rolecodes,'cr');
1.1002    raeburn  4934:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4935:                                 push(@rolecodes,$$role);
1.1002    raeburn  4936:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4937:                                                     $env{'user.name'});
1.1064    raeburn  4938:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4939:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4940:                                 $group_privs = &unescape($group_privs);
                   4941:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4942:                                 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  4943:                                 &get_groups_roles($tdomain,$trest,
                   4944:                                                   \%course_roles,\@rolecodes,
                   4945:                                                   \%groups_roles);
1.1002    raeburn  4946:                             } else {
1.1064    raeburn  4947:                                 push(@rolecodes,$$role);
1.1002    raeburn  4948:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4949:                             }
1.1064    raeburn  4950:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4951:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4952:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4953:                         }
                   4954:                     }
1.1034    raeburn  4955:                     $$tstatus = 'is';
1.1002    raeburn  4956:                 }
1.994     raeburn  4957:             }
                   4958:             if ($$tend) {
1.1104    raeburn  4959:                 if ($$tend<$update) {
1.994     raeburn  4960:                     $$tstatus='expired';
                   4961:                 } elsif ($$tend<$now) {
                   4962:                     $$tstatus='will_not';
                   4963:                 }
                   4964:             }
                   4965:         }
                   4966:     }
                   4967: }
                   4968: 
1.1104    raeburn  4969: sub get_groups_roles {
                   4970:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4971:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4972:                   (ref($rolecodes) eq 'ARRAY') && 
                   4973:                   (ref($groups_roles) eq 'HASH')); 
                   4974:     if (keys(%{$cdom_courseroles}) > 0) {
                   4975:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4976:         if ($cdom ne '' && $cnum ne '') {
                   4977:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4978:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4979:                     my $crsrole = $1;
                   4980:                     my $crssec = $2;
                   4981:                     if ($crsrole =~ /^cr/) {
                   4982:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4983:                             push(@{$rolecodes},'cr');
                   4984:                         }
                   4985:                     } else {
                   4986:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4987:                             push(@{$rolecodes},$crsrole);
                   4988:                         }
                   4989:                     }
                   4990:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4991:                     if ($crssec ne '') {
                   4992:                         $rolekey .= "/$crssec";
                   4993:                     }
                   4994:                     $rolekey .= './';
                   4995:                     $groups_roles->{$rolekey} = $rolecodes;
                   4996:                 }
                   4997:             }
                   4998:         }
                   4999:     }
                   5000:     return;
                   5001: }
                   5002: 
                   5003: sub delete_env_groupprivs {
                   5004:     my ($where,$courseroles,$possroles) = @_;
                   5005:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5006:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5007:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5008:         %{$courseroles->{$udom}} =
                   5009:             &get_my_roles('','','userroles',['active'],
                   5010:                           $possroles,[$udom],1);
                   5011:     }
                   5012:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5013:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5014:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5015:             my $area = '/'.$cdom.'/'.$cnum;
                   5016:             my $privkey = "user.priv.$crsrole.$area";
                   5017:             if ($crssec ne '') {
                   5018:                 $privkey .= '/'.$crssec;
                   5019:             }
                   5020:             $privkey .= ".$area/$group";
                   5021:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5022:         }
                   5023:     }
                   5024:     return;
                   5025: }
                   5026: 
1.994     raeburn  5027: sub check_adhoc_privs {
1.1104    raeburn  5028:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5029:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.9! raeburn  5030:     my $setprivs;
1.994     raeburn  5031:     if ($env{$cckey}) {
                   5032:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5033:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5034:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5035:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9! raeburn  5036:             $setprivs = 1;
1.994     raeburn  5037:         }
                   5038:     } else {
1.1088    raeburn  5039:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1172.2.9! raeburn  5040:         $setprivs = 1;
1.994     raeburn  5041:     }
1.1172.2.9! raeburn  5042:     return $setprivs;
1.994     raeburn  5043: }
                   5044: 
                   5045: sub set_adhoc_privileges {
                   5046: # role can be cc or ca
1.1088    raeburn  5047:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5048:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5049:     my $spec = $role.'.'.$area;
                   5050:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   5051:                                   $env{'user.name'});
                   5052:     my %ccrole = ();
                   5053:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5054:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5055:     &appenv(\%userroles,[$role,'cm']);
                   5056:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5057:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5058:         &appenv( {'request.role'        => $spec,
                   5059:                   'request.role.domain' => $dcdom,
                   5060:                   'request.course.sec'  => ''
                   5061:                  }
                   5062:                );
                   5063:         my $tadv=0;
                   5064:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5065:         &appenv({'request.role.adv'    => $tadv});
                   5066:     }
1.994     raeburn  5067: }
                   5068: 
1.12      www      5069: # --------------------------------------------------------------- get interface
                   5070: 
                   5071: sub get {
1.131     albertel 5072:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5073:    my $items='';
1.800     albertel 5074:    foreach my $item (@$storearr) {
                   5075:        $items.=&escape($item).'&';
1.191     harris41 5076:    }
1.12      www      5077:    $items=~s/\&$//;
1.620     albertel 5078:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5079:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5080:    my $uhome=&homeserver($uname,$udomain);
                   5081: 
1.133     albertel 5082:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5083:    my @pairs=split(/\&/,$rep);
1.273     albertel 5084:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5085:      return @pairs;
                   5086:    }
1.15      www      5087:    my %returnhash=();
1.42      www      5088:    my $i=0;
1.800     albertel 5089:    foreach my $item (@$storearr) {
                   5090:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5091:       $i++;
1.191     harris41 5092:    }
1.15      www      5093:    return %returnhash;
1.27      www      5094: }
                   5095: 
                   5096: # --------------------------------------------------------------- del interface
                   5097: 
                   5098: sub del {
1.133     albertel 5099:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5100:    my $items='';
1.800     albertel 5101:    foreach my $item (@$storearr) {
                   5102:        $items.=&escape($item).'&';
1.191     harris41 5103:    }
1.984     neumanie 5104: 
1.27      www      5105:    $items=~s/\&$//;
1.620     albertel 5106:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5107:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5108:    my $uhome=&homeserver($uname,$udomain);
                   5109:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5110: }
                   5111: 
                   5112: # -------------------------------------------------------------- dump interface
                   5113: 
                   5114: sub dump {
1.1166    raeburn  5115:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.755     albertel 5116:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5117:     if (!$uname) { $uname=$env{'user.name'}; }
                   5118:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5119: 
1.755     albertel 5120:     if ($regexp) {
                   5121: 	$regexp=&escape($regexp);
                   5122:     } else {
                   5123: 	$regexp='.';
                   5124:     }
1.1166    raeburn  5125:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5126:     my @pairs=split(/\&/,$rep);
                   5127:     my %returnhash=();
1.1098    foxr     5128:     if (!($rep =~ /^error/ )) {
                   5129: 	foreach my $item (@pairs) {
                   5130: 	    my ($key,$value)=split(/=/,$item,2);
                   5131: 	    $key = &unescape($key);
                   5132: 	    next if ($key =~ /^error: 2 /);
                   5133: 	    $returnhash{$key}=&thaw_unescape($value);
                   5134: 	}
1.755     albertel 5135:     }
                   5136:     return %returnhash;
1.407     www      5137: }
                   5138: 
1.1098    foxr     5139: 
1.717     albertel 5140: # --------------------------------------------------------- dumpstore interface
                   5141: 
                   5142: sub dumpstore {
                   5143:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 5144:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5145:    if (!$uname) { $uname=$env{'user.name'}; }
                   5146:    my $uhome=&homeserver($uname,$udomain);
                   5147:    if ($regexp) {
                   5148:        $regexp=&escape($regexp);
                   5149:    } else {
                   5150:        $regexp='.';
                   5151:    }
                   5152:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   5153:    my @pairs=split(/\&/,$rep);
                   5154:    my %returnhash=();
                   5155:    foreach my $item (@pairs) {
                   5156:        my ($key,$value)=split(/=/,$item,2);
                   5157:        next if ($key =~ /^error: 2 /);
                   5158:        $returnhash{$key}=&thaw_unescape($value);
                   5159:    }
                   5160:    return %returnhash;
1.717     albertel 5161: }
                   5162: 
1.407     www      5163: # -------------------------------------------------------------- keys interface
                   5164: 
                   5165: sub getkeys {
                   5166:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5167:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5168:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5169:    my $uhome=&homeserver($uname,$udomain);
                   5170:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5171:    my @keyarray=();
1.800     albertel 5172:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5173:       next if ($key =~ /^error: 2 /);
1.800     albertel 5174:       push(@keyarray,&unescape($key));
1.407     www      5175:    }
                   5176:    return @keyarray;
1.318     matthew  5177: }
                   5178: 
1.319     matthew  5179: # --------------------------------------------------------------- currentdump
                   5180: sub currentdump {
1.328     matthew  5181:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5182:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5183:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5184:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5185:    my $uhome = &homeserver($sname,$sdom);
                   5186:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5187:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5188:    #
1.318     matthew  5189:    my %returnhash=();
1.319     matthew  5190:    #
                   5191:    if ($rep eq "unknown_cmd") { 
                   5192:        # an old lond will not know currentdump
                   5193:        # Do a dump and make it look like a currentdump
1.822     albertel 5194:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5195:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5196:        my %hash = @tmp;
                   5197:        @tmp=();
1.424     matthew  5198:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5199:    } else {
                   5200:        my @pairs=split(/\&/,$rep);
1.800     albertel 5201:        foreach my $pair (@pairs) {
                   5202:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5203:            my ($symb,$param) = split(/:/,$key);
                   5204:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5205:                                                         &thaw_unescape($value);
1.319     matthew  5206:        }
1.191     harris41 5207:    }
1.12      www      5208:    return %returnhash;
1.424     matthew  5209: }
                   5210: 
                   5211: sub convert_dump_to_currentdump{
                   5212:     my %hash = %{shift()};
                   5213:     my %returnhash;
                   5214:     # Code ripped from lond, essentially.  The only difference
                   5215:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5216:     # we might run in to problems with parameter names =~ /^v\./
                   5217:     while (my ($key,$value) = each(%hash)) {
                   5218:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5219: 	$symb  = &unescape($symb);
                   5220: 	$param = &unescape($param);
1.424     matthew  5221:         next if ($v eq 'version' || $symb eq 'keys');
                   5222:         next if (exists($returnhash{$symb}) &&
                   5223:                  exists($returnhash{$symb}->{$param}) &&
                   5224:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5225:         $returnhash{$symb}->{$param}=$value;
                   5226:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5227:     }
                   5228:     #
                   5229:     # Remove all of the keys in the hashes which keep track of
                   5230:     # the version of the parameter.
                   5231:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5232:         # use a foreach because we are going to delete from the hash.
                   5233:         foreach my $key (keys(%$param_hash)) {
                   5234:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5235:         }
                   5236:     }
                   5237:     return \%returnhash;
1.12      www      5238: }
                   5239: 
1.627     albertel 5240: # ------------------------------------------------------ critical inc interface
                   5241: 
                   5242: sub cinc {
                   5243:     return &inc(@_,'critical');
                   5244: }
                   5245: 
1.449     matthew  5246: # --------------------------------------------------------------- inc interface
                   5247: 
                   5248: sub inc {
1.627     albertel 5249:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5250:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5251:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5252:     my $uhome=&homeserver($uname,$udomain);
                   5253:     my $items='';
                   5254:     if (! ref($store)) {
                   5255:         # got a single value, so use that instead
                   5256:         $items = &escape($store).'=&';
                   5257:     } elsif (ref($store) eq 'SCALAR') {
                   5258:         $items = &escape($$store).'=&';        
                   5259:     } elsif (ref($store) eq 'ARRAY') {
                   5260:         $items = join('=&',map {&escape($_);} @{$store});
                   5261:     } elsif (ref($store) eq 'HASH') {
                   5262:         while (my($key,$value) = each(%{$store})) {
                   5263:             $items.= &escape($key).'='.&escape($value).'&';
                   5264:         }
                   5265:     }
                   5266:     $items=~s/\&$//;
1.627     albertel 5267:     if ($critical) {
                   5268: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5269:     } else {
                   5270: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5271:     }
1.449     matthew  5272: }
                   5273: 
1.12      www      5274: # --------------------------------------------------------------- put interface
                   5275: 
                   5276: sub put {
1.134     albertel 5277:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5278:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5279:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5280:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5281:    my $items='';
1.800     albertel 5282:    foreach my $item (keys(%$storehash)) {
                   5283:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5284:    }
1.12      www      5285:    $items=~s/\&$//;
1.134     albertel 5286:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5287: }
                   5288: 
1.631     albertel 5289: # ------------------------------------------------------------ newput interface
                   5290: 
                   5291: sub newput {
                   5292:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5293:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5294:    if (!$uname) { $uname=$env{'user.name'}; }
                   5295:    my $uhome=&homeserver($uname,$udomain);
                   5296:    my $items='';
                   5297:    foreach my $key (keys(%$storehash)) {
                   5298:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5299:    }
                   5300:    $items=~s/\&$//;
                   5301:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5302: }
                   5303: 
                   5304: # ---------------------------------------------------------  putstore interface
                   5305: 
1.524     raeburn  5306: sub putstore {
1.715     albertel 5307:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5308:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5309:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5310:    my $uhome=&homeserver($uname,$udomain);
                   5311:    my $items='';
1.715     albertel 5312:    foreach my $key (keys(%$storehash)) {
                   5313:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5314:    }
1.715     albertel 5315:    $items=~s/\&$//;
1.716     albertel 5316:    my $esc_symb=&escape($symb);
                   5317:    my $esc_v=&escape($version);
1.715     albertel 5318:    my $reply =
1.716     albertel 5319:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5320: 	      $uhome);
                   5321:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5322:        # gfall back to way things use to be done
1.715     albertel 5323:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5324: 			    $uname);
1.524     raeburn  5325:    }
1.715     albertel 5326:    return $reply;
                   5327: }
                   5328: 
                   5329: sub old_putstore {
1.716     albertel 5330:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5331:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5332:     if (!$uname) { $uname=$env{'user.name'}; }
                   5333:     my $uhome=&homeserver($uname,$udomain);
                   5334:     my %newstorehash;
1.800     albertel 5335:     foreach my $item (keys(%$storehash)) {
                   5336: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5337: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5338:     }
                   5339:     my $items='';
                   5340:     my %allitems = ();
1.800     albertel 5341:     foreach my $item (keys(%newstorehash)) {
                   5342: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5343: 	    my $key = $1.':keys:'.$2;
                   5344: 	    $allitems{$key} .= $3.':';
                   5345: 	}
1.800     albertel 5346: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5347:     }
1.800     albertel 5348:     foreach my $item (keys(%allitems)) {
                   5349: 	$allitems{$item} =~ s/\:$//;
                   5350: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5351:     }
                   5352:     $items=~s/\&$//;
                   5353:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5354: }
                   5355: 
1.47      www      5356: # ------------------------------------------------------ critical put interface
                   5357: 
                   5358: sub cput {
1.134     albertel 5359:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5360:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5361:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5362:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5363:    my $items='';
1.800     albertel 5364:    foreach my $item (keys(%$storehash)) {
                   5365:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5366:    }
1.47      www      5367:    $items=~s/\&$//;
1.134     albertel 5368:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5369: }
                   5370: 
                   5371: # -------------------------------------------------------------- eget interface
                   5372: 
                   5373: sub eget {
1.133     albertel 5374:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5375:    my $items='';
1.800     albertel 5376:    foreach my $item (@$storearr) {
                   5377:        $items.=&escape($item).'&';
1.191     harris41 5378:    }
1.12      www      5379:    $items=~s/\&$//;
1.620     albertel 5380:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5381:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5382:    my $uhome=&homeserver($uname,$udomain);
                   5383:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5384:    my @pairs=split(/\&/,$rep);
                   5385:    my %returnhash=();
1.42      www      5386:    my $i=0;
1.800     albertel 5387:    foreach my $item (@$storearr) {
                   5388:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5389:       $i++;
1.191     harris41 5390:    }
1.12      www      5391:    return %returnhash;
                   5392: }
                   5393: 
1.667     albertel 5394: # ------------------------------------------------------------ tmpput interface
                   5395: sub tmpput {
1.802     raeburn  5396:     my ($storehash,$server,$context)=@_;
1.667     albertel 5397:     my $items='';
1.800     albertel 5398:     foreach my $item (keys(%$storehash)) {
                   5399: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5400:     }
                   5401:     $items=~s/\&$//;
1.802     raeburn  5402:     if (defined($context)) {
                   5403:         $items .= ':'.&escape($context);
                   5404:     }
1.667     albertel 5405:     return &reply("tmpput:$items",$server);
                   5406: }
                   5407: 
                   5408: # ------------------------------------------------------------ tmpget interface
                   5409: sub tmpget {
1.688     albertel 5410:     my ($token,$server)=@_;
                   5411:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5412:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5413:     my %returnhash;
                   5414:     foreach my $item (split(/\&/,$rep)) {
                   5415: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5416:         next if ($key =~ /^error: 2 /);
1.667     albertel 5417: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5418:     }
                   5419:     return %returnhash;
                   5420: }
                   5421: 
1.1113    raeburn  5422: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5423: sub tmpdel {
                   5424:     my ($token,$server)=@_;
                   5425:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5426:     return &reply("tmpdel:$token",$server);
                   5427: }
                   5428: 
1.765     albertel 5429: # -------------------------------------------------- portfolio access checking
                   5430: 
                   5431: sub portfolio_access {
1.766     albertel 5432:     my ($requrl) = @_;
1.765     albertel 5433:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5434:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5435:     if ($result) {
                   5436:         my %setters;
                   5437:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5438:             my ($startblock,$endblock) =
                   5439:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5440:             if ($startblock && $endblock) {
                   5441:                 return 'B';
                   5442:             }
                   5443:         } else {
                   5444:             my ($startblock,$endblock) =
                   5445:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5446:             if ($startblock && $endblock) {
                   5447:                 return 'B';
                   5448:             }
                   5449:         }
                   5450:     }
1.765     albertel 5451:     if ($result eq 'ok') {
1.766     albertel 5452:        return 'F';
1.765     albertel 5453:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5454:        return 'A';
1.765     albertel 5455:     }
1.766     albertel 5456:     return '';
1.765     albertel 5457: }
                   5458: 
                   5459: sub get_portfolio_access {
1.767     albertel 5460:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5461: 
                   5462:     if (!ref($access_hash)) {
                   5463: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5464: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5465: 						   $file_name);
                   5466: 	$access_hash = $access_controls{$file_name};
                   5467:     }
                   5468: 
1.765     albertel 5469:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5470:     my $now = time;
                   5471:     if (ref($access_hash) eq 'HASH') {
                   5472:         foreach my $key (keys(%{$access_hash})) {
                   5473:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5474:             if ($start > $now) {
                   5475:                 next;
                   5476:             }
                   5477:             if ($end && $end<$now) {
                   5478:                 next;
                   5479:             }
                   5480:             if ($scope eq 'public') {
                   5481:                 $public = $key;
                   5482:                 last;
                   5483:             } elsif ($scope eq 'guest') {
                   5484:                 $guest = $key;
                   5485:             } elsif ($scope eq 'domains') {
                   5486:                 push(@domains,$key);
                   5487:             } elsif ($scope eq 'users') {
                   5488:                 push(@users,$key);
                   5489:             } elsif ($scope eq 'course') {
                   5490:                 push(@courses,$key);
                   5491:             } elsif ($scope eq 'group') {
                   5492:                 push(@groups,$key);
                   5493:             }
                   5494:         }
                   5495:         if ($public) {
                   5496:             return 'ok';
                   5497:         }
                   5498:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5499:             if ($guest) {
                   5500:                 return $guest;
                   5501:             }
                   5502:         } else {
                   5503:             if (@domains > 0) {
                   5504:                 foreach my $domkey (@domains) {
                   5505:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5506:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5507:                             return 'ok';
                   5508:                         }
                   5509:                     }
                   5510:                 }
                   5511:             }
                   5512:             if (@users > 0) {
                   5513:                 foreach my $userkey (@users) {
1.865     raeburn  5514:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5515:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5516:                             if (ref($item) eq 'HASH') {
                   5517:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5518:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5519:                                     return 'ok';
                   5520:                                 }
                   5521:                             }
                   5522:                         }
                   5523:                     } 
1.765     albertel 5524:                 }
                   5525:             }
                   5526:             my %roleshash;
                   5527:             my @courses_and_groups = @courses;
                   5528:             push(@courses_and_groups,@groups); 
                   5529:             if (@courses_and_groups > 0) {
                   5530:                 my (%allgroups,%allroles); 
                   5531:                 my ($start,$end,$role,$sec,$group);
                   5532:                 foreach my $envkey (%env) {
1.1060    raeburn  5533:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5534:                         my $cid = $2.'_'.$3; 
                   5535:                         if ($1 eq 'gr') {
                   5536:                             $group = $4;
                   5537:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5538:                         } else {
                   5539:                             if ($4 eq '') {
                   5540:                                 $sec = 'none';
                   5541:                             } else {
                   5542:                                 $sec = $4;
                   5543:                             }
                   5544:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5545:                         }
1.811     albertel 5546:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5547:                         my $cid = $2.'_'.$3;
                   5548:                         if ($4 eq '') {
                   5549:                             $sec = 'none';
                   5550:                         } else {
                   5551:                             $sec = $4;
                   5552:                         }
                   5553:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5554:                     }
                   5555:                 }
                   5556:                 if (keys(%allroles) == 0) {
                   5557:                     return;
                   5558:                 }
                   5559:                 foreach my $key (@courses_and_groups) {
                   5560:                     my %content = %{$$access_hash{$key}};
                   5561:                     my $cnum = $content{'number'};
                   5562:                     my $cdom = $content{'domain'};
                   5563:                     my $cid = $cdom.'_'.$cnum;
                   5564:                     if (!exists($allroles{$cid})) {
                   5565:                         next;
                   5566:                     }    
                   5567:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5568:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5569:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5570:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5571:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5572:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5573:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5574:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5575:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5576:                                         if (grep/^all$/,@sections) {
                   5577:                                             return 'ok';
                   5578:                                         } else {
                   5579:                                             if (grep/^$sec$/,@sections) {
                   5580:                                                 return 'ok';
                   5581:                                             }
                   5582:                                         }
                   5583:                                     }
                   5584:                                 }
                   5585:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5586:                                     if (grep/^none$/,@groups) {
                   5587:                                         return 'ok';
                   5588:                                     }
                   5589:                                 } else {
                   5590:                                     if (grep/^all$/,@groups) {
                   5591:                                         return 'ok';
                   5592:                                     } 
                   5593:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5594:                                         if (grep/^$group$/,@groups) {
                   5595:                                             return 'ok';
                   5596:                                         }
                   5597:                                     }
                   5598:                                 } 
                   5599:                             }
                   5600:                         }
                   5601:                     }
                   5602:                 }
                   5603:             }
                   5604:             if ($guest) {
                   5605:                 return $guest;
                   5606:             }
                   5607:         }
                   5608:     }
                   5609:     return;
                   5610: }
                   5611: 
                   5612: sub course_group_datechecker {
                   5613:     my ($dates,$now,$status) = @_;
                   5614:     my ($start,$end) = split(/\./,$dates);
                   5615:     if (!$start && !$end) {
                   5616:         return 'ok';
                   5617:     }
                   5618:     if (grep/^active$/,@{$status}) {
                   5619:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5620:             return 'ok';
                   5621:         }
                   5622:     }
                   5623:     if (grep/^previous$/,@{$status}) {
                   5624:         if ($end > $now ) {
                   5625:             return 'ok';
                   5626:         }
                   5627:     }
                   5628:     if (grep/^future$/,@{$status}) {
                   5629:         if ($start > $now) {
                   5630:             return 'ok';
                   5631:         }
                   5632:     }
                   5633:     return; 
                   5634: }
                   5635: 
                   5636: sub parse_portfolio_url {
                   5637:     my ($url) = @_;
                   5638: 
                   5639:     my ($type,$udom,$unum,$group,$file_name);
                   5640:     
1.823     albertel 5641:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5642: 	$type = 1;
                   5643:         $udom = $1;
                   5644:         $unum = $2;
                   5645:         $file_name = $3;
1.823     albertel 5646:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5647: 	$type = 2;
                   5648:         $udom = $1;
                   5649:         $unum = $2;
                   5650:         $group = $3;
                   5651:         $file_name = $3.'/'.$4;
                   5652:     }
                   5653:     if (wantarray) {
                   5654: 	return ($type,$udom,$unum,$file_name,$group);
                   5655:     }
                   5656:     return $type;
                   5657: }
                   5658: 
                   5659: sub is_portfolio_url {
                   5660:     my ($url) = @_;
                   5661:     return scalar(&parse_portfolio_url($url));
                   5662: }
                   5663: 
1.798     raeburn  5664: sub is_portfolio_file {
                   5665:     my ($file) = @_;
1.820     raeburn  5666:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5667:         return 1;
                   5668:     }
                   5669:     return;
                   5670: }
                   5671: 
1.976     raeburn  5672: sub usertools_access {
1.1084    raeburn  5673:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5674:     my ($access,%tools);
                   5675:     if ($context eq '') {
                   5676:         $context = 'tools';
                   5677:     }
                   5678:     if ($context eq 'requestcourses') {
                   5679:         %tools = (
                   5680:                       official   => 1,
                   5681:                       unofficial => 1,
1.1006    raeburn  5682:                       community  => 1,
1.985     raeburn  5683:                  );
1.1172.2.9! raeburn  5684:     } elsif ($context eq 'requestauthor') {
        !          5685:         %tools = (
        !          5686:                       requestauthor => 1,
        !          5687:                  );
1.985     raeburn  5688:     } else {
                   5689:         %tools = (
                   5690:                       aboutme   => 1,
                   5691:                       blog      => 1,
1.1172.2.6  raeburn  5692:                       webdav    => 1,
1.985     raeburn  5693:                       portfolio => 1,
                   5694:                  );
                   5695:     }
1.976     raeburn  5696:     return if (!defined($tools{$tool}));
                   5697: 
                   5698:     if ((!defined($udom)) || (!defined($uname))) {
                   5699:         $udom = $env{'user.domain'};
                   5700:         $uname = $env{'user.name'};
                   5701:     }
                   5702: 
1.978     raeburn  5703:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5704:         if ($action ne 'reload') {
1.985     raeburn  5705:             if ($context eq 'requestcourses') {
                   5706:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9! raeburn  5707:             } elsif ($context eq 'requestauthor') {
        !          5708:                 return $env{'environment.canrequest.author'};
1.985     raeburn  5709:             } else {
                   5710:                 return $env{'environment.availabletools.'.$tool};
                   5711:             }
                   5712:         }
1.976     raeburn  5713:     }
                   5714: 
1.1172.2.9! raeburn  5715:     my ($toolstatus,$inststatus,$envkey);
        !          5716:     if ($context eq 'requestauthor') {
        !          5717:         $envkey = $context;
        !          5718:     } else {
        !          5719:         $envkey = $context.'.'.$tool;
        !          5720:     }
1.976     raeburn  5721: 
1.985     raeburn  5722:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5723:          ($action ne 'reload')) {
1.1172.2.9! raeburn  5724:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  5725:         $inststatus = $env{'environment.inststatus'};
                   5726:     } else {
1.1084    raeburn  5727:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9! raeburn  5728:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  5729:             $inststatus = $userenvref->{'inststatus'};
                   5730:         } else {
1.1172.2.9! raeburn  5731:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
        !          5732:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  5733:             $inststatus = $userenv{'inststatus'};
                   5734:         }
1.976     raeburn  5735:     }
                   5736: 
                   5737:     if ($toolstatus ne '') {
                   5738:         if ($toolstatus) {
                   5739:             $access = 1;
                   5740:         } else {
                   5741:             $access = 0;
                   5742:         }
                   5743:         return $access;
                   5744:     }
                   5745: 
1.1084    raeburn  5746:     my ($is_adv,%domdef);
                   5747:     if (ref($is_advref) eq 'HASH') {
                   5748:         $is_adv = $is_advref->{'is_adv'};
                   5749:     } else {
                   5750:         $is_adv = &is_advanced_user($udom,$uname);
                   5751:     }
                   5752:     if (ref($domdefref) eq 'HASH') {
                   5753:         %domdef = %{$domdefref};
                   5754:     } else {
                   5755:         %domdef = &get_domain_defaults($udom);
                   5756:     }
1.976     raeburn  5757:     if (ref($domdef{$tool}) eq 'HASH') {
                   5758:         if ($is_adv) {
                   5759:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5760:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5761:                     $access = 1;
                   5762:                 } else {
                   5763:                     $access = 0;
                   5764:                 }
                   5765:                 return $access;
                   5766:             }
                   5767:         }
                   5768:         if ($inststatus ne '') {
                   5769:             my ($hasaccess,$hasnoaccess);
                   5770:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5771:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5772:                     if ($domdef{$tool}{$affiliation}) {
                   5773:                         $hasaccess = 1;
                   5774:                     } else {
                   5775:                         $hasnoaccess = 1;
                   5776:                     }
                   5777:                 }
                   5778:             }
                   5779:             if ($hasaccess || $hasnoaccess) {
                   5780:                 if ($hasaccess) {
                   5781:                     $access = 1;
                   5782:                 } elsif ($hasnoaccess) {
                   5783:                     $access = 0; 
                   5784:                 }
                   5785:                 return $access;
                   5786:             }
                   5787:         } else {
                   5788:             if ($domdef{$tool}{'default'} ne '') {
                   5789:                 if ($domdef{$tool}{'default'}) {
                   5790:                     $access = 1;
                   5791:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5792:                     $access = 0;
                   5793:                 }
                   5794:                 return $access;
                   5795:             }
                   5796:         }
                   5797:     } else {
1.1172.2.6  raeburn  5798:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  5799:             $access = 1;
                   5800:         } else {
                   5801:             $access = 0;
                   5802:         }
1.976     raeburn  5803:         return $access;
                   5804:     }
                   5805: }
                   5806: 
1.1050    raeburn  5807: sub is_course_owner {
                   5808:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5809:     if (($udom eq '') || ($uname eq '')) {
                   5810:         $udom = $env{'user.domain'};
                   5811:         $uname = $env{'user.name'};
                   5812:     }
                   5813:     unless (($udom eq '') || ($uname eq '')) {
                   5814:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5815:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5816:                 return 1;
                   5817:             } else {
                   5818:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5819:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5820:                     return 1;
                   5821:                 }
                   5822:             }
                   5823:         }
                   5824:     }
                   5825:     return;
                   5826: }
                   5827: 
1.976     raeburn  5828: sub is_advanced_user {
                   5829:     my ($udom,$uname) = @_;
1.1085    raeburn  5830:     if ($udom ne '' && $uname ne '') {
                   5831:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  5832:             if (wantarray) {
                   5833:                 return ($env{'user.adv'},$env{'user.author'});
                   5834:             } else {
                   5835:                 return $env{'user.adv'};
                   5836:             }
1.1085    raeburn  5837:         }
                   5838:     }
1.976     raeburn  5839:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5840:     my %allroles;
1.1128    raeburn  5841:     my ($is_adv,$is_author);
1.976     raeburn  5842:     foreach my $role (keys(%roleshash)) {
                   5843:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5844:         my $area = '/'.$tdomain.'/'.$trest;
                   5845:         if ($sec ne '') {
                   5846:             $area .= '/'.$sec;
                   5847:         }
                   5848:         if (($area ne '') && ($trole ne '')) {
                   5849:             my $spec=$trole.'.'.$area;
                   5850:             if ($trole =~ /^cr\//) {
                   5851:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5852:             } elsif ($trole ne 'gr') {
                   5853:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5854:             }
1.1128    raeburn  5855:             if ($trole eq 'au') {
                   5856:                 $is_author = 1;
                   5857:             }
1.976     raeburn  5858:         }
                   5859:     }
                   5860:     foreach my $role (keys(%allroles)) {
                   5861:         last if ($is_adv);
                   5862:         foreach my $item (split(/:/,$allroles{$role})) {
                   5863:             if ($item ne '') {
                   5864:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5865:                 if ($privilege eq 'adv') {
                   5866:                     $is_adv = 1;
                   5867:                     last;
                   5868:                 }
                   5869:             }
                   5870:         }
                   5871:     }
1.1128    raeburn  5872:     if (wantarray) {
                   5873:         return ($is_adv,$is_author);
                   5874:     }
1.976     raeburn  5875:     return $is_adv;
                   5876: }
1.798     raeburn  5877: 
1.1035    raeburn  5878: sub check_can_request {
1.1036    raeburn  5879:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5880:     my $canreq = 0;
                   5881:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5882:     my @options = ('approval','validate','autolimit');
                   5883:     my $optregex = join('|',@options);
                   5884:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5885:         foreach my $type (@{$types}) {
                   5886:             if (&usertools_access($env{'user.name'},
                   5887:                                   $env{'user.domain'},
                   5888:                                   $type,undef,'requestcourses')) {
                   5889:                 $canreq ++;
1.1036    raeburn  5890:                 if (ref($request_domains) eq 'HASH') {
                   5891:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5892:                 }
1.1035    raeburn  5893:                 if ($dom eq $env{'user.domain'}) {
                   5894:                     $can_request->{$type} = 1;
                   5895:                 }
                   5896:             }
                   5897:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5898:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5899:                 if (@curr > 0) {
1.1036    raeburn  5900:                     foreach my $item (@curr) {
                   5901:                         if (ref($request_domains) eq 'HASH') {
                   5902:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5903:                             if ($otherdom ne '') {
                   5904:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5905:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5906:                                         push(@{$request_domains->{$type}},$otherdom);
                   5907:                                     }
                   5908:                                 } else {
                   5909:                                     push(@{$request_domains->{$type}},$otherdom);
                   5910:                                 }
                   5911:                             }
                   5912:                         }
                   5913:                     }
                   5914:                     unless($dom eq $env{'user.domain'}) {
                   5915:                         $canreq ++;
1.1035    raeburn  5916:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5917:                             $can_request->{$type} = 1;
                   5918:                         }
                   5919:                     }
                   5920:                 }
                   5921:             }
                   5922:         }
                   5923:     }
                   5924:     return $canreq;
                   5925: }
                   5926: 
1.341     www      5927: # ---------------------------------------------- Custom access rule evaluation
                   5928: 
                   5929: sub customaccess {
                   5930:     my ($priv,$uri)=@_;
1.807     albertel 5931:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5932:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5933:     $udom = &LONCAPA::clean_domain($udom);
                   5934:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5935:     my $access=0;
1.800     albertel 5936:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5937: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5938: 	if ($type eq 'user') {
                   5939: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5940: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5941: 		if ($tdom) {
                   5942: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5943: 		}
1.896     albertel 5944: 		if ($tuname) {
                   5945: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5946: 		}
                   5947: 		$access=($effect eq 'allow');
                   5948: 		last;
                   5949: 	    }
                   5950: 	} else {
                   5951: 	    if ($role) {
                   5952: 		if ($role ne $urole) { next; }
                   5953: 	    }
                   5954: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5955: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5956: 		if ($tdom) {
                   5957: 		    if ($tdom ne $udom) { next; }
                   5958: 		}
                   5959: 		if ($tcrs) {
                   5960: 		    if ($tcrs ne $ucrs) { next; }
                   5961: 		}
                   5962: 		if ($tsec) {
                   5963: 		    if ($tsec ne $usec) { next; }
                   5964: 		}
                   5965: 		$access=($effect eq 'allow');
                   5966: 		last;
                   5967: 	    }
                   5968: 	    if ($realm eq '' && $role eq '') {
                   5969: 		$access=($effect eq 'allow');
                   5970: 	    }
1.402     bowersj2 5971: 	}
1.341     www      5972:     }
                   5973:     return $access;
                   5974: }
                   5975: 
1.103     harris41 5976: # ------------------------------------------------- Check for a user privilege
1.12      www      5977: 
                   5978: sub allowed {
1.810     raeburn  5979:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5980:     my $ver_orguri=$uri;
1.439     www      5981:     $uri=&deversion($uri);
1.152     www      5982:     my $orguri=$uri;
1.52      www      5983:     $uri=&declutter($uri);
1.809     raeburn  5984: 
1.810     raeburn  5985:     if ($priv eq 'evb') {
                   5986: # Evade communication block restrictions for specified role in a course
                   5987:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5988:             return $1;
                   5989:         } else {
                   5990:             return;
                   5991:         }
                   5992:     }
                   5993: 
1.620     albertel 5994:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5995: # Free bre access to adm and meta resources
1.775     albertel 5996:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5997: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5998: 	&& ($priv eq 'bre')) {
1.14      www      5999: 	return 'F';
1.159     www      6000:     }
                   6001: 
1.545     banghart 6002: # Free bre access to user's own portfolio contents
1.714     raeburn  6003:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6004:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6005: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6006:         my %setters;
                   6007:         my ($startblock,$endblock) = 
                   6008:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6009:         if ($startblock && $endblock) {
                   6010:             return 'B';
                   6011:         } else {
                   6012:             return 'F';
                   6013:         }
1.545     banghart 6014:     }
                   6015: 
1.762     raeburn  6016: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6017:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6018:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6019:         if (exists($env{'request.course.id'})) {
                   6020:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6021:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6022:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6023:                 my $courseprivid=$env{'request.course.id'};
                   6024:                 $courseprivid=~s/\_/\//;
                   6025:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6026:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6027:                     return $1; 
1.762     raeburn  6028:                 } else {
                   6029:                     if ($env{'request.course.sec'}) {
                   6030:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6031:                     }
                   6032:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6033:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6034:                         return $2;
                   6035:                     }
1.714     raeburn  6036:                 }
                   6037:             }
                   6038:         }
                   6039:     }
                   6040: 
1.159     www      6041: # Free bre to public access
                   6042: 
                   6043:     if ($priv eq 'bre') {
1.238     www      6044:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6045: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6046:            return 'F'; 
                   6047:         }
1.238     www      6048:         if ($copyright eq 'priv') {
                   6049:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6050: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6051: 		return '';
                   6052:             }
                   6053:         }
                   6054:         if ($copyright eq 'domain') {
                   6055:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6056: 	    unless (($env{'user.domain'} eq $1) ||
                   6057:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6058: 		return '';
                   6059:             }
1.262     matthew  6060:         }
1.620     albertel 6061:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6062:             # Library role, so allow browsing of resources in this domain.
                   6063:             return 'F';
1.238     www      6064:         }
1.341     www      6065:         if ($copyright eq 'custom') {
                   6066: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6067:         }
1.14      www      6068:     }
1.264     matthew  6069:     # Domain coordinator is trying to create a course
1.620     albertel 6070:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6071:         # uri is the requested domain in this case.
                   6072:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6073:         # a role of dc for the domain in question.
1.620     albertel 6074:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6075:     }
1.29      www      6076: 
1.52      www      6077:     my $thisallowed='';
                   6078:     my $statecond=0;
                   6079:     my $courseprivid='';
                   6080: 
1.1039    raeburn  6081:     my $ownaccess;
1.1043    raeburn  6082:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6083:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6084:         if ($uri eq '') {
                   6085:             $ownaccess = 1;
                   6086:         } else {
                   6087:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6088:                 my $udom = $env{'user.domain'};
                   6089:                 my $uname = $env{'user.name'};
                   6090:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6091:                     $ownaccess = 1;
1.1040    raeburn  6092:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6093:                     unless ($uri =~ m{\.\./}) {
                   6094:                         $ownaccess = 1;
                   6095:                     }
                   6096:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6097:                     my $now = time;
                   6098:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6099:                         my $adom = $1;
                   6100:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6101:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6102:                                 my ($start,$end) = split('.',$env{$key});
                   6103:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6104:                                     $ownaccess = 1;
                   6105:                                     last;
                   6106:                                 }
                   6107:                             }
                   6108:                         }
                   6109:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6110:                         my $adom = $1;
                   6111:                         my $aname = $2;
1.1042    raeburn  6112:                         foreach my $role ('ca','aa') { 
                   6113:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6114:                                 my ($start,$end) =
                   6115:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6116:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6117:                                     $ownaccess = 1;
                   6118:                                     last;
                   6119:                                 }
1.1039    raeburn  6120:                             }
                   6121:                         }
                   6122:                     }
                   6123:                 }
                   6124:             }
                   6125:         }
                   6126:     }
                   6127: 
1.52      www      6128: # Course
                   6129: 
1.620     albertel 6130:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6131:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6132:             $thisallowed.=$1;
                   6133:         }
1.52      www      6134:     }
1.29      www      6135: 
1.52      www      6136: # Domain
                   6137: 
1.620     albertel 6138:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6139:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6140:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6141:             $thisallowed.=$1;
                   6142:         }
1.12      www      6143:     }
1.52      www      6144: 
1.1141    raeburn  6145: # User who is not author or co-author might still be able to edit
                   6146: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6147:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6148:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6149:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6150:             $thisallowed.=$1;
                   6151:         }
                   6152:     }
                   6153: 
1.52      www      6154: # Course: uri itself is a course
1.66      www      6155:     my $courseuri=$uri;
                   6156:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6157:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6158: 
1.620     albertel 6159:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6160:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6161:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6162:             $thisallowed.=$1;
                   6163:         }
1.12      www      6164:     }
1.29      www      6165: 
1.665     albertel 6166: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6167: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6168:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6169: 	$thisallowed='';
1.671     raeburn  6170:         my ($match)=&is_on_map($uri);
                   6171:         if ($match) {
                   6172:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6173:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6174:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6175:                 if (@blockers > 0) {
                   6176:                     $thisallowed = 'B';
                   6177:                 } else {
                   6178:                     $thisallowed.=$1;
                   6179:                 }
1.671     raeburn  6180:             }
                   6181:         } else {
1.705     albertel 6182:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6183:             if ($refuri) {
                   6184:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6185:                     $thisallowed='F';
1.671     raeburn  6186:                 } else {
                   6187:                     $refuri=&declutter($refuri);
                   6188:                     my ($match) = &is_on_map($refuri);
                   6189:                     if ($match) {
1.1162    raeburn  6190:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6191:                         if (@blockers > 0) {
                   6192:                             $thisallowed = 'B';
                   6193:                         } else {
                   6194:                             $thisallowed='F';
                   6195:                         }
1.671     raeburn  6196:                     }
1.669     raeburn  6197:                 }
1.671     raeburn  6198:             }
                   6199:         }
1.314     www      6200:     }
1.492     albertel 6201: 
1.766     albertel 6202:     if ($priv eq 'bre'
                   6203: 	&& $thisallowed ne 'F' 
                   6204: 	&& $thisallowed ne '2'
                   6205: 	&& &is_portfolio_url($uri)) {
                   6206: 	$thisallowed = &portfolio_access($uri);
                   6207:     }
                   6208:     
1.52      www      6209: # Full access at system, domain or course-wide level? Exit.
1.29      www      6210:     if ($thisallowed=~/F/) {
                   6211: 	return 'F';
                   6212:     }
                   6213: 
1.52      www      6214: # If this is generating or modifying users, exit with special codes
1.29      www      6215: 
1.643     www      6216:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6217: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6218: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6219: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6220: 	    unless ($auname) { return $thisallowed; }
                   6221: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6222: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6223: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6224: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6225: 	}
1.52      www      6226: 	return $thisallowed;
                   6227:     }
                   6228: #
1.103     harris41 6229: # Gathered so far: system, domain and course wide privileges
1.52      www      6230: #
                   6231: # Course: See if uri or referer is an individual resource that is part of 
                   6232: # the course
                   6233: 
1.620     albertel 6234:     if ($env{'request.course.id'}) {
1.232     www      6235: 
1.620     albertel 6236:        $courseprivid=$env{'request.course.id'};
                   6237:        if ($env{'request.course.sec'}) {
                   6238:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6239:        }
                   6240:        $courseprivid=~s/\_/\//;
                   6241:        my $checkreferer=1;
1.232     www      6242:        my ($match,$cond)=&is_on_map($uri);
                   6243:        if ($match) {
                   6244:            $statecond=$cond;
1.620     albertel 6245:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6246:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6247:                my $value = $1;
                   6248:                if ($priv eq 'bre') {
                   6249:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6250:                    if (@blockers > 0) {
                   6251:                        $thisallowed = 'B';
                   6252:                    } else {
                   6253:                        $thisallowed.=$value;
                   6254:                    }
                   6255:                } else {
                   6256:                    $thisallowed.=$value;
                   6257:                }
1.52      www      6258:                $checkreferer=0;
                   6259:            }
1.29      www      6260:        }
1.83      www      6261:        
1.148     www      6262:        if ($checkreferer) {
1.620     albertel 6263: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6264:             unless ($refuri) {
1.800     albertel 6265:                 foreach my $key (keys(%env)) {
                   6266: 		    if ($key=~/^httpref\..*\*/) {
                   6267: 			my $pattern=$key;
1.156     www      6268:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6269:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6270:                         $pattern=~s/\//\\\//g;
1.152     www      6271:                         if ($orguri=~/$pattern/) {
1.800     albertel 6272: 			    $refuri=$env{$key};
1.148     www      6273:                         }
                   6274:                     }
1.191     harris41 6275:                 }
1.148     www      6276:             }
1.232     www      6277: 
1.148     www      6278:          if ($refuri) { 
1.152     www      6279: 	  $refuri=&declutter($refuri);
1.232     www      6280:           my ($match,$cond)=&is_on_map($refuri);
                   6281:             if ($match) {
                   6282:               my $refstatecond=$cond;
1.620     albertel 6283:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6284:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6285:                   my $value = $1;
                   6286:                   if ($priv eq 'bre') {
                   6287:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6288:                       if (@blockers > 0) {
                   6289:                           $thisallowed = 'B';
                   6290:                       } else {
                   6291:                           $thisallowed.=$value;
                   6292:                       }
                   6293:                   } else {
                   6294:                       $thisallowed.=$value;
                   6295:                   }
1.53      www      6296:                   $uri=$refuri;
                   6297:                   $statecond=$refstatecond;
1.52      www      6298:               }
                   6299:           }
1.148     www      6300:         }
1.29      www      6301:        }
1.52      www      6302:    }
1.29      www      6303: 
1.52      www      6304: #
1.103     harris41 6305: # Gathered now: all privileges that could apply, and condition number
1.52      www      6306: # 
                   6307: #
                   6308: # Full or no access?
                   6309: #
1.29      www      6310: 
1.52      www      6311:     if ($thisallowed=~/F/) {
                   6312: 	return 'F';
                   6313:     }
1.29      www      6314: 
1.52      www      6315:     unless ($thisallowed) {
                   6316:         return '';
                   6317:     }
1.29      www      6318: 
1.52      www      6319: # Restrictions exist, deal with them
                   6320: #
                   6321: #   C:according to course preferences
                   6322: #   R:according to resource settings
                   6323: #   L:unless locked
                   6324: #   X:according to user session state
                   6325: #
                   6326: 
                   6327: # Possibly locked functionality, check all courses
1.54      www      6328: # Locks might take effect only after 10 minutes cache expiration for other
                   6329: # courses, and 2 minutes for current course
1.52      www      6330: 
                   6331:     my $envkey;
                   6332:     if ($thisallowed=~/L/) {
1.1000    raeburn  6333:         foreach $envkey (keys(%env)) {
1.54      www      6334:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6335:                my $courseid=$2;
                   6336:                my $roleid=$1.'.'.$2;
1.92      www      6337:                $courseid=~s/^\///;
1.54      www      6338:                my $expiretime=600;
1.620     albertel 6339:                if ($env{'request.role'} eq $roleid) {
1.54      www      6340: 		  $expiretime=120;
                   6341:                }
                   6342: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6343:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6344:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6345: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6346:                }
1.620     albertel 6347:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6348:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6349: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6350:                        &log($env{'user.domain'},$env{'user.name'},
                   6351:                             $env{'user.home'},
1.57      www      6352:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6353:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6354:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6355: 		       return '';
                   6356:                    }
                   6357:                }
1.620     albertel 6358:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6359:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6360: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6361:                        &log($env{'user.domain'},$env{'user.name'},
                   6362:                             $env{'user.home'},
1.57      www      6363:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6364:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6365:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6366: 		       return '';
                   6367:                    }
                   6368:                }
                   6369: 	   }
1.29      www      6370:        }
1.52      www      6371:     }
                   6372:    
                   6373: #
                   6374: # Rest of the restrictions depend on selected course
                   6375: #
                   6376: 
1.620     albertel 6377:     unless ($env{'request.course.id'}) {
1.766     albertel 6378: 	if ($thisallowed eq 'A') {
                   6379: 	    return 'A';
1.814     raeburn  6380:         } elsif ($thisallowed eq 'B') {
                   6381:             return 'B';
1.766     albertel 6382: 	} else {
                   6383: 	    return '1';
                   6384: 	}
1.52      www      6385:     }
1.29      www      6386: 
1.52      www      6387: #
                   6388: # Now user is definitely in a course
                   6389: #
1.53      www      6390: 
                   6391: 
                   6392: # Course preferences
                   6393: 
                   6394:    if ($thisallowed=~/C/) {
1.620     albertel 6395:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6396:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6397:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6398: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6399: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6400: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6401: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6402: 			$env{'request.course.id'});
                   6403: 	   }
1.237     www      6404:            return '';
                   6405:        }
                   6406: 
1.620     albertel 6407:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6408: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6409: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6410: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6411: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6412: 			$env{'request.course.id'});
                   6413: 	   }
1.54      www      6414:            return '';
                   6415:        }
1.53      www      6416:    }
                   6417: 
                   6418: # Resource preferences
                   6419: 
                   6420:    if ($thisallowed=~/R/) {
1.620     albertel 6421:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6422:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6423: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6424: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6425: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6426: 	   }
                   6427: 	   return '';
1.54      www      6428:        }
1.53      www      6429:    }
1.30      www      6430: 
1.246     www      6431: # Restricted by state or randomout?
1.30      www      6432: 
1.52      www      6433:    if ($thisallowed=~/X/) {
1.620     albertel 6434:       if ($env{'acc.randomout'}) {
1.579     albertel 6435: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6436:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6437:             return ''; 
                   6438:          }
1.247     www      6439:       }
                   6440:       if (&condval($statecond)) {
1.52      www      6441: 	 return '2';
                   6442:       } else {
                   6443:          return '';
                   6444:       }
                   6445:    }
1.30      www      6446: 
1.766     albertel 6447:     if ($thisallowed eq 'A') {
                   6448: 	return 'A';
1.814     raeburn  6449:     } elsif ($thisallowed eq 'B') {
                   6450:         return 'B';
1.766     albertel 6451:     }
1.52      www      6452:    return 'F';
1.232     www      6453: }
1.1162    raeburn  6454: 
                   6455: sub get_comm_blocks {
                   6456:     my ($cdom,$cnum) = @_;
                   6457:     if ($cdom eq '' || $cnum eq '') {
                   6458:         return unless ($env{'request.course.id'});
                   6459:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6460:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6461:     }
                   6462:     my %commblocks;
                   6463:     my $hashid=$cdom.'_'.$cnum;
                   6464:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6465:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6466:         %commblocks = %{$blocksref};
                   6467:     } else {
                   6468:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6469:         my $cachetime = 600;
                   6470:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6471:     }
                   6472:     return %commblocks;
                   6473: }
                   6474: 
                   6475: sub has_comm_blocking {
                   6476:     my ($priv,$symb,$uri,$blocks) = @_;
                   6477:     return unless ($env{'request.course.id'});
                   6478:     return unless ($priv eq 'bre');
                   6479:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6480:     my %commblocks;
                   6481:     if (ref($blocks) eq 'HASH') {
                   6482:         %commblocks = %{$blocks};
                   6483:     } else {
                   6484:         %commblocks = &get_comm_blocks();
                   6485:     }
                   6486:     return unless (keys(%commblocks) > 0);
                   6487:     if (!$symb) { $symb=&symbread($uri,1); }
                   6488:     my ($map,$resid,undef)=&decode_symb($symb);
                   6489:     my %tocheck = (
                   6490:                     maps      => $map,
                   6491:                     resources => $symb,
                   6492:                   );
                   6493:     my @blockers;
                   6494:     my $now = time;
1.1163    raeburn  6495:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6496:     foreach my $block (keys(%commblocks)) {
                   6497:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6498:             my ($start,$end) = ($1,$2);
                   6499:             if ($start <= $now && $end >= $now) {
                   6500:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6501:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6502:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6503:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6504:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6505:                                     push(@blockers,$block);
                   6506:                                 }
                   6507:                             }
                   6508:                         }
                   6509:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6510:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6511:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6512:                                     push(@blockers,$block);
                   6513:                                 }
                   6514:                             }
                   6515:                         }
                   6516:                     }
                   6517:                 }
                   6518:             }
                   6519:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6520:             my $item = $1;
1.1163    raeburn  6521:             my @to_test;
1.1162    raeburn  6522:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6523:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6524:                     my $check_interval;
                   6525:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6526:                         my @interval;
                   6527:                         my $type = 'map';
                   6528:                         if ($item eq 'course') {
                   6529:                             $type = 'course';
                   6530:                             @interval=&EXT("resource.0.interval");
                   6531:                         } else {
                   6532:                             if ($item =~ /___\d+___/) {
                   6533:                                 $type = 'resource';
                   6534:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  6535:                                 if (ref($navmap)) {                        
                   6536:                                     my $res = $navmap->getBySymb($item); 
                   6537:                                     push(@to_test,$res);
                   6538:                                 }
1.1162    raeburn  6539:                             } else {
                   6540:                                 my $mapsymb = &symbread($item,1);
                   6541:                                 if ($mapsymb) {
                   6542:                                     if (ref($navmap)) {
                   6543:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  6544:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   6545:                                         foreach my $res (@to_test) {
1.1162    raeburn  6546:                                             my $symb = $res->symb();
                   6547:                                             next if ($symb eq $mapsymb);
                   6548:                                             if ($symb ne '') {
                   6549:                                                 @interval=&EXT("resource.0.interval",$symb);
                   6550:                                                 last;
                   6551:                                             }
                   6552:                                         }
                   6553:                                     }
                   6554:                                 }
                   6555:                             }
                   6556:                         }
                   6557:                         if ($interval[0] =~ /\d+/) {
                   6558:                             my $first_access;
                   6559:                             if ($type eq 'resource') {
                   6560:                                 $first_access=&get_first_access($interval[1],$item);
                   6561:                             } elsif ($type eq 'map') {
                   6562:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   6563:                             } else {
                   6564:                                 $first_access=&get_first_access($interval[1]);
                   6565:                             }
                   6566:                             if ($first_access) {
                   6567:                                 my $timesup = $first_access+$interval[0];
                   6568:                                 if ($timesup > $now) {
1.1163    raeburn  6569:                                     foreach my $res (@to_test) {
                   6570:                                         if ($res->is_problem()) {
                   6571:                                             if ($res->completable()) {
                   6572:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6573:                                                     push(@blockers,$block);
                   6574:                                                 }
                   6575:                                                 last;
                   6576:                                             }
                   6577:                                         }
1.1162    raeburn  6578:                                     }
                   6579:                                 }
                   6580:                             }
                   6581:                         }
                   6582:                     }
                   6583:                 }
                   6584:             }
                   6585:         }
                   6586:     }
                   6587:     return @blockers;
                   6588: }
                   6589: 
                   6590: sub check_docs_block {
                   6591:     my ($docsblock,$tocheck) =@_;
                   6592:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   6593:         return;
                   6594:     }
                   6595:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   6596:         if ($tocheck->{'maps'}) {
                   6597:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   6598:                 return 1;
                   6599:             }
                   6600:         }
                   6601:     }
                   6602:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   6603:         if ($tocheck->{'resources'}) {
                   6604:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   6605:                 return 1;
                   6606:             }
                   6607:         }
                   6608:     }
                   6609:     return;
                   6610: }
                   6611: 
1.1133    foxr     6612: #
                   6613: #   Removes the versino from a URI and
                   6614: #   splits it in to its filename and path to the filename.
                   6615: #   Seems like File::Basename could have done this more clearly.
                   6616: #   Parameters:
                   6617: #      $uri   - input URI
                   6618: #   Returns:
                   6619: #     Two element list consisting of 
                   6620: #     $pathname  - the URI up to and excluding the trailing /
                   6621: #     $filename  - The part of the URI following the last /
                   6622: #  NOTE:
                   6623: #    Another realization of this is simply:
                   6624: #    use File::Basename;
                   6625: #    ...
                   6626: #    $uri = shift;
                   6627: #    $filename = basename($uri);
                   6628: #    $path     = dirname($uri);
                   6629: #    return ($filename, $path);
                   6630: #
                   6631: #     The implementation below is probably faster however.
                   6632: #
1.710     albertel 6633: sub split_uri_for_cond {
                   6634:     my $uri=&deversion(&declutter(shift));
                   6635:     my @uriparts=split(/\//,$uri);
                   6636:     my $filename=pop(@uriparts);
                   6637:     my $pathname=join('/',@uriparts);
                   6638:     return ($pathname,$filename);
                   6639: }
1.232     www      6640: # --------------------------------------------------- Is a resource on the map?
                   6641: 
                   6642: sub is_on_map {
1.710     albertel 6643:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 6644:     #Trying to find the conditional for the file
1.620     albertel 6645:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 6646: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      6647:     if ($match) {
1.289     bowersj2 6648: 	return (1,$1);
                   6649:     } else {
1.434     www      6650: 	return (0,0);
1.289     bowersj2 6651:     }
1.12      www      6652: }
                   6653: 
1.427     www      6654: # --------------------------------------------------------- Get symb from alias
                   6655: 
                   6656: sub get_symb_from_alias {
                   6657:     my $symb=shift;
                   6658:     my ($map,$resid,$url)=&decode_symb($symb);
                   6659: # Already is a symb
                   6660:     if ($url) { return $symb; }
                   6661: # Must be an alias
                   6662:     my $aliassymb='';
                   6663:     my %bighash;
1.620     albertel 6664:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      6665:                             &GDBM_READER(),0640)) {
                   6666:         my $rid=$bighash{'mapalias_'.$symb};
                   6667: 	if ($rid) {
                   6668: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 6669: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   6670: 				    $resid,$bighash{'src_'.$rid});
1.427     www      6671: 	}
                   6672:         untie %bighash;
                   6673:     }
                   6674:     return $aliassymb;
                   6675: }
                   6676: 
1.12      www      6677: # ----------------------------------------------------------------- Define Role
                   6678: 
                   6679: sub definerole {
                   6680:   if (allowed('mcr','/')) {
                   6681:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 6682:     foreach my $role (split(':',$sysrole)) {
                   6683: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6684:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   6685:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   6686: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6687:                return "refused:s:$crole&$cqual"; 
                   6688:             }
                   6689:         }
1.191     harris41 6690:     }
1.800     albertel 6691:     foreach my $role (split(':',$domrole)) {
                   6692: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6693:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   6694:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   6695: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      6696:                return "refused:d:$crole&$cqual"; 
                   6697:             }
                   6698:         }
1.191     harris41 6699:     }
1.800     albertel 6700:     foreach my $role (split(':',$courole)) {
                   6701: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6702:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   6703:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   6704: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6705:                return "refused:c:$crole&$cqual"; 
                   6706:             }
                   6707:         }
1.191     harris41 6708:     }
1.620     albertel 6709:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   6710:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6711: 	        "rolesdef_$rolename=".
                   6712:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 6713:     return reply($command,$env{'user.home'});
1.12      www      6714:   } else {
                   6715:     return 'refused';
                   6716:   }
1.105     harris41 6717: }
                   6718: 
                   6719: # ---------------- Make a metadata query against the network of library servers
                   6720: 
                   6721: sub metadata_query {
1.244     matthew  6722:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6723:     my %rhash;
1.845     albertel 6724:     my %libserv = &all_library();
1.244     matthew  6725:     my @server_list = (defined($server_array) ? @$server_array
                   6726:                                               : keys(%libserv) );
                   6727:     for my $server (@server_list) {
1.118     harris41 6728: 	unless ($custom or $customshow) {
                   6729: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6730: 	    $rhash{$server}=$reply;
                   6731: 	}
                   6732: 	else {
                   6733: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6734: 			     &escape($custom).':'.&escape($customshow),
                   6735: 			     $server);
                   6736: 	    $rhash{$server}=$reply;
                   6737: 	}
1.112     harris41 6738:     }
1.118     harris41 6739:     return \%rhash;
1.240     www      6740: }
                   6741: 
                   6742: # ----------------------------------------- Send log queries and wait for reply
                   6743: 
                   6744: sub log_query {
                   6745:     my ($uname,$udom,$query,%filters)=@_;
                   6746:     my $uhome=&homeserver($uname,$udom);
                   6747:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6748:     my $uhost=&hostname($uhome);
1.800     albertel 6749:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6750:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6751:                        $uhome);
1.479     albertel 6752:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6753:     return get_query_reply($queryid);
                   6754: }
                   6755: 
1.818     raeburn  6756: # -------------------------- Update MySQL table for portfolio file
                   6757: 
                   6758: sub update_portfolio_table {
1.821     raeburn  6759:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6760:     if ($group ne '') {
                   6761:         $file_name =~s /^\Q$group\E//;
                   6762:     }
1.818     raeburn  6763:     my $homeserver = &homeserver($uname,$udom);
                   6764:     my $queryid=
1.821     raeburn  6765:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6766:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6767:     my $reply = &get_query_reply($queryid);
                   6768:     return $reply;
                   6769: }
                   6770: 
1.899     raeburn  6771: # -------------------------- Update MySQL allusers table
                   6772: 
                   6773: sub update_allusers_table {
                   6774:     my ($uname,$udom,$names) = @_;
                   6775:     my $homeserver = &homeserver($uname,$udom);
                   6776:     my $queryid=
                   6777:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6778:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6779:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6780:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6781:                'generation='.&escape($names->{'generation'}).'%%'.
                   6782:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6783:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6784:     return;
1.899     raeburn  6785: }
                   6786: 
1.508     raeburn  6787: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6788: 
                   6789: sub fetch_enrollment_query {
1.511     raeburn  6790:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6791:     my $homeserver;
1.547     raeburn  6792:     my $maxtries = 1;
1.508     raeburn  6793:     if ($context eq 'automated') {
                   6794:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6795:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6796:     } else {
                   6797:         $homeserver = &homeserver($cnum,$dom);
                   6798:     }
1.838     albertel 6799:     my $host=&hostname($homeserver);
1.506     raeburn  6800:     my $cmd = '';
1.1000    raeburn  6801:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6802:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6803:     }
                   6804:     $cmd =~ s/%%$//;
                   6805:     $cmd = &escape($cmd);
                   6806:     my $query = 'fetchenrollment';
1.620     albertel 6807:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6808:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6809:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6810:         return 'error: '.$queryid;
                   6811:     }
1.506     raeburn  6812:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6813:     my $tries = 1;
                   6814:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6815:         $reply = &get_query_reply($queryid);
                   6816:         $tries ++;
                   6817:     }
1.526     raeburn  6818:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6819:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6820:     } else {
1.901     albertel 6821:         my @responses = split(/:/,$reply);
1.515     raeburn  6822:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6823:             foreach my $line (@responses) {
                   6824:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6825:                 $$replyref{$key} = $value;
                   6826:             }
                   6827:         } else {
1.1117    foxr     6828:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6829:             foreach my $line (@responses) {
                   6830:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6831:                 $$replyref{$key} = $value;
                   6832:                 if ($value > 0) {
1.800     albertel 6833:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6834:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6835:                         my $destname = $pathname.'/'.$filename;
                   6836:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6837:                         if ($xml_classlist =~ /^error/) {
                   6838:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6839:                         } else {
1.506     raeburn  6840:                             if ( open(FILE,">$destname") ) {
                   6841:                                 print FILE &unescape($xml_classlist);
                   6842:                                 close(FILE);
1.526     raeburn  6843:                             } else {
                   6844:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6845:                             }
                   6846:                         }
                   6847:                     }
                   6848:                 }
                   6849:             }
                   6850:         }
                   6851:         return 'ok';
                   6852:     }
                   6853:     return 'error';
                   6854: }
                   6855: 
1.242     www      6856: sub get_query_reply {
                   6857:     my $queryid=shift;
1.1117    foxr     6858:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6859:     my $reply='';
                   6860:     for (1..100) {
                   6861: 	sleep 2;
                   6862:         if (-e $replyfile.'.end') {
1.448     albertel 6863: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6864: 		$reply = join('',<$fh>);
                   6865: 		close($fh);
1.240     www      6866: 	   } else { return 'error: reply_file_error'; }
1.242     www      6867:            return &unescape($reply);
                   6868: 	}
1.240     www      6869:     }
1.242     www      6870:     return 'timeout:'.$queryid;
1.240     www      6871: }
                   6872: 
                   6873: sub courselog_query {
1.241     www      6874: #
                   6875: # possible filters:
                   6876: # url: url or symb
                   6877: # username
                   6878: # domain
                   6879: # action: view, submit, grade
                   6880: # start: timestamp
                   6881: # end: timestamp
                   6882: #
1.240     www      6883:     my (%filters)=@_;
1.620     albertel 6884:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6885:     if ($filters{'url'}) {
                   6886: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6887:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6888:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6889:     }
1.620     albertel 6890:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6891:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6892:     return &log_query($cname,$cdom,'courselog',%filters);
                   6893: }
                   6894: 
                   6895: sub userlog_query {
1.858     raeburn  6896: #
                   6897: # possible filters:
                   6898: # action: log check role
                   6899: # start: timestamp
                   6900: # end: timestamp
                   6901: #
1.240     www      6902:     my ($uname,$udom,%filters)=@_;
                   6903:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6904: }
                   6905: 
1.506     raeburn  6906: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6907: 
                   6908: sub auto_run {
1.508     raeburn  6909:     my ($cnum,$cdom) = @_;
1.876     raeburn  6910:     my $response = 0;
                   6911:     my $settings;
                   6912:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6913:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6914:         $settings = $domconfig{'autoenroll'};
                   6915:         if ($settings->{'run'} eq '1') {
                   6916:             $response = 1;
                   6917:         }
                   6918:     } else {
1.934     raeburn  6919:         my $homeserver;
                   6920:         if (&is_course($cdom,$cnum)) {
                   6921:             $homeserver = &homeserver($cnum,$cdom);
                   6922:         } else {
                   6923:             $homeserver = &domain($cdom,'primary');
                   6924:         }
                   6925:         if ($homeserver ne 'no_host') {
                   6926:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6927:         }
1.876     raeburn  6928:     }
1.506     raeburn  6929:     return $response;
                   6930: }
1.776     albertel 6931: 
1.506     raeburn  6932: sub auto_get_sections {
1.508     raeburn  6933:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6934:     my $homeserver;
                   6935:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6936:         $homeserver = &homeserver($cnum,$cdom);
                   6937:     }
                   6938:     if (!defined($homeserver)) { 
                   6939:         if ($cdom =~ /^$match_domain$/) {
                   6940:             $homeserver = &domain($cdom,'primary');
                   6941:         }
                   6942:     }
                   6943:     my @secs;
                   6944:     if (defined($homeserver)) {
                   6945:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6946:         unless ($response eq 'refused') {
                   6947:             @secs = split(/:/,$response);
                   6948:         }
1.506     raeburn  6949:     }
                   6950:     return @secs;
                   6951: }
1.776     albertel 6952: 
1.506     raeburn  6953: sub auto_new_course {
1.1099    raeburn  6954:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6955:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6956:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6957:     return $response;
                   6958: }
1.776     albertel 6959: 
1.506     raeburn  6960: sub auto_validate_courseID {
1.508     raeburn  6961:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6962:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6963:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6964:     return $response;
                   6965: }
1.776     albertel 6966: 
1.1007    raeburn  6967: sub auto_validate_instcode {
1.1020    raeburn  6968:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6969:     my ($homeserver,$response);
                   6970:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6971:         $homeserver = &homeserver($cnum,$cdom);
                   6972:     }
                   6973:     if (!defined($homeserver)) {
                   6974:         if ($cdom =~ /^$match_domain$/) {
                   6975:             $homeserver = &domain($cdom,'primary');
                   6976:         }
                   6977:     }
1.1065    raeburn  6978:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6979:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6980:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6981:     return ($outcome,$description);
1.1007    raeburn  6982: }
                   6983: 
1.506     raeburn  6984: sub auto_create_password {
1.873     raeburn  6985:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6986:     my ($homeserver,$response);
1.506     raeburn  6987:     my $create_passwd = 0;
                   6988:     my $authchk = '';
1.873     raeburn  6989:     if ($udom =~ /^$match_domain$/) {
                   6990:         $homeserver = &domain($udom,'primary');
                   6991:     }
                   6992:     if ($homeserver eq '') {
                   6993:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6994:             $homeserver = &homeserver($cnum,$cdom);
                   6995:         }
                   6996:     }
                   6997:     if ($homeserver eq '') {
                   6998:         $authchk = 'nodomain';
1.506     raeburn  6999:     } else {
1.873     raeburn  7000:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7001:         if ($response eq 'refused') {
                   7002:             $authchk = 'refused';
                   7003:         } else {
1.901     albertel 7004:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7005:         }
1.506     raeburn  7006:     }
                   7007:     return ($authparam,$create_passwd,$authchk);
                   7008: }
                   7009: 
1.706     raeburn  7010: sub auto_photo_permission {
                   7011:     my ($cnum,$cdom,$students) = @_;
                   7012:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7013:     my ($outcome,$perm_reqd,$conditions) = 
                   7014: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7015:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7016: 	return (undef,undef);
                   7017:     }
1.706     raeburn  7018:     return ($outcome,$perm_reqd,$conditions);
                   7019: }
                   7020: 
                   7021: sub auto_checkphotos {
                   7022:     my ($uname,$udom,$pid) = @_;
                   7023:     my $homeserver = &homeserver($uname,$udom);
                   7024:     my ($result,$resulttype);
                   7025:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7026: 				   &escape($uname).':'.&escape($pid),
                   7027: 				   $homeserver));
1.709     albertel 7028:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7029: 	return (undef,undef);
                   7030:     }
1.706     raeburn  7031:     if ($outcome) {
                   7032:         ($result,$resulttype) = split(/:/,$outcome);
                   7033:     } 
                   7034:     return ($result,$resulttype);
                   7035: }
                   7036: 
                   7037: sub auto_photochoice {
                   7038:     my ($cnum,$cdom) = @_;
                   7039:     my $homeserver = &homeserver($cnum,$cdom);
                   7040:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7041: 						       &escape($cdom),
                   7042: 						       $homeserver)));
1.709     albertel 7043:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7044: 	return (undef,undef);
                   7045:     }
1.706     raeburn  7046:     return ($update,$comment);
                   7047: }
                   7048: 
                   7049: sub auto_photoupdate {
                   7050:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7051:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7052:     my $host=&hostname($homeserver);
1.706     raeburn  7053:     my $cmd = '';
                   7054:     my $maxtries = 1;
1.800     albertel 7055:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7056:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7057:     }
                   7058:     $cmd =~ s/%%$//;
                   7059:     $cmd = &escape($cmd);
                   7060:     my $query = 'institutionalphotos';
                   7061:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7062:     unless ($queryid=~/^\Q$host\E\_/) {
                   7063:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7064:         return 'error: '.$queryid;
                   7065:     }
                   7066:     my $reply = &get_query_reply($queryid);
                   7067:     my $tries = 1;
                   7068:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7069:         $reply = &get_query_reply($queryid);
                   7070:         $tries ++;
                   7071:     }
                   7072:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7073:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7074:     } else {
                   7075:         my @responses = split(/:/,$reply);
                   7076:         my $outcome = shift(@responses); 
                   7077:         foreach my $item (@responses) {
                   7078:             my ($key,$value) = split(/=/,$item);
                   7079:             $$photo{$key} = $value;
                   7080:         }
                   7081:         return $outcome;
                   7082:     }
                   7083:     return 'error';
                   7084: }
                   7085: 
1.521     raeburn  7086: sub auto_instcode_format {
1.793     albertel 7087:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7088: 	$cat_order) = @_;
1.521     raeburn  7089:     my $courses = '';
1.772     raeburn  7090:     my @homeservers;
1.521     raeburn  7091:     if ($caller eq 'global') {
1.841     albertel 7092: 	my %servers = &get_servers($codedom,'library');
                   7093: 	foreach my $tryserver (keys(%servers)) {
                   7094: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7095: 		push(@homeservers,$tryserver);
                   7096: 	    }
1.584     raeburn  7097:         }
1.1022    raeburn  7098:     } elsif ($caller eq 'requests') {
                   7099:         if ($codedom =~ /^$match_domain$/) {
                   7100:             my $chome = &domain($codedom,'primary');
                   7101:             unless ($chome eq 'no_host') {
                   7102:                 push(@homeservers,$chome);
                   7103:             }
                   7104:         }
1.521     raeburn  7105:     } else {
1.772     raeburn  7106:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7107:     }
1.793     albertel 7108:     foreach my $code (keys(%{$instcodes})) {
                   7109:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7110:     }
                   7111:     chop($courses);
1.772     raeburn  7112:     my $ok_response = 0;
                   7113:     my $response;
                   7114:     while (@homeservers > 0 && $ok_response == 0) {
                   7115:         my $server = shift(@homeservers); 
                   7116:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7117:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7118:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7119: 		split(/:/,$response);
1.772     raeburn  7120:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7121:             push(@{$codetitles},&str2array($codetitles_str));
                   7122:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7123:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7124:             $ok_response = 1;
                   7125:         }
                   7126:     }
                   7127:     if ($ok_response) {
1.521     raeburn  7128:         return 'ok';
1.772     raeburn  7129:     } else {
                   7130:         return $response;
1.521     raeburn  7131:     }
                   7132: }
                   7133: 
1.792     raeburn  7134: sub auto_instcode_defaults {
                   7135:     my ($domain,$returnhash,$code_order) = @_;
                   7136:     my @homeservers;
1.841     albertel 7137: 
                   7138:     my %servers = &get_servers($domain,'library');
                   7139:     foreach my $tryserver (keys(%servers)) {
                   7140: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7141: 	    push(@homeservers,$tryserver);
                   7142: 	}
1.792     raeburn  7143:     }
1.841     albertel 7144: 
1.792     raeburn  7145:     my $response;
1.841     albertel 7146:     foreach my $server (@homeservers) {
1.792     raeburn  7147:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7148:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7149: 	
                   7150: 	foreach my $pair (split(/\&/,$response)) {
                   7151: 	    my ($name,$value)=split(/\=/,$pair);
                   7152: 	    if ($name eq 'code_order') {
                   7153: 		@{$code_order} = split(/\&/,&unescape($value));
                   7154: 	    } else {
                   7155: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7156: 	    }
                   7157: 	}
                   7158: 	return 'ok';
1.792     raeburn  7159:     }
1.841     albertel 7160: 
                   7161:     return $response;
1.1003    raeburn  7162: }
                   7163: 
                   7164: sub auto_possible_instcodes {
1.1007    raeburn  7165:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7166:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7167:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7168:         return;
                   7169:     }
1.1003    raeburn  7170:     my (@homeservers,$uhome);
                   7171:     if (defined(&domain($domain,'primary'))) {
                   7172:         $uhome=&domain($domain,'primary');
                   7173:         push(@homeservers,&domain($domain,'primary'));
                   7174:     } else {
                   7175:         my %servers = &get_servers($domain,'library');
                   7176:         foreach my $tryserver (keys(%servers)) {
                   7177:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7178:                 push(@homeservers,$tryserver);
                   7179:             }
                   7180:         }
                   7181:     }
                   7182:     my $response;
                   7183:     foreach my $server (@homeservers) {
                   7184:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7185:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7186:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7187:             split(':',$response);
                   7188:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7189:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7190:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7191:             my ($name,$value)=split('=',$item);
                   7192:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7193:         }
                   7194:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7195:             my ($name,$value)=split('=',$item);
                   7196:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7197:         }
                   7198:         return 'ok';
                   7199:     }
                   7200:     return $response;
                   7201: }
1.792     raeburn  7202: 
1.1010    raeburn  7203: sub auto_courserequest_checks {
                   7204:     my ($dom) = @_;
1.1020    raeburn  7205:     my ($homeserver,%validations);
                   7206:     if ($dom =~ /^$match_domain$/) {
                   7207:         $homeserver = &domain($dom,'primary');
                   7208:     }
                   7209:     unless ($homeserver eq 'no_host') {
                   7210:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7211:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7212:             my @items = split(/&/,$response);
                   7213:             foreach my $item (@items) {
                   7214:                 my ($key,$value) = split('=',$item);
                   7215:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7216:             }
                   7217:         }
                   7218:     }
1.1010    raeburn  7219:     return %validations; 
                   7220: }
                   7221: 
1.1020    raeburn  7222: sub auto_courserequest_validation {
                   7223:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7224:     my ($homeserver,$response);
                   7225:     if ($dom =~ /^$match_domain$/) {
                   7226:         $homeserver = &domain($dom,'primary');
                   7227:     }
                   7228:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7229:           
1.1020    raeburn  7230:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7231:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7232:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7233:                                     $homeserver));
                   7234:     }
                   7235:     return $response;
                   7236: }
                   7237: 
1.777     albertel 7238: sub auto_validate_class_sec {
1.918     raeburn  7239:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7240:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7241:     my $ownerlist;
                   7242:     if (ref($owners) eq 'ARRAY') {
                   7243:         $ownerlist = join(',',@{$owners});
                   7244:     } else {
                   7245:         $ownerlist = $owners;
                   7246:     }
1.773     raeburn  7247:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7248:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7249:     return $response;
                   7250: }
                   7251: 
1.679     raeburn  7252: # ------------------------------------------------------- Course Group routines
                   7253: 
                   7254: sub get_coursegroups {
1.809     raeburn  7255:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7256:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7257: }
                   7258: 
1.679     raeburn  7259: sub modify_coursegroup {
                   7260:     my ($cdom,$cnum,$groupsettings) = @_;
                   7261:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7262: }
                   7263: 
1.809     raeburn  7264: sub toggle_coursegroup_status {
                   7265:     my ($cdom,$cnum,$group,$action) = @_;
                   7266:     my ($from_namespace,$to_namespace);
                   7267:     if ($action eq 'delete') {
                   7268:         $from_namespace = 'coursegroups';
                   7269:         $to_namespace = 'deleted_groups';
                   7270:     } else {
                   7271:         $from_namespace = 'deleted_groups';
                   7272:         $to_namespace = 'coursegroups';
                   7273:     }
                   7274:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7275:     if (my $tmp = &error(%curr_group)) {
                   7276:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7277:         return ('read error',$tmp);
                   7278:     } else {
                   7279:         my %savedsettings = %curr_group; 
1.809     raeburn  7280:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7281:         my $deloutcome;
                   7282:         if ($result eq 'ok') {
1.809     raeburn  7283:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7284:         } else {
                   7285:             return ('write error',$result);
                   7286:         }
                   7287:         if ($deloutcome eq 'ok') {
                   7288:             return 'ok';
                   7289:         } else {
                   7290:             return ('delete error',$deloutcome);
                   7291:         }
                   7292:     }
                   7293: }
                   7294: 
1.679     raeburn  7295: sub modify_group_roles {
1.957     raeburn  7296:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7297:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7298:     my $role = 'gr/'.&escape($userprivs);
                   7299:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7300:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7301:     if ($result eq 'ok') {
                   7302:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7303:     }
1.679     raeburn  7304:     return $result;
                   7305: }
                   7306: 
                   7307: sub modify_coursegroup_membership {
                   7308:     my ($cdom,$cnum,$membership) = @_;
                   7309:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7310:     return $result;
                   7311: }
                   7312: 
1.682     raeburn  7313: sub get_active_groups {
                   7314:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7315:     my $now = time;
                   7316:     my %groups = ();
                   7317:     foreach my $key (keys(%env)) {
1.811     albertel 7318:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7319:             my ($start,$end) = split(/\./,$env{$key});
                   7320:             if (($end!=0) && ($end<$now)) { next; }
                   7321:             if (($start!=0) && ($start>$now)) { next; }
                   7322:             if ($1 eq $cdom && $2 eq $cnum) {
                   7323:                 $groups{$3} = $env{$key} ;
                   7324:             }
                   7325:         }
                   7326:     }
                   7327:     return %groups;
                   7328: }
                   7329: 
1.683     raeburn  7330: sub get_group_membership {
                   7331:     my ($cdom,$cnum,$group) = @_;
                   7332:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7333: }
                   7334: 
                   7335: sub get_users_groups {
                   7336:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7337:     my @usersgroups;
1.683     raeburn  7338:     my $cachetime=1800;
                   7339: 
                   7340:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7341:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7342:     if (defined($cached)) {
1.734     albertel 7343:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7344:     } else {  
                   7345:         $grouplist = '';
1.816     raeburn  7346:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7347:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7348:         my $access_end = $env{'course.'.$courseid.
                   7349:                               '.default_enrollment_end_date'};
                   7350:         my $now = time;
                   7351:         foreach my $key (keys(%roleshash)) {
                   7352:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7353:                 my $group = $1;
                   7354:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7355:                     my $start = $2;
                   7356:                     my $end = $1;
                   7357:                     if ($start == -1) { next; } # deleted from group
                   7358:                     if (($start!=0) && ($start>$now)) { next; }
                   7359:                     if (($end!=0) && ($end<$now)) {
                   7360:                         if ($access_end && $access_end < $now) {
                   7361:                             if ($access_end - $end < 86400) {
                   7362:                                 push(@usersgroups,$group);
1.733     raeburn  7363:                             }
                   7364:                         }
1.817     raeburn  7365:                         next;
1.733     raeburn  7366:                     }
1.817     raeburn  7367:                     push(@usersgroups,$group);
1.683     raeburn  7368:                 }
                   7369:             }
                   7370:         }
1.817     raeburn  7371:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7372:         $grouplist = join(':',@usersgroups);
                   7373:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7374:     }
1.733     raeburn  7375:     return @usersgroups;
1.683     raeburn  7376: }
                   7377: 
                   7378: sub devalidate_getgroups_cache {
                   7379:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7380:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7381: 
1.683     raeburn  7382:     my $hashid="$udom:$uname:$courseid";
                   7383:     &devalidate_cache_new('getgroups',$hashid);
                   7384: }
                   7385: 
1.12      www      7386: # ------------------------------------------------------------------ Plain Text
                   7387: 
                   7388: sub plaintext {
1.988     raeburn  7389:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7390:     if ($short =~ m{^cr/}) {
1.758     albertel 7391: 	return (split('/',$short))[-1];
                   7392:     }
1.742     raeburn  7393:     if (!defined($cid)) {
                   7394:         $cid = $env{'request.course.id'};
                   7395:     }
                   7396:     my %rolenames = (
1.1008    raeburn  7397:                       Course    => 'std',
                   7398:                       Community => 'alt1',
1.742     raeburn  7399:                     );
1.1037    raeburn  7400:     if ($cid ne '') {
                   7401:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7402:             unless ($forcedefault) {
                   7403:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7404:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7405:                 return &Apache::lonlocal::mt($roletext);
                   7406:             }
                   7407:         }
                   7408:     }
                   7409:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7410:         (defined($rolenames{$type})) && 
                   7411:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7412:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7413:     } elsif ($cid ne '') {
                   7414:         my $crstype = $env{'course.'.$cid.'.type'};
                   7415:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7416:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7417:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7418:         }
1.742     raeburn  7419:     }
1.1037    raeburn  7420:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7421: }
                   7422: 
                   7423: # ----------------------------------------------------------------- Assign Role
                   7424: 
                   7425: sub assignrole {
1.957     raeburn  7426:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7427:         $context)=@_;
1.21      www      7428:     my $mrole;
                   7429:     if ($role =~ /^cr\//) {
1.393     www      7430:         my $cwosec=$url;
1.811     albertel 7431:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7432: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7433:            my $refused = 1;
                   7434:            if ($context eq 'requestcourses') {
                   7435:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7436:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7437:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7438:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7439:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7440:                            if ($crsenv{'internal.courseowner'} eq
                   7441:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7442:                                $refused = '';
                   7443:                            }
                   7444:                        }
                   7445:                    }
                   7446:                }
                   7447:            }
                   7448:            if ($refused) {
                   7449:                &logthis('Refused custom assignrole: '.
                   7450:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7451:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7452:                return 'refused';
                   7453:            }
1.104     www      7454:         }
1.21      www      7455:         $mrole='cr';
1.678     raeburn  7456:     } elsif ($role =~ /^gr\//) {
                   7457:         my $cwogrp=$url;
1.811     albertel 7458:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7459:         unless (&allowed('mdg',$cwogrp)) {
                   7460:             &logthis('Refused group assignrole: '.
                   7461:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7462:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7463:             return 'refused';
                   7464:         }
                   7465:         $mrole='gr';
1.21      www      7466:     } else {
1.82      www      7467:         my $cwosec=$url;
1.811     albertel 7468:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7469:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7470:             my $refused;
                   7471:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7472:                 if (!(&allowed('c'.$role,$url))) {
                   7473:                     $refused = 1;
                   7474:                 }
                   7475:             } else {
                   7476:                 $refused = 1;
                   7477:             }
1.947     raeburn  7478:             if ($refused) {
1.1045    raeburn  7479:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7480:                 if (!$selfenroll && $context eq 'course') {
                   7481:                     my %crsenv;
                   7482:                     if ($role eq 'cc' || $role eq 'co') {
                   7483:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7484:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7485:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7486:                                 if ($crsenv{'internal.courseowner'} eq 
                   7487:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7488:                                     $refused = '';
                   7489:                                 }
                   7490:                             }
                   7491:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7492:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7493:                                 if ($crsenv{'internal.courseowner'} eq 
                   7494:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7495:                                     $refused = '';
                   7496:                                 }
                   7497:                             }
                   7498:                         }
                   7499:                     }
                   7500:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7501:                     $refused = '';
1.1017    raeburn  7502:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7503:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7504:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7505:                         my $wrongcc;
                   7506:                         if ($cnum =~ /^$match_community$/) {
                   7507:                             $wrongcc = 1 if ($role eq 'cc');
                   7508:                         } else {
                   7509:                             $wrongcc = 1 if ($role eq 'co');
                   7510:                         }
                   7511:                         unless ($wrongcc) {
                   7512:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7513:                             if ($crsenv{'internal.courseowner'} eq 
                   7514:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7515:                                 $refused = '';
                   7516:                             }
1.1017    raeburn  7517:                         }
                   7518:                     }
1.1172.2.9! raeburn  7519:                 } elsif ($context eq 'requestauthor') {
        !          7520:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
        !          7521:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
        !          7522:                         if ($env{'environment.requestauthor'} eq 'automatic') {
        !          7523:                             $refused = '';
        !          7524:                         } else {
        !          7525:                             my %domdefaults = &get_domain_defaults($udom);
        !          7526:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
        !          7527:                                 my $checkbystatus;
        !          7528:                                 if ($env{'user.adv'}) {
        !          7529:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
        !          7530:                                     if ($disposition eq 'automatic') {
        !          7531:                                         $refused = '';
        !          7532:                                     } elsif ($disposition eq '') {
        !          7533:                                         $checkbystatus = 1;
        !          7534:                                     }
        !          7535:                                 } else {
        !          7536:                                     $checkbystatus = 1;
        !          7537:                                 }
        !          7538:                                 if ($checkbystatus) {
        !          7539:                                     if ($env{'environment.inststatus'}) {
        !          7540:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
        !          7541:                                         foreach my $type (@inststatuses) {
        !          7542:                                             if (($type ne '') &&
        !          7543:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
        !          7544:                                                 $refused = '';
        !          7545:                                             }
        !          7546:                                         }
        !          7547:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
        !          7548:                                         $refused = '';
        !          7549:                                     }
        !          7550:                                 }
        !          7551:                             }
        !          7552:                         }
        !          7553:                     }
1.1017    raeburn  7554:                 }
                   7555:                 if ($refused) {
1.947     raeburn  7556:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7557:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7558: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7559:                     return 'refused';
                   7560:                 }
1.932     raeburn  7561:             }
1.1131    raeburn  7562:         } elsif ($role eq 'au') {
                   7563:             if ($url ne '/'.$udom.'/') {
                   7564:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7565:                          ' to assign author role for '.$uname.':'.$udom.
                   7566:                          ' in domain: '.$url.' refused (wrong domain).');
                   7567:                 return 'refused';
                   7568:             }
1.104     www      7569:         }
1.21      www      7570:         $mrole=$role;
                   7571:     }
1.620     albertel 7572:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7573:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7574:     if ($end) { $command.='_'.$end; }
1.21      www      7575:     if ($start) {
                   7576: 	if ($end) { 
1.81      www      7577:            $command.='_'.$start; 
1.21      www      7578:         } else {
1.81      www      7579:            $command.='_0_'.$start;
1.21      www      7580:         }
                   7581:     }
1.739     raeburn  7582:     my $origstart = $start;
                   7583:     my $origend = $end;
1.957     raeburn  7584:     my $delflag;
1.357     www      7585: # actually delete
                   7586:     if ($deleteflag) {
1.373     www      7587: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      7588: # modify command to delete the role
1.620     albertel 7589:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      7590:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 7591: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      7592: # set start and finish to negative values for userrolelog
                   7593:            $start=-1;
                   7594:            $end=-1;
1.957     raeburn  7595:            $delflag = 1;
1.357     www      7596:         }
                   7597:     }
                   7598: # send command
1.349     www      7599:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      7600: # log new user role if status is ok
1.349     www      7601:     if ($answer eq 'ok') {
1.663     raeburn  7602: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  7603: # for course roles, perform group memberships changes triggered by role change.
                   7604:         unless ($role =~ /^gr/) {
                   7605:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  7606:                                              $origstart,$selfenroll,$context);
1.739     raeburn  7607:         }
1.1172.2.9! raeburn  7608:         if (($role eq 'cc') || ($role eq 'in') ||
        !          7609:             ($role eq 'ep') || ($role eq 'ad') ||
        !          7610:             ($role eq 'ta') || ($role eq 'st') ||
        !          7611:             ($role=~/^cr/) || ($role eq 'gr') ||
        !          7612:             ($role eq 'co')) {
        !          7613:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
        !          7614:                            $selfenroll,$context);
        !          7615:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
        !          7616:                  ($role eq 'au') || ($role eq 'dc')) {
        !          7617:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
        !          7618:                            $context);
        !          7619:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
        !          7620:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
        !          7621:                              $context);
        !          7622:         }
1.1053    raeburn  7623:         if ($role eq 'cc') {
                   7624:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   7625:         }
1.349     www      7626:     }
                   7627:     return $answer;
1.169     harris41 7628: }
                   7629: 
1.1053    raeburn  7630: sub autoupdate_coowners {
                   7631:     my ($url,$end,$start,$uname,$udom) = @_;
                   7632:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   7633:     if (($cdom ne '') && ($cnum ne '')) {
                   7634:         my $now = time;
                   7635:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   7636:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   7637:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   7638:             my $instcode = $coursehash{'internal.coursecode'};
                   7639:             if ($instcode ne '') {
1.1056    raeburn  7640:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   7641:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  7642:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  7643:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   7644:                         if ($result eq 'valid') {
                   7645:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  7646:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7647:                                     push(@newcoowners,$coowner);
                   7648:                                 }
                   7649:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   7650:                                     push(@newcoowners,$uname.':'.$udom);
                   7651:                                 }
                   7652:                                 @newcoowners = sort(@newcoowners);
                   7653:                             } else {
                   7654:                                 push(@newcoowners,$uname.':'.$udom);
                   7655:                             }
                   7656:                         } else {
                   7657:                             if ($coursehash{'internal.co-owners'}) {
                   7658:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7659:                                     unless ($coowner eq $uname.':'.$udom) {
                   7660:                                         push(@newcoowners,$coowner);
                   7661:                                     }
                   7662:                                 }
                   7663:                                 unless (@newcoowners > 0) {
                   7664:                                     $delcoowners = 1;
                   7665:                                     $coowners = '';
                   7666:                                 }
                   7667:                             }
                   7668:                         }
                   7669:                         if (@newcoowners || $delcoowners) {
                   7670:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   7671:                                             $delcoowners,@newcoowners);
                   7672:                         }
                   7673:                     }
                   7674:                 }
                   7675:             }
                   7676:         }
                   7677:     }
                   7678: }
                   7679: 
                   7680: sub store_coowners {
                   7681:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   7682:     my $cid = $cdom.'_'.$cnum;
                   7683:     my ($coowners,$delresult,$putresult);
                   7684:     if (@newcoowners) {
                   7685:         $coowners = join(',',@newcoowners);
                   7686:         my %coownershash = (
                   7687:                             'internal.co-owners' => $coowners,
                   7688:                            );
                   7689:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   7690:         if ($putresult eq 'ok') {
                   7691:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   7692:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   7693:             }
                   7694:         }
                   7695:     }
                   7696:     if ($delcoowners) {
                   7697:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   7698:         if ($delresult eq 'ok') {
                   7699:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   7700:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   7701:             }
                   7702:         }
                   7703:     }
                   7704:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   7705:         my %crsinfo =
                   7706:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   7707:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   7708:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   7709:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   7710:         }
                   7711:     }
                   7712: }
                   7713: 
1.169     harris41 7714: # -------------------------------------------------- Modify user authentication
1.197     www      7715: # Overrides without validation
                   7716: 
1.169     harris41 7717: sub modifyuserauth {
                   7718:     my ($udom,$uname,$umode,$upass)=@_;
                   7719:     my $uhome=&homeserver($uname,$udom);
1.197     www      7720:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   7721:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 7722:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7723:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 7724:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   7725: 		     &escape($upass),$uhome);
1.620     albertel 7726:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      7727:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   7728:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   7729:     &log($udom,,$uname,$uhome,
1.620     albertel 7730:         'Authentication changed by '.$env{'user.domain'}.', '.
                   7731:                                      $env{'user.name'}.', '.$umode.
1.197     www      7732:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 7733:     unless ($reply eq 'ok') {
1.197     www      7734:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 7735: 	return 'error: '.$reply;
                   7736:     }   
1.170     harris41 7737:     return 'ok';
1.80      www      7738: }
                   7739: 
1.81      www      7740: # --------------------------------------------------------------- Modify a user
1.80      www      7741: 
1.81      www      7742: sub modifyuser {
1.206     matthew  7743:     my ($udom,    $uname, $uid,
                   7744:         $umode,   $upass, $first,
                   7745:         $middle,  $last,  $gene,
1.1058    raeburn  7746:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 7747:     $udom= &LONCAPA::clean_domain($udom);
                   7748:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  7749:     my $showcandelete = 'none';
                   7750:     if (ref($candelete) eq 'ARRAY') {
                   7751:         if (@{$candelete} > 0) {
                   7752:             $showcandelete = join(', ',@{$candelete});
                   7753:         }
                   7754:     }
1.81      www      7755:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      7756:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  7757: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  7758:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   7759:                                      ' desiredhome not specified'). 
1.620     albertel 7760:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7761:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 7762:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  7763:     my $newuser;
                   7764:     if ($uhome eq 'no_host') {
                   7765:         $newuser = 1;
                   7766:     }
1.80      www      7767: # ----------------------------------------------------------------- Create User
1.406     albertel 7768:     if (($uhome eq 'no_host') && 
                   7769: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      7770:         my $unhome='';
1.844     albertel 7771:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7772:             $unhome = $desiredhome;
1.620     albertel 7773: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7774: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7775:         } else { # load balancing routine for determining $unhome
1.81      www      7776:             my $loadm=10000000;
1.841     albertel 7777: 	    my %servers = &get_servers($udom,'library');
                   7778: 	    foreach my $tryserver (keys(%servers)) {
                   7779: 		my $answer=reply('load',$tryserver);
                   7780: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7781: 		    $loadm=$answer;
                   7782: 		    $unhome=$tryserver;
                   7783: 		}
1.80      www      7784: 	    }
                   7785:         }
                   7786:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7787: 	    return 'error: unable to find a home server for '.$uname.
                   7788:                    ' in domain '.$udom;
1.80      www      7789:         }
                   7790:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7791:                          &escape($upass),$unhome);
                   7792: 	unless ($reply eq 'ok') {
                   7793:             return 'error: '.$reply;
                   7794:         }   
1.230     stredwic 7795:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7796:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7797: 	    return 'error: unable verify users home machine.';
1.80      www      7798:         }
1.209     matthew  7799:     }   # End of creation of new user
1.80      www      7800: # ---------------------------------------------------------------------- Add ID
                   7801:     if ($uid) {
                   7802:        $uid=~tr/A-Z/a-z/;
                   7803:        my %uidhash=&idrget($udom,$uname);
1.196     www      7804:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7805:          && (!$forceid)) {
1.80      www      7806: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7807: 	      return 'error: user id "'.$uid.'" does not match '.
                   7808:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7809:           }
                   7810:        } else {
                   7811: 	  &idput($udom,($uname => $uid));
                   7812:        }
                   7813:     }
                   7814: # -------------------------------------------------------------- Add names, etc
1.313     matthew  7815:     my @tmp=&get('environment',
1.899     raeburn  7816: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  7817:                     'permanentemail','inststatus'],
1.134     albertel 7818: 		   $udom,$uname);
1.1075    raeburn  7819:     my (%names,%oldnames);
1.313     matthew  7820:     if ($tmp[0] =~ m/^error:.*/) { 
                   7821:         %names=(); 
                   7822:     } else {
                   7823:         %names = @tmp;
1.1075    raeburn  7824:         %oldnames = %names;
1.313     matthew  7825:     }
1.388     www      7826: #
1.1058    raeburn  7827: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7828: # of users did not contain them), do not overwrite existing values
                   7829: # unless field is in $candelete array ref.  
                   7830: #
                   7831: 
                   7832:     my @fields = ('firstname','middlename','lastname','generation',
                   7833:                   'permanentemail','id');
                   7834:     my %newvalues;
                   7835:     if (ref($candelete) eq 'ARRAY') {
                   7836:         foreach my $field (@fields) {
                   7837:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7838:                 if ($field eq 'firstname') {
                   7839:                     $names{$field} = $first;
                   7840:                 } elsif ($field eq 'middlename') {
                   7841:                     $names{$field} = $middle;
                   7842:                 } elsif ($field eq 'lastname') {
                   7843:                     $names{$field} = $last;
                   7844:                 } elsif ($field eq 'generation') { 
                   7845:                     $names{$field} = $gene;
                   7846:                 } elsif ($field eq 'permanentemail') {
                   7847:                     $names{$field} = $email;
                   7848:                 } elsif ($field eq 'id') {
                   7849:                     $names{$field}  = $uid;
                   7850:                 }
                   7851:             }
                   7852:         }
                   7853:     }
1.388     www      7854:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7855:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7856:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7857:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7858:     if ($email) {
                   7859:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7860:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7861:     }
1.899     raeburn  7862:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7863:     if (defined($inststatus)) {
                   7864:         $names{'inststatus'} = '';
                   7865:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7866:         if (ref($usertypes) eq 'HASH') {
                   7867:             my @okstatuses; 
                   7868:             foreach my $item (split(/:/,$inststatus)) {
                   7869:                 if (defined($usertypes->{$item})) {
                   7870:                     push(@okstatuses,$item);  
                   7871:                 }
                   7872:             }
                   7873:             if (@okstatuses) {
                   7874:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7875:             }
                   7876:         }
                   7877:     }
1.1075    raeburn  7878:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7879:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7880:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7881:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7882:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7883:     } else {
                   7884:         $logmsg .= ' during self creation';
                   7885:     }
1.1075    raeburn  7886:     my $changed;
                   7887:     if ($newuser) {
                   7888:         $changed = 1;
                   7889:     } else {
                   7890:         foreach my $field (@fields) {
                   7891:             if ($names{$field} ne $oldnames{$field}) {
                   7892:                 $changed = 1;
                   7893:                 last;
                   7894:             }
                   7895:         }
                   7896:     }
                   7897:     unless ($changed) {
                   7898:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7899:         &logthis($logmsg);
                   7900:         return 'ok';
                   7901:     }
                   7902:     my $reply = &put('environment', \%names, $udom,$uname);
                   7903:     if ($reply ne 'ok') { 
                   7904:         return 'error: '.$reply;
                   7905:     }
1.1087    raeburn  7906:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7907:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7908:     }
1.1075    raeburn  7909:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7910:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7911:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7912:     &logthis($logmsg);
1.134     albertel 7913:     return 'ok';
1.80      www      7914: }
                   7915: 
1.81      www      7916: # -------------------------------------------------------------- Modify student
1.80      www      7917: 
1.81      www      7918: sub modifystudent {
                   7919:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7920:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7921:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7922:     if (!$cid) {
1.620     albertel 7923: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7924: 	    return 'not_in_class';
                   7925: 	}
1.80      www      7926:     }
                   7927: # --------------------------------------------------------------- Make the user
1.81      www      7928:     my $reply=&modifyuser
1.209     matthew  7929: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7930:          $desiredhome,$email,$inststatus);
1.80      www      7931:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7932:     # This will cause &modify_student_enrollment to get the uid from the
                   7933:     # students environment
                   7934:     $uid = undef if (!$forceid);
1.455     albertel 7935:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7936: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7937:     return $reply;
                   7938: }
                   7939: 
                   7940: sub modify_student_enrollment {
1.957     raeburn  7941:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7942:     my ($cdom,$cnum,$chome);
                   7943:     if (!$cid) {
1.620     albertel 7944: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7945: 	    return 'not_in_class';
                   7946: 	}
1.620     albertel 7947: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7948: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7949:     } else {
                   7950: 	($cdom,$cnum)=split(/_/,$cid);
                   7951:     }
1.620     albertel 7952:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7953:     if (!$chome) {
1.457     raeburn  7954: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7955:     }
1.455     albertel 7956:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7957:     # Make sure the user exists
1.81      www      7958:     my $uhome=&homeserver($uname,$udom);
                   7959:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7960: 	return 'error: no such user';
                   7961:     }
1.297     matthew  7962:     # Get student data if we were not given enough information
                   7963:     if (!defined($first)  || $first  eq '' || 
                   7964:         !defined($last)   || $last   eq '' || 
                   7965:         !defined($uid)    || $uid    eq '' || 
                   7966:         !defined($middle) || $middle eq '' || 
                   7967:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7968:         # They did not supply us with enough data to enroll the student, so
                   7969:         # we need to pick up more information.
1.297     matthew  7970:         my %tmp = &get('environment',
1.294     matthew  7971:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7972:                        ,$udom,$uname);
                   7973: 
1.800     albertel 7974:         #foreach my $key (keys(%tmp)) {
                   7975:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7976:         #}
1.294     matthew  7977:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7978:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7979:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7980:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7981:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7982:     }
1.556     albertel 7983:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  7984:     my $user = "$uname:$udom";
                   7985:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 7986:     my $reply=cput('classlist',
1.1148    raeburn  7987: 		   {$user => 
1.515     raeburn  7988: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7989: 		   $cdom,$cnum);
1.1148    raeburn  7990:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7991:         &devalidate_getsection_cache($udom,$uname,$cid);
                   7992:     } else { 
1.81      www      7993: 	return 'error: '.$reply;
                   7994:     }
1.297     matthew  7995:     # Add student role to user
1.83      www      7996:     my $uurl='/'.$cid;
1.81      www      7997:     $uurl=~s/\_/\//g;
                   7998:     if ($usec) {
                   7999: 	$uurl.='/'.$usec;
                   8000:     }
1.1148    raeburn  8001:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8002:                              $selfenroll,$context);
                   8003:     if ($result ne 'ok') {
                   8004:         if ($old_entry{$user} ne '') {
                   8005:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8006:         } else {
                   8007:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8008:         }
                   8009:     }
                   8010:     return $result; 
1.21      www      8011: }
                   8012: 
1.556     albertel 8013: sub format_name {
                   8014:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   8015:     my $name;
                   8016:     if ($first ne 'lastname') {
                   8017: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   8018:     } else {
                   8019: 	if ($lastname=~/\S/) {
                   8020: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   8021: 	    $name=~s/\s+,/,/;
                   8022: 	} else {
                   8023: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   8024: 	}
                   8025:     }
                   8026:     $name=~s/^\s+//;
                   8027:     $name=~s/\s+$//;
                   8028:     $name=~s/\s+/ /g;
                   8029:     return $name;
                   8030: }
                   8031: 
1.84      www      8032: # ------------------------------------------------- Write to course preferences
                   8033: 
                   8034: sub writecoursepref {
                   8035:     my ($courseid,%prefs)=@_;
                   8036:     $courseid=~s/^\///;
                   8037:     $courseid=~s/\_/\//g;
                   8038:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   8039:     my $chome=homeserver($cnum,$cdomain);
                   8040:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   8041: 	return 'error: no such course';
                   8042:     }
                   8043:     my $cstring='';
1.800     albertel 8044:     foreach my $pref (keys(%prefs)) {
                   8045: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 8046:     }
1.84      www      8047:     $cstring=~s/\&$//;
                   8048:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   8049: }
                   8050: 
                   8051: # ---------------------------------------------------------- Make/modify course
                   8052: 
                   8053: sub createcourse {
1.741     raeburn  8054:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  8055:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      8056:     $url=&declutter($url);
                   8057:     my $cid='';
1.1028    raeburn  8058:     if ($context eq 'requestcourses') {
                   8059:         my $can_create = 0;
                   8060:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   8061:         if ($udom eq $ownerdom) {
                   8062:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   8063:                                   $context)) {
                   8064:                 $can_create = 1;
                   8065:             }
                   8066:         } else {
                   8067:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8068:                                            $category);
                   8069:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8070:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8071:                 if (@curr > 0) {
                   8072:                     my @options = qw(approval validate autolimit);
                   8073:                     my $optregex = join('|',@options);
                   8074:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8075:                         $can_create = 1;
                   8076:                     }
                   8077:                 }
                   8078:             }
                   8079:         }
                   8080:         if ($can_create) {
                   8081:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8082:                 unless (&allowed('ccc',$udom)) {
                   8083:                     return 'refused'; 
                   8084:                 }
1.1017    raeburn  8085:             }
                   8086:         } else {
                   8087:             return 'refused';
                   8088:         }
1.1028    raeburn  8089:     } elsif (!&allowed('ccc',$udom)) {
                   8090:         return 'refused';
1.84      www      8091:     }
1.1011    raeburn  8092: # --------------------------------------------------------------- Get Unique ID
                   8093:     my $uname;
                   8094:     if ($cnum =~ /^$match_courseid$/) {
                   8095:         my $chome=&homeserver($cnum,$udom,'true');
                   8096:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8097:             $uname = $cnum;
                   8098:         } else {
1.1038    raeburn  8099:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8100:         }
                   8101:     } else {
1.1038    raeburn  8102:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8103:     }
                   8104:     return $uname if ($uname =~ /^error/);
                   8105: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8106:     if (!defined($course_server)) {
                   8107:         if (defined(&domain($udom,'primary'))) {
                   8108:             $course_server = &domain($udom,'primary');
                   8109:         } else {
                   8110:             $course_server = $env{'user.home'}; 
                   8111:         }
                   8112:     }
                   8113:     my %host_servers =
                   8114:         &Apache::lonnet::get_servers($udom,'library');
                   8115:     unless ($host_servers{$course_server}) {
                   8116:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8117:     }
1.84      www      8118: # ------------------------------------------------------------- Make the course
                   8119:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8120:                       $course_server);
1.84      www      8121:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8122:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8123:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8124: 	return 'error: no such course';
                   8125:     }
1.271     www      8126: # ----------------------------------------------------------------- Course made
1.516     raeburn  8127: # log existence
1.1029    raeburn  8128:     my $now = time;
1.918     raeburn  8129:     my $newcourse = {
                   8130:                     $udom.'_'.$uname => {
1.921     raeburn  8131:                                      description => $description,
                   8132:                                      inst_code   => $inst_code,
                   8133:                                      owner       => $course_owner,
                   8134:                                      type        => $crstype,
1.1029    raeburn  8135:                                      creator     => $env{'user.name'}.':'.
                   8136:                                                     $env{'user.domain'},
                   8137:                                      created     => $now,
                   8138:                                      context     => $context,
1.918     raeburn  8139:                                                 },
                   8140:                     };
1.921     raeburn  8141:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8142: # set toplevel url
1.271     www      8143:     my $topurl=$url;
                   8144:     unless ($nonstandard) {
                   8145: # ------------------------------------------ For standard courses, make top url
                   8146:         my $mapurl=&clutter($url);
1.278     www      8147:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8148:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8149: <map>
                   8150: <resource id="1" type="start"></resource>
                   8151: <resource id="2" src="$mapurl"></resource>
                   8152: <resource id="3" type="finish"></resource>
                   8153: <link index="1" from="1" to="2"></link>
                   8154: <link index="2" from="2" to="3"></link>
                   8155: </map>
                   8156: ENDINITMAP
                   8157:         $topurl=&declutter(
1.638     albertel 8158:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8159:                           );
                   8160:     }
                   8161: # ----------------------------------------------------------- Write preferences
1.84      www      8162:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8163:                      ('description'              => $description,
                   8164:                       'url'                      => $topurl,
                   8165:                       'internal.creator'         => $env{'user.name'}.':'.
                   8166:                                                     $env{'user.domain'},
                   8167:                       'internal.created'         => $now,
                   8168:                       'internal.creationcontext' => $context)
                   8169:                     );
1.84      www      8170:     return '/'.$udom.'/'.$uname;
                   8171: }
                   8172: 
1.1011    raeburn  8173: # ------------------------------------------------------------------- Create ID
                   8174: sub generate_coursenum {
1.1038    raeburn  8175:     my ($udom,$crstype) = @_;
1.1011    raeburn  8176:     my $domdesc = &domain($udom);
                   8177:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8178:     my $first;
                   8179:     if ($crstype eq 'Community') {
                   8180:         $first = '0';
                   8181:     } else {
                   8182:         $first = int(1+rand(9)); 
                   8183:     } 
                   8184:     my $uname=$first.
1.1011    raeburn  8185:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8186:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8187:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8188: # ----------------------------------------------- Make sure that does not exist
                   8189:     my $uhome=&homeserver($uname,$udom,'true');
                   8190:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8191:         if ($crstype eq 'Community') {
                   8192:             $first = '0';
                   8193:         } else {
                   8194:             $first = int(1+rand(9));
                   8195:         }
                   8196:         $uname=$first.
1.1011    raeburn  8197:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8198:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8199:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8200:         $uhome=&homeserver($uname,$udom,'true');
                   8201:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8202:             return 'error: unable to generate unique course-ID';
                   8203:         }
                   8204:     }
                   8205:     return $uname;
                   8206: }
                   8207: 
1.813     albertel 8208: sub is_course {
1.1167    droeschl 8209:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8210:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8211: 
                   8212:     return unless $cdom and $cnum;
                   8213: 
                   8214:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8215:         '.');
                   8216: 
                   8217:     return unless exists($courses{$cdom.'_'.$cnum});
                   8218:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8219: }
                   8220: 
1.1015    raeburn  8221: sub store_userdata {
                   8222:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8223:     my $result;
1.1016    raeburn  8224:     if ($datakey ne '') {
1.1013    raeburn  8225:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8226:             if ($udom eq '' || $uname eq '') {
                   8227:                 $udom = $env{'user.domain'};
                   8228:                 $uname = $env{'user.name'};
                   8229:             }
                   8230:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8231:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8232:                 $result = 'error: no_host';
                   8233:             } else {
                   8234:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8235:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8236: 
                   8237:                 my $namevalue='';
                   8238:                 foreach my $key (keys(%{$storehash})) {
                   8239:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8240:                 }
                   8241:                 $namevalue=~s/\&$//;
1.1105    raeburn  8242:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8243:                                   $namevalue,$uhome);
1.1013    raeburn  8244:             }
                   8245:         } else {
                   8246:             $result = 'error: data to store was not a hash reference'; 
                   8247:         }
                   8248:     } else {
                   8249:         $result= 'error: invalid requestkey'; 
                   8250:     }
                   8251:     return $result;
                   8252: }
                   8253: 
1.21      www      8254: # ---------------------------------------------------------- Assign Custom Role
                   8255: 
                   8256: sub assigncustomrole {
1.957     raeburn  8257:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8258:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8259:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8260: }
                   8261: 
                   8262: # ----------------------------------------------------------------- Revoke Role
                   8263: 
                   8264: sub revokerole {
1.957     raeburn  8265:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8266:     my $now=time;
1.965     raeburn  8267:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8268: }
                   8269: 
                   8270: # ---------------------------------------------------------- Revoke Custom Role
                   8271: 
                   8272: sub revokecustomrole {
1.957     raeburn  8273:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8274:     my $now=time;
1.357     www      8275:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8276:            $deleteflag,$selfenroll,$context);
1.17      www      8277: }
                   8278: 
1.533     banghart 8279: # ------------------------------------------------------------ Disk usage
1.535     albertel 8280: sub diskusage {
1.955     raeburn  8281:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8282:     $directorypath =~ s/\/$//;
                   8283:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8284:                        .&escape($getpropath).':'.&escape($uname).':'
                   8285:                        .&escape($udom),homeserver($uname,$udom));
                   8286:     if ($listing eq 'unknown_cmd') {
                   8287:         if ($getpropath) {
                   8288:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8289:         }
                   8290:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8291:     }
1.514     albertel 8292:     return $listing;
1.512     banghart 8293: }
                   8294: 
1.566     banghart 8295: sub is_locked {
1.1096    raeburn  8296:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8297:     my @check;
                   8298:     my $is_locked;
1.1093    raeburn  8299:     push (@check,$file_name);
1.613     albertel 8300:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8301: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8302:     my ($tmp)=keys(%locked);
                   8303:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8304:     
1.566     banghart 8305:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8306:         $is_locked = 'false';
                   8307:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8308:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8309:                $is_locked = 'true';
1.1096    raeburn  8310:                if (ref($which) eq 'ARRAY') {
                   8311:                    push(@{$which},$entry);
                   8312:                } else {
                   8313:                    last;
                   8314:                }
1.745     raeburn  8315:            }
                   8316:        }
1.566     banghart 8317:     } else {
                   8318:         $is_locked = 'false';
                   8319:     }
1.1093    raeburn  8320:     return $is_locked;
1.566     banghart 8321: }
                   8322: 
1.759     albertel 8323: sub declutter_portfile {
                   8324:     my ($file) = @_;
1.833     albertel 8325:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8326:     return $file;
                   8327: }
                   8328: 
1.559     banghart 8329: # ------------------------------------------------------------- Mark as Read Only
                   8330: 
                   8331: sub mark_as_readonly {
                   8332:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8333:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8334:     my ($tmp)=keys(%current_permissions);
                   8335:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8336:     foreach my $file (@{$files}) {
1.759     albertel 8337: 	$file = &declutter_portfile($file);
1.561     banghart 8338:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8339:     }
1.613     albertel 8340:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8341:     return;
                   8342: }
                   8343: 
1.572     banghart 8344: # ------------------------------------------------------------Save Selected Files
                   8345: 
                   8346: sub save_selected_files {
                   8347:     my ($user, $path, @files) = @_;
                   8348:     my $filename = $user."savedfiles";
1.573     banghart 8349:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8350:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8351:     foreach my $file (@files) {
1.620     albertel 8352:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8353:     }
                   8354:     foreach my $file (@other_files) {
1.574     banghart 8355:         print (OUT $file."\n");
1.572     banghart 8356:     }
1.574     banghart 8357:     close (OUT);
1.572     banghart 8358:     return 'ok';
                   8359: }
                   8360: 
1.574     banghart 8361: sub clear_selected_files {
                   8362:     my ($user) = @_;
                   8363:     my $filename = $user."savedfiles";
1.1117    foxr     8364:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8365:     print (OUT undef);
                   8366:     close (OUT);
                   8367:     return ("ok");    
                   8368: }
                   8369: 
1.572     banghart 8370: sub files_in_path {
                   8371:     my ($user, $path) = @_;
                   8372:     my $filename = $user."savedfiles";
                   8373:     my %return_files;
1.1117    foxr     8374:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8375:     while (my $line_in = <IN>) {
1.574     banghart 8376:         chomp ($line_in);
                   8377:         my @paths_and_file = split (m!/!, $line_in);
                   8378:         my $file_part = pop (@paths_and_file);
                   8379:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8380:         $path_part.='/';
                   8381:         my $path_and_file = $path_part.$file_part;
                   8382:         if ($path_part eq $path) {
                   8383:             $return_files{$file_part}= 'selected';
                   8384:         }
                   8385:     }
1.574     banghart 8386:     close (IN);
                   8387:     return (\%return_files);
1.572     banghart 8388: }
                   8389: 
                   8390: # called in portfolio select mode, to show files selected NOT in current directory
                   8391: sub files_not_in_path {
                   8392:     my ($user, $path) = @_;
                   8393:     my $filename = $user."savedfiles";
                   8394:     my @return_files;
                   8395:     my $path_part;
1.1117    foxr     8396:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8397:     while (my $line = <IN>) {
1.572     banghart 8398:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8399:         my @paths_and_file = split(m|/|, $line);
                   8400:         my $file_part = pop(@paths_and_file);
                   8401:         chomp($file_part);
                   8402:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8403:         $path_part .= '/';
                   8404:         my $path_and_file = $path_part.$file_part;
                   8405:         if ($path_part ne $path) {
1.800     albertel 8406:             push(@return_files, ($path_and_file));
1.572     banghart 8407:         }
                   8408:     }
1.800     albertel 8409:     close(OUT);
1.574     banghart 8410:     return (@return_files);
1.572     banghart 8411: }
                   8412: 
1.745     raeburn  8413: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8414: 
1.745     raeburn  8415: sub get_portfile_permissions {
                   8416:     my ($domain,$user) = @_;
1.613     albertel 8417:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8418:     my ($tmp)=keys(%current_permissions);
                   8419:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8420:     return \%current_permissions;
                   8421: }
                   8422: 
                   8423: #---------------------------------------------Get portfolio file access controls
                   8424: 
1.749     raeburn  8425: sub get_access_controls {
1.745     raeburn  8426:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8427:     my %access;
                   8428:     my $real_file = $file;
                   8429:     $file =~ s/\.meta$//;
1.745     raeburn  8430:     if (defined($file)) {
1.749     raeburn  8431:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8432:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8433:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8434:             }
                   8435:         }
1.745     raeburn  8436:     } else {
1.749     raeburn  8437:         foreach my $key (keys(%{$current_permissions})) {
                   8438:             if ($key =~ /\0accesscontrol$/) {
                   8439:                 if (defined($group)) {
                   8440:                     if ($key !~ m-^\Q$group\E/-) {
                   8441:                         next;
                   8442:                     }
                   8443:                 }
                   8444:                 my ($fullpath) = split(/\0/,$key);
                   8445:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8446:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8447:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8448:                     }
                   8449:                 }
                   8450:             }
                   8451:         }
                   8452:     }
                   8453:     return %access;
                   8454: }
                   8455: 
                   8456: sub modify_access_controls {
                   8457:     my ($file_name,$changes,$domain,$user)=@_;
                   8458:     my ($outcome,$deloutcome);
                   8459:     my %store_permissions;
                   8460:     my %new_values;
                   8461:     my %new_control;
                   8462:     my %translation;
                   8463:     my @deletions = ();
                   8464:     my $now = time;
                   8465:     if (exists($$changes{'activate'})) {
                   8466:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8467:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8468:             my $numnew = scalar(@newitems);
                   8469:             for (my $i=0; $i<$numnew; $i++) {
                   8470:                 my $newkey = $newitems[$i];
                   8471:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8472:                 if ($newkey =~ /^\d+:/) { 
                   8473:                     $newkey =~ s/^(\d+)/$newid/;
                   8474:                     $translation{$1} = $newid;
                   8475:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8476:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8477:                     $translation{$1} = $newid;
                   8478:                 }
1.749     raeburn  8479:                 $new_values{$file_name."\0".$newkey} = 
                   8480:                                           $$changes{'activate'}{$newitems[$i]};
                   8481:                 $new_control{$newkey} = $now;
                   8482:             }
                   8483:         }
                   8484:     }
                   8485:     my %todelete;
                   8486:     my %changed_items;
                   8487:     foreach my $action ('delete','update') {
                   8488:         if (exists($$changes{$action})) {
                   8489:             if (ref($$changes{$action}) eq 'HASH') {
                   8490:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8491:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8492:                     if ($action eq 'delete') { 
                   8493:                         $todelete{$itemnum} = 1;
                   8494:                     } else {
                   8495:                         $changed_items{$itemnum} = $key;
                   8496:                     }
                   8497:                 }
1.745     raeburn  8498:             }
                   8499:         }
1.749     raeburn  8500:     }
                   8501:     # get lock on access controls for file.
                   8502:     my $lockhash = {
                   8503:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8504:                                                        ':'.$env{'user.domain'},
                   8505:                    }; 
                   8506:     my $tries = 0;
                   8507:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8508:    
                   8509:     while (($gotlock ne 'ok') && $tries <3) {
                   8510:         $tries ++;
                   8511:         sleep 1;
                   8512:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8513:     }
                   8514:     if ($gotlock eq 'ok') {
                   8515:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8516:         my ($tmp)=keys(%curr_permissions);
                   8517:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8518:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8519:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8520:             if (ref($curr_controls) eq 'HASH') {
                   8521:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8522:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8523:                     if (defined($todelete{$itemnum})) {
                   8524:                         push(@deletions,$file_name."\0".$control_item);
                   8525:                     } else {
                   8526:                         if (defined($changed_items{$itemnum})) {
                   8527:                             $new_control{$changed_items{$itemnum}} = $now;
                   8528:                             push(@deletions,$file_name."\0".$control_item);
                   8529:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8530:                         } else {
                   8531:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8532:                         }
                   8533:                     }
1.745     raeburn  8534:                 }
                   8535:             }
                   8536:         }
1.970     raeburn  8537:         my ($group);
                   8538:         if (&is_course($domain,$user)) {
                   8539:             ($group,my $file) = split(/\//,$file_name,2);
                   8540:         }
1.749     raeburn  8541:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8542:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8543:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8544:         #  remove lock
                   8545:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8546:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8547:         my $sqlresult =
1.970     raeburn  8548:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8549:                                     $group);
1.749     raeburn  8550:     } else {
                   8551:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8552:     }
1.749     raeburn  8553:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8554: }
                   8555: 
1.827     raeburn  8556: sub make_public_indefinitely {
                   8557:     my ($requrl) = @_;
                   8558:     my $now = time;
                   8559:     my $action = 'activate';
                   8560:     my $aclnum = 0;
                   8561:     if (&is_portfolio_url($requrl)) {
                   8562:         my (undef,$udom,$unum,$file_name,$group) =
                   8563:             &parse_portfolio_url($requrl);
                   8564:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8565:         my %access_controls = &get_access_controls($current_perms,
                   8566:                                                    $group,$file_name);
                   8567:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8568:             my ($num,$scope,$end,$start) = 
                   8569:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8570:             if ($scope eq 'public') {
                   8571:                 if ($start <= $now && $end == 0) {
                   8572:                     $action = 'none';
                   8573:                 } else {
                   8574:                     $action = 'update';
                   8575:                     $aclnum = $num;
                   8576:                 }
                   8577:                 last;
                   8578:             }
                   8579:         }
                   8580:         if ($action eq 'none') {
                   8581:              return 'ok';
                   8582:         } else {
                   8583:             my %changes;
                   8584:             my $newend = 0;
                   8585:             my $newstart = $now;
                   8586:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   8587:             $changes{$action}{$newkey} = {
                   8588:                 type => 'public',
                   8589:                 time => {
                   8590:                     start => $newstart,
                   8591:                     end   => $newend,
                   8592:                 },
                   8593:             };
                   8594:             my ($outcome,$deloutcome,$new_values,$translation) =
                   8595:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   8596:             return $outcome;
                   8597:         }
                   8598:     } else {
                   8599:         return 'invalid';
                   8600:     }
                   8601: }
                   8602: 
1.745     raeburn  8603: #------------------------------------------------------Get Marked as Read Only
                   8604: 
                   8605: sub get_marked_as_readonly {
                   8606:     my ($domain,$user,$what,$group) = @_;
                   8607:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 8608:     my @readonly_files;
1.629     banghart 8609:     my $cmp1=$what;
                   8610:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  8611:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8612:         if (defined($group)) {
                   8613:             if ($file_name !~ m-^\Q$group\E/-) {
                   8614:                 next;
                   8615:             }
                   8616:         }
1.561     banghart 8617:         if (ref($value) eq "ARRAY"){
                   8618:             foreach my $stored_what (@{$value}) {
1.629     banghart 8619:                 my $cmp2=$stored_what;
1.759     albertel 8620:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  8621:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  8622:                 }
1.629     banghart 8623:                 if ($cmp1 eq $cmp2) {
1.561     banghart 8624:                     push(@readonly_files, $file_name);
1.745     raeburn  8625:                     last;
1.563     banghart 8626:                 } elsif (!defined($what)) {
                   8627:                     push(@readonly_files, $file_name);
1.745     raeburn  8628:                     last;
1.561     banghart 8629:                 }
                   8630:             }
1.745     raeburn  8631:         }
1.561     banghart 8632:     }
                   8633:     return @readonly_files;
                   8634: }
1.577     banghart 8635: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 8636: 
1.577     banghart 8637: sub get_marked_as_readonly_hash {
1.745     raeburn  8638:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 8639:     my %readonly_files;
1.745     raeburn  8640:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8641:         if (defined($group)) {
                   8642:             if ($file_name !~ m-^\Q$group\E/-) {
                   8643:                 next;
                   8644:             }
                   8645:         }
1.577     banghart 8646:         if (ref($value) eq "ARRAY"){
                   8647:             foreach my $stored_what (@{$value}) {
1.745     raeburn  8648:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 8649:                     foreach my $lock_descriptor(@{$stored_what}) {
                   8650:                         if ($lock_descriptor eq 'graded') {
                   8651:                             $readonly_files{$file_name} = 'graded';
                   8652:                         } elsif ($lock_descriptor eq 'handback') {
                   8653:                             $readonly_files{$file_name} = 'handback';
                   8654:                         } else {
                   8655:                             if (!exists($readonly_files{$file_name})) {
                   8656:                                 $readonly_files{$file_name} = 'locked';
                   8657:                             }
                   8658:                         }
1.745     raeburn  8659:                     }
1.750     banghart 8660:                 } 
1.577     banghart 8661:             }
                   8662:         } 
                   8663:     }
                   8664:     return %readonly_files;
                   8665: }
1.559     banghart 8666: # ------------------------------------------------------------ Unmark as Read Only
                   8667: 
                   8668: sub unmark_as_readonly {
1.629     banghart 8669:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   8670:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  8671:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 8672:     $file_name = &declutter_portfile($file_name);
1.634     albertel 8673:     my $symb_crs = $what;
                   8674:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  8675:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 8676:     my ($tmp)=keys(%current_permissions);
                   8677:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8678:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 8679:     foreach my $file (@readonly_files) {
1.759     albertel 8680: 	my $clean_file = &declutter_portfile($file);
                   8681: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 8682: 	my $current_locks = $current_permissions{$file};
1.563     banghart 8683:         my @new_locks;
                   8684:         my @del_keys;
                   8685:         if (ref($current_locks) eq "ARRAY"){
                   8686:             foreach my $locker (@{$current_locks}) {
1.632     albertel 8687:                 my $compare=$locker;
1.749     raeburn  8688:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  8689:                     $compare=join('',@{$locker});
1.746     raeburn  8690:                     if ($compare ne $symb_crs) {
                   8691:                         push(@new_locks, $locker);
                   8692:                     }
1.563     banghart 8693:                 }
                   8694:             }
1.650     albertel 8695:             if (scalar(@new_locks) > 0) {
1.563     banghart 8696:                 $current_permissions{$file} = \@new_locks;
                   8697:             } else {
                   8698:                 push(@del_keys, $file);
1.613     albertel 8699:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 8700:                 delete($current_permissions{$file});
1.563     banghart 8701:             }
                   8702:         }
1.561     banghart 8703:     }
1.613     albertel 8704:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8705:     return;
                   8706: }
1.512     banghart 8707: 
1.17      www      8708: # ------------------------------------------------------------ Directory lister
                   8709: 
                   8710: sub dirlist {
1.955     raeburn  8711:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      8712:     $uri=~s/^\///;
                   8713:     $uri=~s/\/$//;
1.253     stredwic 8714:     my ($udom, $uname);
1.955     raeburn  8715:     if ($getuserdir) {
1.253     stredwic 8716:         $udom = $userdomain;
                   8717:         $uname = $username;
1.955     raeburn  8718:     } else {
                   8719:         (undef,$udom,$uname)=split(/\//,$uri);
                   8720:         if(defined($userdomain)) {
                   8721:             $udom = $userdomain;
                   8722:         }
                   8723:         if(defined($username)) {
                   8724:             $uname = $username;
                   8725:         }
1.253     stredwic 8726:     }
1.955     raeburn  8727:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 8728: 
1.955     raeburn  8729:     $dirRoot = $perlvar{'lonDocRoot'};
                   8730:     if (defined($getpropath)) {
                   8731:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 8732:         $dirRoot =~ s/\/$//;
1.955     raeburn  8733:     } elsif (defined($getuserdir)) {
                   8734:         my $subdir=$uname.'__';
                   8735:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   8736:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   8737:                    ."/$udom/$subdir/$uname";
                   8738:     } elsif (defined($alternateRoot)) {
                   8739:         $dirRoot = $alternateRoot;
1.751     banghart 8740:     }
1.253     stredwic 8741: 
                   8742:     if($udom) {
                   8743:         if($uname) {
1.1135    raeburn  8744:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  8745:             if ($uhome eq 'no_host') {
                   8746:                 return ([],'no_host');
                   8747:             }
1.955     raeburn  8748:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  8749:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  8750:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  8751:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8752:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  8753:             } else {
                   8754:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8755:             }
1.605     matthew  8756:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8757:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  8758:                 @listing_results = split(/:/,$listing);
                   8759:             } else {
                   8760:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8761:             }
1.1135    raeburn  8762:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  8763:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8764:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8765:                 return ([],$listing);
                   8766:             } else {
                   8767:                 return (\@listing_results);
1.1135    raeburn  8768:             }
1.955     raeburn  8769:         } elsif(!$alternateRoot) {
1.1136    raeburn  8770:             my (%allusers,%listerror);
1.841     albertel 8771: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  8772:  	    foreach my $tryserver (keys(%servers)) {
                   8773:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   8774:                                   &escape($udom),$tryserver);
                   8775:                 if ($listing eq 'unknown_cmd') {
                   8776: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8777: 				      $udom, $tryserver);
                   8778:                 } else {
                   8779:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8780:                 }
1.841     albertel 8781: 		if ($listing eq 'unknown_cmd') {
                   8782: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8783: 				      $udom, $tryserver);
                   8784: 		    @listing_results = split(/:/,$listing);
                   8785: 		} else {
                   8786: 		    @listing_results =
                   8787: 			map { &unescape($_); } split(/:/,$listing);
                   8788: 		}
1.1136    raeburn  8789:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   8790:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8791:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8792:                     $listerror{$tryserver} = $listing;
                   8793:                 } else {
1.841     albertel 8794: 		    foreach my $line (@listing_results) {
                   8795: 			my ($entry) = split(/&/,$line,2);
                   8796: 			$allusers{$entry} = 1;
                   8797: 		    }
                   8798: 		}
1.253     stredwic 8799:             }
1.1136    raeburn  8800:             my @alluserslist=();
1.800     albertel 8801:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  8802:                 push(@alluserslist,$user.'&user');
1.253     stredwic 8803:             }
1.1136    raeburn  8804:             return (\@alluserslist);
1.253     stredwic 8805:         } else {
1.1136    raeburn  8806:             return ([],'missing username');
1.253     stredwic 8807:         }
1.955     raeburn  8808:     } elsif(!defined($getpropath)) {
1.1136    raeburn  8809:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   8810:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   8811:         return (\@all_domains);
1.955     raeburn  8812:     } else {
1.1136    raeburn  8813:         return ([],'missing domain');
1.275     stredwic 8814:     }
                   8815: }
                   8816: 
                   8817: # --------------------------------------------- GetFileTimestamp
                   8818: # This function utilizes dirlist and returns the date stamp for
                   8819: # when it was last modified.  It will also return an error of -1
                   8820: # if an error occurs
                   8821: 
                   8822: sub GetFileTimestamp {
1.955     raeburn  8823:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 8824:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   8825:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  8826:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   8827:                                     undef,$getuserdir);
                   8828:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8829:         return -1;
                   8830:     }
                   8831:     if (ref($fileref) eq 'ARRAY') {
                   8832:         my @stats = split('&',$fileref->[0]);
1.375     matthew  8833:         # @stats contains first the filename, then the stat output
                   8834:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 8835:     } else {
                   8836:         return -1;
1.253     stredwic 8837:     }
1.26      www      8838: }
                   8839: 
1.712     albertel 8840: sub stat_file {
                   8841:     my ($uri) = @_;
1.787     albertel 8842:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8843: 
1.955     raeburn  8844:     my ($udom,$uname,$file);
1.712     albertel 8845:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8846: 	($udom,$uname,$file) =
1.811     albertel 8847: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8848: 	$file = 'userfiles/'.$file;
                   8849:     }
                   8850:     if ($uri =~ m-^/res/-) {
                   8851: 	($udom,$uname) = 
1.807     albertel 8852: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8853: 	$file = $uri;
                   8854:     }
                   8855: 
                   8856:     if (!$udom || !$uname || !$file) {
                   8857: 	# unable to handle the uri
                   8858: 	return ();
                   8859:     }
1.956     raeburn  8860:     my $getpropath;
                   8861:     if ($file =~ /^userfiles\//) {
                   8862:         $getpropath = 1;
                   8863:     }
1.1136    raeburn  8864:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   8865:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8866:         return ();
                   8867:     } else {
                   8868:         if (ref($listref) eq 'ARRAY') {
                   8869:             my @stats = split('&',$listref->[0]);
                   8870: 	    shift(@stats); #filename is first
                   8871: 	    return @stats;
                   8872:         }
1.712     albertel 8873:     }
                   8874:     return ();
                   8875: }
                   8876: 
1.26      www      8877: # -------------------------------------------------------- Value of a Condition
                   8878: 
1.713     albertel 8879: # gets the value of a specific preevaluated condition
                   8880: #    stored in the string  $env{user.state.<cid>}
                   8881: # or looks up a condition reference in the bighash and if if hasn't
                   8882: # already been evaluated recurses into docondval to get the value of
                   8883: # the condition, then memoizing it to 
                   8884: #   $env{user.state.<cid>.<condition>}
1.40      www      8885: sub directcondval {
                   8886:     my $number=shift;
1.620     albertel 8887:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8888: 	&Apache::lonuserstate::evalstate();
                   8889:     }
1.713     albertel 8890:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8891: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8892:     } elsif ($number =~ /^_/) {
                   8893: 	my $sub_condition;
                   8894: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8895: 		&GDBM_READER(),0640)) {
                   8896: 	    $sub_condition=$bighash{'conditions'.$number};
                   8897: 	    untie(%bighash);
                   8898: 	}
                   8899: 	my $value = &docondval($sub_condition);
1.949     raeburn  8900: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8901: 	return $value;
                   8902:     }
1.620     albertel 8903:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8904:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8905:     } else {
                   8906:        return 2;
                   8907:     }
                   8908: }
                   8909: 
1.713     albertel 8910: # get the collection of conditions for this resource
1.26      www      8911: sub condval {
                   8912:     my $condidx=shift;
1.54      www      8913:     my $allpathcond='';
1.713     albertel 8914:     foreach my $cond (split(/\|/,$condidx)) {
                   8915: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8916: 	    $allpathcond.=
                   8917: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8918: 	}
1.191     harris41 8919:     }
1.54      www      8920:     $allpathcond=~s/\|$//;
1.713     albertel 8921:     return &docondval($allpathcond);
                   8922: }
                   8923: 
                   8924: #evaluates an expression of conditions
                   8925: sub docondval {
                   8926:     my ($allpathcond) = @_;
                   8927:     my $result=0;
                   8928:     if ($env{'request.course.id'}
                   8929: 	&& defined($allpathcond)) {
                   8930: 	my $operand='|';
                   8931: 	my @stack;
                   8932: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8933: 	    if ($chunk eq '(') {
                   8934: 		push @stack,($operand,$result);
                   8935: 	    } elsif ($chunk eq ')') {
                   8936: 		my $before=pop @stack;
                   8937: 		if (pop @stack eq '&') {
                   8938: 		    $result=$result>$before?$before:$result;
                   8939: 		} else {
                   8940: 		    $result=$result>$before?$result:$before;
                   8941: 		}
                   8942: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8943: 		$operand=$chunk;
                   8944: 	    } else {
                   8945: 		my $new=directcondval($chunk);
                   8946: 		if ($operand eq '&') {
                   8947: 		    $result=$result>$new?$new:$result;
                   8948: 		} else {
                   8949: 		    $result=$result>$new?$result:$new;
                   8950: 		}
                   8951: 	    }
                   8952: 	}
1.26      www      8953:     }
                   8954:     return $result;
1.421     albertel 8955: }
                   8956: 
                   8957: # ---------------------------------------------------- Devalidate courseresdata
                   8958: 
                   8959: sub devalidatecourseresdata {
                   8960:     my ($coursenum,$coursedomain)=@_;
                   8961:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8962:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8963: }
                   8964: 
1.763     www      8965: 
1.200     www      8966: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8967: #
                   8968: #  Parameters:
                   8969: #      $coursenum    - Number of the course.
                   8970: #      $coursedomain - Domain at which the course was created.
                   8971: #  Returns:
                   8972: #     A hash of the course parameters along (I think) with timestamps
                   8973: #     and version info.
1.877     foxr     8974: 
1.624     albertel 8975: sub get_courseresdata {
                   8976:     my ($coursenum,$coursedomain)=@_;
1.200     www      8977:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8978:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8979:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8980:     my %dumpreply;
1.417     albertel 8981:     unless (defined($cached)) {
1.624     albertel 8982: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8983: 	$result=\%dumpreply;
1.251     albertel 8984: 	my ($tmp) = keys(%dumpreply);
                   8985: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8986: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8987: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8988: 	    return $tmp;
1.416     albertel 8989: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8990: 	    $result=undef;
1.599     albertel 8991: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8992: 	}
                   8993:     }
1.624     albertel 8994:     return $result;
                   8995: }
                   8996: 
1.633     albertel 8997: sub devalidateuserresdata {
                   8998:     my ($uname,$udom)=@_;
                   8999:     my $hashid="$udom:$uname";
                   9000:     &devalidate_cache_new('userres',$hashid);
                   9001: }
                   9002: 
1.624     albertel 9003: sub get_userresdata {
                   9004:     my ($uname,$udom)=@_;
                   9005:     #most student don\'t have any data set, check if there is some data
                   9006:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   9007: 
                   9008:     my $hashid="$udom:$uname";
                   9009:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   9010:     if (!defined($cached)) {
                   9011: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   9012: 	$result=\%resourcedata;
                   9013: 	&do_cache_new('userres',$hashid,$result,600);
                   9014:     }
                   9015:     my ($tmp)=keys(%$result);
                   9016:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   9017: 	return $result;
                   9018:     }
                   9019:     #error 2 occurs when the .db doesn't exist
                   9020:     if ($tmp!~/error: 2 /) {
1.672     albertel 9021: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 9022: 		 " Trying to get resource data for ".
                   9023: 		 $uname." at ".$udom.": ".
                   9024: 		 $tmp."</font>");
                   9025:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 9026: 	#&EXT_cache_set($udom,$uname);
                   9027: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 9028: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 9029:     }
                   9030:     return $tmp;
                   9031: }
1.879     foxr     9032: #----------------------------------------------- resdata - return resource data
                   9033: #  Purpose:
                   9034: #    Return resource data for either users or for a course.
                   9035: #  Parameters:
                   9036: #     $name      - Course/user name.
                   9037: #     $domain    - Name of the domain the user/course is registered on.
                   9038: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   9039: #     @which     - Array of names of resources desired.
                   9040: #  Returns:
                   9041: #     The value of the first reasource in @which that is found in the
                   9042: #     resource hash.
                   9043: #  Exceptional Conditions:
                   9044: #     If the $type passed in is not valid (not the string 'course' or 
                   9045: #     'user', an undefined  reference is returned.
                   9046: #     If none of the resources are found, an undef is returned
1.624     albertel 9047: sub resdata {
                   9048:     my ($name,$domain,$type,@which)=@_;
                   9049:     my $result;
                   9050:     if ($type eq 'course') {
                   9051: 	$result=&get_courseresdata($name,$domain);
                   9052:     } elsif ($type eq 'user') {
                   9053: 	$result=&get_userresdata($name,$domain);
                   9054:     }
                   9055:     if (!ref($result)) { return $result; }    
1.251     albertel 9056:     foreach my $item (@which) {
1.927     albertel 9057: 	if (defined($result->{$item->[0]})) {
                   9058: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 9059: 	}
1.250     albertel 9060:     }
1.291     albertel 9061:     return undef;
1.200     www      9062: }
                   9063: 
1.379     matthew  9064: #
                   9065: # EXT resource caching routines
                   9066: #
                   9067: 
                   9068: sub clear_EXT_cache_status {
1.383     albertel 9069:     &delenv('cache.EXT.');
1.379     matthew  9070: }
                   9071: 
                   9072: sub EXT_cache_status {
                   9073:     my ($target_domain,$target_user) = @_;
1.383     albertel 9074:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9075:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9076:         # We know already the user has no data
                   9077:         return 1;
                   9078:     } else {
                   9079:         return 0;
                   9080:     }
                   9081: }
                   9082: 
                   9083: sub EXT_cache_set {
                   9084:     my ($target_domain,$target_user) = @_;
1.383     albertel 9085:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9086:     #&appenv({$cachename => time});
1.379     matthew  9087: }
                   9088: 
1.28      www      9089: # --------------------------------------------------------- Value of a Variable
1.58      www      9090: sub EXT {
1.715     albertel 9091: 
1.395     albertel 9092:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      9093:     unless ($varname) { return ''; }
1.218     albertel 9094:     #get real user name/domain, courseid and symb
                   9095:     my $courseid;
1.359     albertel 9096:     my $publicuser;
1.427     www      9097:     if ($symbparm) {
                   9098: 	$symbparm=&get_symb_from_alias($symbparm);
                   9099:     }
1.218     albertel 9100:     if (!($uname && $udom)) {
1.790     albertel 9101:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9102:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9103:     } else {
1.620     albertel 9104: 	$courseid=$env{'request.course.id'};
1.218     albertel 9105:     }
1.48      www      9106:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9107:     my $rest;
1.320     albertel 9108:     if (defined($therest[0])) {
1.48      www      9109:        $rest=join('.',@therest);
                   9110:     } else {
                   9111:        $rest='';
                   9112:     }
1.320     albertel 9113: 
1.57      www      9114:     my $qualifierrest=$qualifier;
                   9115:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9116:     my $spacequalifierrest=$space;
                   9117:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9118:     if ($realm eq 'user') {
1.48      www      9119: # --------------------------------------------------------------- user.resource
                   9120: 	if ($space eq 'resource') {
1.651     albertel 9121: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9122: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9123: 		 &&
1.744     albertel 9124: 		 ($symbparm eq &symbread()) ) {	
                   9125: 		# if we are in the middle of processing the resource the
                   9126: 		# get the value we are planning on committing
                   9127:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9128:                     return $Apache::lonhomework::results{$qualifierrest};
                   9129:                 } else {
                   9130:                     return $Apache::lonhomework::history{$qualifierrest};
                   9131:                 }
1.335     albertel 9132: 	    } else {
1.359     albertel 9133: 		my %restored;
1.620     albertel 9134: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9135: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9136: 		} else {
                   9137: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9138: 		}
1.335     albertel 9139: 		return $restored{$qualifierrest};
                   9140: 	    }
1.48      www      9141: # ----------------------------------------------------------------- user.access
                   9142:         } elsif ($space eq 'access') {
1.218     albertel 9143: 	    # FIXME - not supporting calls for a specific user
1.48      www      9144:             return &allowed($qualifier,$rest);
                   9145: # ------------------------------------------ user.preferences, user.environment
                   9146:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9147: 	    if (($uname eq $env{'user.name'}) &&
                   9148: 		($udom eq $env{'user.domain'})) {
                   9149: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9150: 	    } else {
1.359     albertel 9151: 		my %returnhash;
                   9152: 		if (!$publicuser) {
                   9153: 		    %returnhash=&userenvironment($udom,$uname,
                   9154: 						 $qualifierrest);
                   9155: 		}
1.218     albertel 9156: 		return $returnhash{$qualifierrest};
                   9157: 	    }
1.48      www      9158: # ----------------------------------------------------------------- user.course
                   9159:         } elsif ($space eq 'course') {
1.218     albertel 9160: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9161:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9162: # ------------------------------------------------------------------- user.role
                   9163:         } elsif ($space eq 'role') {
1.218     albertel 9164: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9165:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9166:             if ($qualifier eq 'value') {
                   9167: 		return $role;
                   9168:             } elsif ($qualifier eq 'extent') {
                   9169:                 return $where;
                   9170:             }
                   9171: # ----------------------------------------------------------------- user.domain
                   9172:         } elsif ($space eq 'domain') {
1.218     albertel 9173:             return $udom;
1.48      www      9174: # ------------------------------------------------------------------- user.name
                   9175:         } elsif ($space eq 'name') {
1.218     albertel 9176:             return $uname;
1.48      www      9177: # ---------------------------------------------------- Any other user namespace
1.29      www      9178:         } else {
1.359     albertel 9179: 	    my %reply;
                   9180: 	    if (!$publicuser) {
                   9181: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9182: 	    }
                   9183: 	    return $reply{$qualifierrest};
1.48      www      9184:         }
1.236     www      9185:     } elsif ($realm eq 'query') {
                   9186: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9187:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9188: 						[$spacequalifierrest]);
1.620     albertel 9189: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9190:    } elsif ($realm eq 'request') {
1.48      www      9191: # ------------------------------------------------------------- request.browser
                   9192:         if ($space eq 'browser') {
1.1145    bisitz   9193:             return $env{'browser.'.$qualifier};
1.57      www      9194: # ------------------------------------------------------------ request.filename
                   9195:         } else {
1.620     albertel 9196:             return $env{'request.'.$spacequalifierrest};
1.29      www      9197:         }
1.28      www      9198:     } elsif ($realm eq 'course') {
1.48      www      9199: # ---------------------------------------------------------- course.description
1.620     albertel 9200:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9201:     } elsif ($realm eq 'resource') {
1.165     www      9202: 
1.620     albertel 9203: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9204: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9205: 	}
1.693     albertel 9206: 
                   9207: 	if ($space eq 'title') {
                   9208: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9209: 	    return &gettitle($symbparm);
                   9210: 	}
                   9211: 	
                   9212: 	if ($space eq 'map') {
                   9213: 	    my ($map) = &decode_symb($symbparm);
                   9214: 	    return &symbread($map);
                   9215: 	}
1.905     albertel 9216: 	if ($space eq 'filename') {
                   9217: 	    if ($symbparm) {
                   9218: 		return &clutter((&decode_symb($symbparm))[2]);
                   9219: 	    }
                   9220: 	    return &hreflocation('',$env{'request.filename'});
                   9221: 	}
1.693     albertel 9222: 
                   9223: 	my ($section, $group, @groups);
1.593     albertel 9224: 	my ($courselevelm,$courselevel);
1.539     albertel 9225: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9226: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9227: 
1.218     albertel 9228: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9229: 
1.60      www      9230: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9231: 	    my $symbp=$symbparm;
1.735     albertel 9232: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9233: 
                   9234: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9235: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9236: 
1.620     albertel 9237: 	    if (($env{'user.name'} eq $uname) &&
                   9238: 		($env{'user.domain'} eq $udom)) {
                   9239: 		$section=$env{'request.course.sec'};
1.733     raeburn  9240:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9241:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9242: 	    } else {
1.539     albertel 9243: 		if (! defined($usection)) {
1.551     albertel 9244: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9245: 		} else {
                   9246: 		    $section = $usection;
                   9247: 		}
1.733     raeburn  9248:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9249: 	    }
                   9250: 
                   9251: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9252: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9253: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9254: 
1.593     albertel 9255: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9256: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9257: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9258: 
1.60      www      9259: # ----------------------------------------------------------- first, check user
1.624     albertel 9260: 
                   9261: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9262: 				       ([$courselevelr,'resource'],
                   9263: 					[$courselevelm,'map'     ],
                   9264: 					[$courselevel, 'course'  ]));
1.931     albertel 9265: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9266: 
1.594     albertel 9267: # ------------------------------------------------ second, check some of course
1.684     raeburn  9268:             my $coursereply;
1.691     raeburn  9269:             if (@groups > 0) {
                   9270:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9271:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9272:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9273:             }
1.96      www      9274: 
1.684     raeburn  9275: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9276: 				  $env{'course.'.$courseid.'.domain'},
                   9277: 				  'course',
                   9278: 				  ([$seclevelr,   'resource'],
                   9279: 				   [$seclevelm,   'map'     ],
                   9280: 				   [$seclevel,    'course'  ],
                   9281: 				   [$courselevelr,'resource']));
                   9282: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9283: 
1.60      www      9284: # ------------------------------------------------------ third, check map parms
1.218     albertel 9285: 	    my %parmhash=();
                   9286: 	    my $thisparm='';
                   9287: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9288: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9289: 		    &GDBM_READER(),0640)) {
1.218     albertel 9290: 		$thisparm=$parmhash{$symbparm};
                   9291: 		untie(%parmhash);
                   9292: 	    }
1.927     albertel 9293: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9294: 	}
1.594     albertel 9295: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9296: 
1.218     albertel 9297: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9298: 	my $filename;
                   9299: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9300: 	if ($symbparm) {
1.409     www      9301: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9302: 	} else {
1.620     albertel 9303: 	    $filename=$env{'request.filename'};
1.282     albertel 9304: 	}
                   9305: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9306: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9307: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9308: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9309: 
1.927     albertel 9310: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9311: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9312: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9313: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9314: 				     $env{'course.'.$courseid.'.domain'},
                   9315: 				     'course',
1.927     albertel 9316: 				     ([$courselevelm,'map'   ],
                   9317: 				      [$courselevel, 'course']));
                   9318: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9319: 	}
1.145     www      9320: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9321: 	unless ($space eq '0') {
1.336     albertel 9322: 	    my @parts=split(/_/,$space);
                   9323: 	    my $id=pop(@parts);
                   9324: 	    my $part=join('_',@parts);
                   9325: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9326: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9327: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9328: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9329: 	}
1.395     albertel 9330: 	if ($recurse) { return undef; }
                   9331: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9332: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9333: # ---------------------------------------------------- Any other user namespace
                   9334:     } elsif ($realm eq 'environment') {
                   9335: # ----------------------------------------------------------------- environment
1.620     albertel 9336: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9337: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9338: 	} else {
1.770     albertel 9339: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9340: 		return '';
                   9341: 	    }
1.219     albertel 9342: 	    my %returnhash=&userenvironment($udom,$uname,
                   9343: 					    $spacequalifierrest);
                   9344: 	    return $returnhash{$spacequalifierrest};
                   9345: 	}
1.28      www      9346:     } elsif ($realm eq 'system') {
1.48      www      9347: # ----------------------------------------------------------------- system.time
                   9348: 	if ($space eq 'time') {
                   9349: 	    return time;
                   9350:         }
1.696     albertel 9351:     } elsif ($realm eq 'server') {
                   9352: # ----------------------------------------------------------------- system.time
                   9353: 	if ($space eq 'name') {
                   9354: 	    return $ENV{'SERVER_NAME'};
                   9355:         }
1.28      www      9356:     }
1.48      www      9357:     return '';
1.61      www      9358: }
                   9359: 
1.927     albertel 9360: sub get_reply {
                   9361:     my ($reply_value) = @_;
1.940     raeburn  9362:     if (ref($reply_value) eq 'ARRAY') {
                   9363:         if (wantarray) {
                   9364: 	    return @$reply_value;
                   9365:         }
                   9366:         return $reply_value->[0];
                   9367:     } else {
                   9368:         return $reply_value;
1.927     albertel 9369:     }
                   9370: }
                   9371: 
1.691     raeburn  9372: sub check_group_parms {
                   9373:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9374:     my @groupitems = ();
                   9375:     my $resultitem;
1.927     albertel 9376:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9377:     foreach my $group (@{$groups}) {
                   9378:         foreach my $level (@levels) {
1.927     albertel 9379:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9380:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9381:         }
                   9382:     }
                   9383:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9384:                             $env{'course.'.$courseid.'.domain'},
                   9385:                                      'course',@groupitems);
                   9386:     return $coursereply;
                   9387: }
                   9388: 
                   9389: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9390:     my ($courseid,@groups) = @_;
                   9391:     @groups = sort(@groups);
1.691     raeburn  9392:     return @groups;
                   9393: }
                   9394: 
1.395     albertel 9395: sub packages_tab_default {
                   9396:     my ($uri,$varname)=@_;
                   9397:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9398: 
                   9399:     my (@extension,@specifics,$do_default);
                   9400:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9401: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9402: 	if ($pack_type eq 'default') {
                   9403: 	    $do_default=1;
                   9404: 	} elsif ($pack_type eq 'extension') {
                   9405: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9406: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9407: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9408: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9409: 	}
                   9410:     }
                   9411:     # first look for a package that matches the requested part id
                   9412:     foreach my $package (@specifics) {
                   9413: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9414: 	next if ($pack_part ne $part);
                   9415: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9416: 	    return $packagetab{"$pack_type&$name&default"};
                   9417: 	}
                   9418:     }
                   9419:     # look for any possible matching non extension_ package
                   9420:     foreach my $package (@specifics) {
                   9421: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9422: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9423: 	    return $packagetab{"$pack_type&$name&default"};
                   9424: 	}
1.585     albertel 9425: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9426: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9427: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9428: 	}
                   9429:     }
1.738     albertel 9430:     # look for any posible extension_ match
                   9431:     foreach my $package (@extension) {
                   9432: 	my ($package,$pack_type)=@{$package};
                   9433: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9434: 	    return $packagetab{"$pack_type&$name&default"};
                   9435: 	}
                   9436: 	if (defined($packagetab{$package."&$name&default"})) {
                   9437: 	    return $packagetab{$package."&$name&default"};
                   9438: 	}
                   9439:     }
                   9440:     # look for a global default setting
                   9441:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9442: 	return $packagetab{"default&$name&default"};
                   9443:     }
1.395     albertel 9444:     return undef;
                   9445: }
                   9446: 
1.334     albertel 9447: sub add_prefix_and_part {
                   9448:     my ($prefix,$part)=@_;
                   9449:     my $keyroot;
                   9450:     if (defined($prefix) && $prefix !~ /^__/) {
                   9451: 	# prefix that has a part already
                   9452: 	$keyroot=$prefix;
                   9453:     } elsif (defined($prefix)) {
                   9454: 	# prefix that is missing a part
                   9455: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9456:     } else {
                   9457: 	# no prefix at all
                   9458: 	if (defined($part)) { $keyroot='_'.$part; }
                   9459:     }
                   9460:     return $keyroot;
                   9461: }
                   9462: 
1.71      www      9463: # ---------------------------------------------------------------- Get metadata
                   9464: 
1.599     albertel 9465: my %metaentry;
1.1070    www      9466: my %importedpartids;
1.71      www      9467: sub metadata {
1.176     www      9468:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9469:     $uri=&declutter($uri);
1.288     albertel 9470:     # if it is a non metadata possible uri return quickly
1.529     albertel 9471:     if (($uri eq '') || 
                   9472: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 9473: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  9474:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9475: 	return undef;
                   9476:     }
1.1140    www      9477:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9478: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9479: 	return undef;
1.288     albertel 9480:     }
1.73      www      9481:     my $filename=$uri;
                   9482:     $uri=~s/\.meta$//;
1.172     www      9483: #
                   9484: # Is the metadata already cached?
1.177     www      9485: # Look at timestamp of caching
1.172     www      9486: # Everything is cached by the main uri, libraries are never directly cached
                   9487: #
1.428     albertel 9488:     if (!defined($liburi)) {
1.599     albertel 9489: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9490: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9491:     }
                   9492:     {
1.1069    www      9493: # Imported parts would go here
1.1070    www      9494:         my %importedids=();
                   9495:         my @origfileimportpartids=();
1.1069    www      9496:         my $importedparts=0;
1.172     www      9497: #
                   9498: # Is this a recursive call for a library?
                   9499: #
1.599     albertel 9500: #	if (! exists($metacache{$uri})) {
                   9501: #	    $metacache{$uri}={};
                   9502: #	}
1.924     albertel 9503: 	my $cachetime = 60*60;
1.171     www      9504:         if ($liburi) {
                   9505: 	    $liburi=&declutter($liburi);
                   9506:             $filename=$liburi;
1.401     bowersj2 9507:         } else {
1.599     albertel 9508: 	    &devalidate_cache_new('meta',$uri);
                   9509: 	    undef(%metaentry);
1.401     bowersj2 9510: 	}
1.140     www      9511:         my %metathesekeys=();
1.73      www      9512:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9513: 	my $metastring;
1.1140    www      9514: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9515: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9516: 	    $metastring = 
1.929     albertel 9517: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9518: 					  ('grade_target' => 'meta'));
                   9519: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9520: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9521:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9522: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9523: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9524: 	    $metastring=&getfile($file);
1.489     albertel 9525: 	}
1.208     albertel 9526:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9527:         my $token;
1.140     www      9528:         undef %metathesekeys;
1.71      www      9529:         while ($token=$parser->get_token) {
1.339     albertel 9530: 	    if ($token->[0] eq 'S') {
                   9531: 		if (defined($token->[2]->{'package'})) {
1.172     www      9532: #
                   9533: # This is a package - get package info
                   9534: #
1.339     albertel 9535: 		    my $package=$token->[2]->{'package'};
                   9536: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9537: 		    if (defined($token->[2]->{'id'})) { 
                   9538: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9539: 		    }
1.599     albertel 9540: 		    if ($metaentry{':packages'}) {
                   9541: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9542: 		    } else {
1.599     albertel 9543: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9544: 		    }
1.736     albertel 9545: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9546: 			my $part=$keyroot;
                   9547: 			$part=~s/^\_//;
1.736     albertel 9548: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9549: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9550: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9551: 			    # ignore package.tab specified default values
                   9552:                             # here &package_tab_default() will fetch those
                   9553: 			    if ($subp eq 'default') { next; }
1.736     albertel 9554: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9555: 			    my $unikey;
                   9556: 			    if ($pack =~ /_0$/) {
                   9557: 				$unikey='parameter_0_'.$name;
                   9558: 				$part=0;
                   9559: 			    } else {
                   9560: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9561: 			    }
1.339     albertel 9562: 			    if ($subp eq 'display') {
                   9563: 				$value.=' [Part: '.$part.']';
                   9564: 			    }
1.599     albertel 9565: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9566: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9567: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9568: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9569: 			    }
1.599     albertel 9570: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9571: 				$metaentry{':'.$unikey}=
                   9572: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9573: 			    }
1.339     albertel 9574: 			}
                   9575: 		    }
                   9576: 		} else {
1.172     www      9577: #
                   9578: # This is not a package - some other kind of start tag
1.339     albertel 9579: #
                   9580: 		    my $entry=$token->[1];
1.1068    www      9581: 		    my $unikey='';
1.175     www      9582: 
1.339     albertel 9583: 		    if ($entry eq 'import') {
1.175     www      9584: #
                   9585: # Importing a library here
1.339     albertel 9586: #
1.1067    www      9587:                         my $location=$parser->get_text('/import');
                   9588:                         my $dir=$filename;
                   9589:                         $dir=~s|[^/]*$||;
                   9590:                         $location=&filelocation($dir,$location);
1.1069    www      9591:                        
1.1068    www      9592:                         my $importmode=$token->[2]->{'importmode'};
                   9593:                         if ($importmode eq 'problem') {
1.1069    www      9594: # Import as problem/response
1.1068    www      9595:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9596:                         } elsif ($importmode eq 'part') {
                   9597: # Import as part(s)
1.1069    www      9598:                            $importedparts=1;
                   9599: # We need to get the original file and the imported file to get the part order correct
                   9600: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   9601: # Load and inspect original file
1.1070    www      9602:                            if ($#origfileimportpartids<0) {
                   9603:                               undef(%importedpartids);
                   9604:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   9605:                               my $origfile=&getfile($origfilelocation);
                   9606:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9607:                            }
                   9608: 
1.1069    www      9609: # Load and inspect imported file
                   9610:                            my $impfile=&getfile($location);
                   9611:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9612:                            if ($#impfilepartids>=0) {
                   9613: # This problem had parts
1.1070    www      9614:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      9615:                            } else {
                   9616: # Importing by turning a single problem into a problem part
                   9617: # It gets the import-tags ID as part-ID
                   9618:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      9619:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      9620:                            }
1.1068    www      9621:                         } else {
                   9622: # Normal import
                   9623:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9624:                            if (defined($token->[2]->{'id'})) {
                   9625:                               $unikey.='_'.$token->[2]->{'id'};
                   9626:                            }
1.1067    www      9627:                         }
                   9628: 
1.339     albertel 9629: 			if ($depthcount<20) {
1.736     albertel 9630: 			    my $metadata = 
                   9631: 				&metadata($uri,'keys', $location,$unikey,
                   9632: 					  $depthcount+1);
                   9633: 			    foreach my $meta (split(',',$metadata)) {
                   9634: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   9635: 				$metathesekeys{$meta}=1;
1.339     albertel 9636: 			    }
1.1068    www      9637: 			
                   9638:                         }
1.1067    www      9639: 		    } else {
                   9640: #
                   9641: # Not importing, some other kind of non-package, non-library start tag
                   9642: # 
                   9643:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9644:                         if (defined($token->[2]->{'id'})) {
                   9645:                             $unikey.='_'.$token->[2]->{'id'};
                   9646:                         }
1.339     albertel 9647: 			if (defined($token->[2]->{'name'})) { 
                   9648: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   9649: 			}
                   9650: 			$metathesekeys{$unikey}=1;
1.736     albertel 9651: 			foreach my $param (@{$token->[3]}) {
                   9652: 			    $metaentry{':'.$unikey.'.'.$param} =
                   9653: 				$token->[2]->{$param};
1.339     albertel 9654: 			}
                   9655: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 9656: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 9657: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   9658: 		 # only ws inside the tag, and not in default, so use default
                   9659: 		 # as value
1.599     albertel 9660: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 9661: 			} elsif ( $internaltext =~ /\S/ ) {
                   9662: 		  # something interesting inside the tag
                   9663: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 9664: 			} else {
1.908     albertel 9665: 		  # no interesting values, don't set a default
1.339     albertel 9666: 			}
1.172     www      9667: # end of not-a-package not-a-library import
1.339     albertel 9668: 		    }
1.172     www      9669: # end of not-a-package start tag
1.339     albertel 9670: 		}
1.172     www      9671: # the next is the end of "start tag"
1.339     albertel 9672: 	    }
                   9673: 	}
1.483     albertel 9674: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 9675: 	$extension = lc($extension);
                   9676: 	if ($extension eq 'htm') { $extension='html'; }
                   9677: 
1.737     albertel 9678: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 9679: 	    #no specific packages #how's our extension
                   9680: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 9681: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 9682: 					 \%metathesekeys);
                   9683: 	}
1.883     albertel 9684: 
                   9685: 	if (!exists($metaentry{':packages'})
                   9686: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 9687: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 9688: 		#no specific packages well let's get default then
                   9689: 		if ($key!~/^default&/) { next; }
1.488     albertel 9690: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 9691: 					     \%metathesekeys);
                   9692: 	    }
                   9693: 	}
1.338     www      9694: # are there custom rights to evaluate
1.599     albertel 9695: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 9696: 
1.338     www      9697:     #
                   9698:     # Importing a rights file here
1.339     albertel 9699:     #
                   9700: 	    unless ($depthcount) {
1.599     albertel 9701: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 9702: 		my $dir=$filename;
                   9703: 		$dir=~s|[^/]*$||;
                   9704: 		$location=&filelocation($dir,$location);
1.736     albertel 9705: 		my $rights_metadata =
                   9706: 		    &metadata($uri,'keys',$location,'_rights',
                   9707: 			      $depthcount+1);
                   9708: 		foreach my $rights (split(',',$rights_metadata)) {
                   9709: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   9710: 		    $metathesekeys{$rights}=1;
1.339     albertel 9711: 		}
                   9712: 	    }
                   9713: 	}
1.737     albertel 9714: 	# uniqifiy package listing
                   9715: 	my %seen;
                   9716: 	my @uniq_packages =
                   9717: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   9718: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   9719: 
1.1070    www      9720:         if ($importedparts) {
                   9721: # We had imported parts and need to rebuild partorder
                   9722:            $metaentry{':partorder'}='';
                   9723:            $metathesekeys{'partorder'}=1;
                   9724:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   9725:                if ($origfileimportpartids[$index] eq 'part') {
                   9726: # original part, part of the problem
                   9727:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   9728:                } else {
                   9729: # we have imported parts at this position
                   9730:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   9731:                }
                   9732:            }
                   9733:            $metaentry{':partorder'}=~s/^\,//;
                   9734:         }
                   9735: 
1.737     albertel 9736: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 9737: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   9738: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 9739: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      9740: # this is the end of "was not already recently cached
1.71      www      9741:     }
1.599     albertel 9742:     return $metaentry{':'.$what};
1.261     albertel 9743: }
                   9744: 
1.488     albertel 9745: sub metadata_create_package_def {
1.483     albertel 9746:     my ($uri,$key,$package,$metathesekeys)=@_;
                   9747:     my ($pack,$name,$subp)=split(/\&/,$key);
                   9748:     if ($subp eq 'default') { next; }
                   9749:     
1.599     albertel 9750:     if (defined($metaentry{':packages'})) {
                   9751: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 9752:     } else {
1.599     albertel 9753: 	$metaentry{':packages'}=$package;
1.483     albertel 9754:     }
                   9755:     my $value=$packagetab{$key};
                   9756:     my $unikey;
                   9757:     $unikey='parameter_0_'.$name;
1.599     albertel 9758:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 9759:     $$metathesekeys{$unikey}=1;
1.599     albertel 9760:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9761: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 9762:     }
1.599     albertel 9763:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   9764: 	$metaentry{':'.$unikey}=
                   9765: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 9766:     }
                   9767: }
                   9768: 
1.261     albertel 9769: sub metadata_generate_part0 {
                   9770:     my ($metadata,$metacache,$uri) = @_;
                   9771:     my %allnames;
1.737     albertel 9772:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 9773: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 9774: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   9775: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 9776: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 9777: 	    $allnames{$name}=$part;
                   9778: 	  }
                   9779: 	}
                   9780:     }
                   9781:     foreach my $name (keys(%allnames)) {
                   9782:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 9783:       my $key=":parameter_0_$name";
1.261     albertel 9784:       $$metacache{"$key.part"}='0';
                   9785:       $$metacache{"$key.name"}=$name;
1.428     albertel 9786:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 9787: 					   $allnames{$name}.'_'.$name.
                   9788: 					   '.type'};
1.428     albertel 9789:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9790: 			     '.display'};
1.644     www      9791:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9792:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9793:       $$metacache{"$key.display"}=$olddis;
                   9794:     }
1.71      www      9795: }
                   9796: 
1.764     albertel 9797: # ------------------------------------------------------ Devalidate title cache
                   9798: 
                   9799: sub devalidate_title_cache {
                   9800:     my ($url)=@_;
                   9801:     if (!$env{'request.course.id'}) { return; }
                   9802:     my $symb=&symbread($url);
                   9803:     if (!$symb) { return; }
                   9804:     my $key=$env{'request.course.id'}."\0".$symb;
                   9805:     &devalidate_cache_new('title',$key);
                   9806: }
                   9807: 
1.1014    droeschl 9808: # ------------------------------------------------- Get the title of a course
                   9809: 
                   9810: sub current_course_title {
                   9811:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   9812: }
1.301     www      9813: # ------------------------------------------------- Get the title of a resource
                   9814: 
                   9815: sub gettitle {
                   9816:     my $urlsymb=shift;
                   9817:     my $symb=&symbread($urlsymb);
1.534     albertel 9818:     if ($symb) {
1.620     albertel 9819: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 9820: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 9821: 	if (defined($cached)) { 
                   9822: 	    return $result;
                   9823: 	}
1.534     albertel 9824: 	my ($map,$resid,$url)=&decode_symb($symb);
                   9825: 	my $title='';
1.907     albertel 9826: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   9827: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   9828: 	} else {
                   9829: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9830: 		    &GDBM_READER(),0640)) {
                   9831: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   9832: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   9833: 		untie(%bighash);
                   9834: 	    }
1.534     albertel 9835: 	}
                   9836: 	$title=~s/\&colon\;/\:/gs;
                   9837: 	if ($title) {
1.1159    www      9838: # Remember both $symb and $title for dynamic metadata
                   9839:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      9840:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      9841: # Cache this title and then return it
1.599     albertel 9842: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 9843: 	}
                   9844: 	$urlsymb=$url;
                   9845:     }
                   9846:     my $title=&metadata($urlsymb,'title');
                   9847:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   9848:     return $title;
1.301     www      9849: }
1.613     albertel 9850: 
1.614     albertel 9851: sub get_slot {
                   9852:     my ($which,$cnum,$cdom)=@_;
                   9853:     if (!$cnum || !$cdom) {
1.790     albertel 9854: 	(undef,my $courseid)=&whichuser();
1.620     albertel 9855: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9856: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9857:     }
1.703     albertel 9858:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9859:     my %slotinfo;
                   9860:     if (exists($remembered{$key})) {
                   9861: 	$slotinfo{$which} = $remembered{$key};
                   9862:     } else {
                   9863: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9864: 	&Apache::lonhomework::showhash(%slotinfo);
                   9865: 	my ($tmp)=keys(%slotinfo);
                   9866: 	if ($tmp=~/^error:/) { return (); }
                   9867: 	$remembered{$key} = $slotinfo{$which};
                   9868:     }
1.616     albertel 9869:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9870: 	return %{$slotinfo{$which}};
                   9871:     }
                   9872:     return $slotinfo{$which};
1.614     albertel 9873: }
1.1150    raeburn  9874: 
                   9875: sub get_reservable_slots {
                   9876:     my ($cnum,$cdom,$uname,$udom) = @_;
                   9877:     my $now = time;
                   9878:     my $reservable_info;
                   9879:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   9880:     if (exists($remembered{$key})) {
                   9881:         $reservable_info = $remembered{$key};
                   9882:     } else {
                   9883:         my %resv;
                   9884:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   9885:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   9886:         $reservable_info = \%resv;
                   9887:         $remembered{$key} = $reservable_info;
                   9888:     }
                   9889:     return $reservable_info;
                   9890: }
                   9891: 
                   9892: sub get_course_slots {
                   9893:     my ($cnum,$cdom) = @_;
                   9894:     my $hashid=$cnum.':'.$cdom;
                   9895:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   9896:     if (defined($cached)) {
                   9897:         if (ref($result) eq 'HASH') {
                   9898:             return %{$result};
                   9899:         }
                   9900:     } else {
                   9901:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   9902:         my ($tmp) = keys(%slots);
                   9903:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9904:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   9905:             return %slots;
                   9906:         }
                   9907:     }
                   9908:     return;
                   9909: }
                   9910: 
                   9911: sub devalidate_slots_cache {
                   9912:     my ($cnum,$cdom)=@_;
                   9913:     my $hashid=$cnum.':'.$cdom;
                   9914:     &devalidate_cache_new('allslots',$hashid);
                   9915: }
                   9916: 
1.1172.2.8  raeburn  9917: sub get_coursechange {
                   9918:     my ($cdom,$cnum) = @_;
                   9919:     if ($cdom eq '' || $cnum eq '') {
                   9920:         return unless ($env{'request.course.id'});
                   9921:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9922:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9923:     }
                   9924:     my $hashid=$cdom.'_'.$cnum;
                   9925:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   9926:     if ((defined($cached)) && ($change ne '')) {
                   9927:         return $change;
                   9928:     } else {
                   9929:         my %crshash;
                   9930:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   9931:         if ($crshash{'internal.contentchange'} eq '') {
                   9932:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   9933:             if ($change eq '') {
                   9934:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   9935:                 $change = $crshash{'internal.created'};
                   9936:             }
                   9937:         } else {
                   9938:             $change = $crshash{'internal.contentchange'};
                   9939:         }
                   9940:         my $cachetime = 600;
                   9941:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   9942:     }
                   9943:     return $change;
                   9944: }
                   9945: 
                   9946: sub devalidate_coursechange_cache {
                   9947:     my ($cnum,$cdom)=@_;
                   9948:     my $hashid=$cnum.':'.$cdom;
                   9949:     &devalidate_cache_new('crschange',$hashid);
                   9950: }
                   9951: 
1.31      www      9952: # ------------------------------------------------- Update symbolic store links
                   9953: 
                   9954: sub symblist {
                   9955:     my ($mapname,%newhash)=@_;
1.438     www      9956:     $mapname=&deversion(&declutter($mapname));
1.31      www      9957:     my %hash;
1.620     albertel 9958:     if (($env{'request.course.fn'}) && (%newhash)) {
                   9959:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9960:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  9961: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 9962: 		next if ($url eq 'last_known'
                   9963: 			 && $env{'form.no_update_last_known'});
                   9964: 		$hash{declutter($url)}=&encode_symb($mapname,
                   9965: 						    $newhash{$url}->[1],
                   9966: 						    $newhash{$url}->[0]);
1.191     harris41 9967:             }
1.31      www      9968:             if (untie(%hash)) {
                   9969: 		return 'ok';
                   9970:             }
                   9971:         }
                   9972:     }
                   9973:     return 'error';
1.212     www      9974: }
                   9975: 
                   9976: # --------------------------------------------------------------- Verify a symb
                   9977: 
                   9978: sub symbverify {
1.510     www      9979:     my ($symb,$thisurl)=@_;
                   9980:     my $thisfn=$thisurl;
1.439     www      9981:     $thisfn=&declutter($thisfn);
1.215     www      9982: # direct jump to resource in page or to a sequence - will construct own symbs
                   9983:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9984: # check URL part
1.409     www      9985:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9986: 
1.431     www      9987:     unless ($url eq $thisfn) { return 0; }
1.213     www      9988: 
1.216     www      9989:     $symb=&symbclean($symb);
1.510     www      9990:     $thisurl=&deversion($thisurl);
1.439     www      9991:     $thisfn=&deversion($thisfn);
1.213     www      9992: 
                   9993:     my %bighash;
                   9994:     my $okay=0;
1.431     www      9995: 
1.620     albertel 9996:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9997:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9998:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9999:             $thisurl =~ s/\?.+$//;
                   10000:         }
1.510     www      10001:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  10002:         unless ($ids) {
                   10003:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   10004:             $ids=$bighash{$idkey};
1.216     www      10005:         }
                   10006:         if ($ids) {
                   10007: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 10008: 	    foreach my $id (split(/\,/,$ids)) {
                   10009: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  10010:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   10011:                    $symb =~ s/\?.+$//;
                   10012:                }
1.216     www      10013:                if (
                   10014:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   10015:    eq $symb) { 
1.620     albertel 10016: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  10017: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   10018:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 10019: 		       $okay=1; 
                   10020: 		   }
                   10021: 	       }
1.216     www      10022: 	   }
                   10023:         }
1.213     www      10024: 	untie(%bighash);
                   10025:     }
                   10026:     return $okay;
1.31      www      10027: }
                   10028: 
1.210     www      10029: # --------------------------------------------------------------- Clean-up symb
                   10030: 
                   10031: sub symbclean {
                   10032:     my $symb=shift;
1.568     albertel 10033:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      10034: # remove version from map
                   10035:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      10036: 
1.210     www      10037: # remove version from URL
                   10038:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      10039: 
1.507     www      10040: # remove wrapper
                   10041: 
1.510     www      10042:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 10043:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      10044:     return $symb;
1.409     www      10045: }
                   10046: 
                   10047: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 10048: 
                   10049: sub encode_symb {
                   10050:     my ($map,$resid,$url)=@_;
                   10051:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   10052: }
1.409     www      10053: 
                   10054: sub decode_symb {
1.568     albertel 10055:     my $symb=shift;
                   10056:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   10057:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      10058:     return (&fixversion($map),$resid,&fixversion($url));
                   10059: }
                   10060: 
                   10061: sub fixversion {
                   10062:     my $fn=shift;
1.609     banghart 10063:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10064:     my %bighash;
                   10065:     my $uri=&clutter($fn);
1.620     albertel 10066:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10067: # is this cached?
1.599     albertel 10068:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10069:     if (defined($cached)) { return $result; }
                   10070: # unfortunately not cached, or expired
1.620     albertel 10071:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10072: 	    &GDBM_READER(),0640)) {
                   10073:  	if ($bighash{'version_'.$uri}) {
                   10074:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10075:  	    unless (($version eq 'mostrecent') || 
                   10076: 		    ($version==&getversion($uri))) {
1.440     www      10077:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10078:  	    }
                   10079:  	}
                   10080:  	untie %bighash;
1.413     www      10081:     }
1.599     albertel 10082:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10083: }
                   10084: 
                   10085: sub deversion {
                   10086:     my $url=shift;
                   10087:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10088:     return $url;
1.210     www      10089: }
                   10090: 
1.31      www      10091: # ------------------------------------------------------ Return symb list entry
                   10092: 
                   10093: sub symbread {
1.249     www      10094:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 10095:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.8  raeburn  10096:     if (defined($env{$cache_str})) {
                   10097:         if (($thisfn) || ($env{$cache_str} ne '')) {
                   10098:             return $env{$cache_str};
                   10099:         }
                   10100:     }
1.242     www      10101: # no filename provided? try from environment
1.44      www      10102:     unless ($thisfn) {
1.620     albertel 10103:         if ($env{'request.symb'}) {
                   10104: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 10105: 	}
1.620     albertel 10106: 	$thisfn=$env{'request.filename'};
1.44      www      10107:     }
1.569     albertel 10108:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10109: # is that filename actually a symb? Verify, clean, and return
                   10110:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10111: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10112: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10113: 	}
1.242     www      10114:     }
1.44      www      10115:     $thisfn=declutter($thisfn);
1.31      www      10116:     my %hash;
1.37      www      10117:     my %bighash;
                   10118:     my $syval='';
1.620     albertel 10119:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10120:         my $targetfn = $thisfn;
1.609     banghart 10121:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10122:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10123:         }
1.687     albertel 10124: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10125: 	    $targetfn=$1;
                   10126: 	}
1.620     albertel 10127:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10128:                       &GDBM_READER(),0640)) {
1.481     raeburn  10129: 	    $syval=$hash{$targetfn};
1.37      www      10130:             untie(%hash);
                   10131:         }
                   10132: # ---------------------------------------------------------- There was an entry
                   10133:         if ($syval) {
1.601     albertel 10134: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10135: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10136: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10137: 		    #return $env{$cache_str}='';
1.601     albertel 10138: 		#}    
                   10139: 		#$syval.=$1;
                   10140: 	    #}
1.37      www      10141:         } else {
                   10142: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10143:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10144:                             &GDBM_READER(),0640)) {
1.37      www      10145: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10146:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10147:               unless ($ids) { 
                   10148:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10149:               }
                   10150:               unless ($ids) {
                   10151: # alias?
                   10152: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10153:               }
1.37      www      10154:               if ($ids) {
                   10155: # ------------------------------------------------------------------- Has ID(s)
                   10156:                  my @possibilities=split(/\,/,$ids);
1.39      www      10157:                  if ($#possibilities==0) {
                   10158: # ----------------------------------------------- There is only one possibility
1.37      www      10159: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10160: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10161: 						    $resid,$thisfn);
1.249     www      10162:                  } elsif (!$donotrecurse) {
1.39      www      10163: # ------------------------------------------ There is more than one possibility
                   10164:                      my $realpossible=0;
1.800     albertel 10165:                      foreach my $id (@possibilities) {
                   10166: 			 my $file=$bighash{'src_'.$id};
1.39      www      10167:                          if (&allowed('bre',$file)) {
1.800     albertel 10168:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10169:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10170: 				$realpossible++;
1.626     albertel 10171:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10172: 						    $resid,$thisfn);
1.39      www      10173:                             }
                   10174: 			 }
1.191     harris41 10175:                      }
1.39      www      10176: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10177:                  } else {
                   10178:                      $syval='';
1.37      www      10179:                  }
                   10180: 	      }
                   10181:               untie(%bighash)
1.481     raeburn  10182:            }
1.31      www      10183:         }
1.62      www      10184:         if ($syval) {
1.620     albertel 10185: 	    return $env{$cache_str}=$syval;
1.62      www      10186:         }
1.31      www      10187:     }
1.949     raeburn  10188:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10189:     return $env{$cache_str}='';
1.31      www      10190: }
                   10191: 
                   10192: # ---------------------------------------------------------- Return random seed
                   10193: 
1.32      www      10194: sub numval {
                   10195:     my $txt=shift;
                   10196:     $txt=~tr/A-J/0-9/;
                   10197:     $txt=~tr/a-j/0-9/;
                   10198:     $txt=~tr/K-T/0-9/;
                   10199:     $txt=~tr/k-t/0-9/;
                   10200:     $txt=~tr/U-Z/0-5/;
                   10201:     $txt=~tr/u-z/0-5/;
                   10202:     $txt=~s/\D//g;
1.564     albertel 10203:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10204:     return int($txt);
1.368     albertel 10205: }
                   10206: 
1.484     albertel 10207: sub numval2 {
                   10208:     my $txt=shift;
                   10209:     $txt=~tr/A-J/0-9/;
                   10210:     $txt=~tr/a-j/0-9/;
                   10211:     $txt=~tr/K-T/0-9/;
                   10212:     $txt=~tr/k-t/0-9/;
                   10213:     $txt=~tr/U-Z/0-5/;
                   10214:     $txt=~tr/u-z/0-5/;
                   10215:     $txt=~s/\D//g;
                   10216:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10217:     my $total;
                   10218:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10219:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10220:     return int($total);
                   10221: }
                   10222: 
1.575     albertel 10223: sub numval3 {
                   10224:     use integer;
                   10225:     my $txt=shift;
                   10226:     $txt=~tr/A-J/0-9/;
                   10227:     $txt=~tr/a-j/0-9/;
                   10228:     $txt=~tr/K-T/0-9/;
                   10229:     $txt=~tr/k-t/0-9/;
                   10230:     $txt=~tr/U-Z/0-5/;
                   10231:     $txt=~tr/u-z/0-5/;
                   10232:     $txt=~s/\D//g;
                   10233:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10234:     my $total;
                   10235:     foreach my $val (@txts) { $total+=$val; }
                   10236:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10237:     return $total;
                   10238: }
                   10239: 
1.675     albertel 10240: sub digest {
                   10241:     my ($data)=@_;
                   10242:     my $digest=&Digest::MD5::md5($data);
                   10243:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10244:     my ($e,$f);
                   10245:     {
                   10246:         use integer;
                   10247:         $e=($a+$b);
                   10248:         $f=($c+$d);
                   10249:         if ($_64bit) {
                   10250:             $e=(($e<<32)>>32);
                   10251:             $f=(($f<<32)>>32);
                   10252:         }
                   10253:     }
                   10254:     if (wantarray) {
                   10255: 	return ($e,$f);
                   10256:     } else {
                   10257: 	my $g;
                   10258: 	{
                   10259: 	    use integer;
                   10260: 	    $g=($e+$f);
                   10261: 	    if ($_64bit) {
                   10262: 		$g=(($g<<32)>>32);
                   10263: 	    }
                   10264: 	}
                   10265: 	return $g;
                   10266:     }
                   10267: }
                   10268: 
1.368     albertel 10269: sub latest_rnd_algorithm_id {
1.675     albertel 10270:     return '64bit5';
1.366     albertel 10271: }
1.32      www      10272: 
1.503     albertel 10273: sub get_rand_alg {
                   10274:     my ($courseid)=@_;
1.790     albertel 10275:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10276:     if ($courseid) {
1.620     albertel 10277: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10278:     }
                   10279:     return &latest_rnd_algorithm_id();
                   10280: }
                   10281: 
1.562     albertel 10282: sub validCODE {
                   10283:     my ($CODE)=@_;
                   10284:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10285:     return 0;
                   10286: }
                   10287: 
1.491     albertel 10288: sub getCODE {
1.620     albertel 10289:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10290:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10291: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10292: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10293: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10294:     }
                   10295:     return undef;
                   10296: }
1.1133    foxr     10297: #
                   10298: #  Determines the random seed for a specific context:
                   10299: #
                   10300: # parameters:
                   10301: #   symb      - in course context the symb for the seed.
                   10302: #   course_id - The course id of the form domain_coursenum.
                   10303: #   domain    - Domain for the user.
                   10304: #   course    - Course for the user.
                   10305: #   cenv      - environment of the course.
                   10306: #
                   10307: # NOTE:
                   10308: #   All parameters are picked out of the environment if missing
                   10309: #   or not defined.
                   10310: #   If a symb cannot be determined the current time is used instead.
                   10311: #
                   10312: #  For a given well defined symb, courside, domain, username,
                   10313: #  and course environment, the seed is reproducible.
                   10314: #
1.31      www      10315: sub rndseed {
1.1133    foxr     10316:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10317:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10318:     if (!defined($symb)) {
1.366     albertel 10319: 	unless ($symb=$wsymb) { return time; }
                   10320:     }
1.1146    foxr     10321:     if (!defined $courseid) { 
                   10322: 	$courseid=$wcourseid; 
                   10323:     }
                   10324:     if (!defined $domain) { $domain=$wdomain; }
                   10325:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10326: 
                   10327:     my $which;
                   10328:     if (defined($cenv->{'rndseed'})) {
                   10329: 	$which = $cenv->{'rndseed'};
                   10330:     } else {
                   10331: 	$which =&get_rand_alg($courseid);
                   10332:     }
1.491     albertel 10333:     if (defined(&getCODE())) {
1.1133    foxr     10334: 
1.675     albertel 10335: 	if ($which eq '64bit5') {
                   10336: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10337: 	} elsif ($which eq '64bit4') {
1.575     albertel 10338: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10339: 	} else {
                   10340: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10341: 	}
1.675     albertel 10342:     } elsif ($which eq '64bit5') {
                   10343: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10344:     } elsif ($which eq '64bit4') {
                   10345: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10346:     } elsif ($which eq '64bit3') {
                   10347: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10348:     } elsif ($which eq '64bit2') {
                   10349: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10350:     } elsif ($which eq '64bit') {
                   10351: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10352:     }
                   10353:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10354: }
                   10355: 
                   10356: sub rndseed_32bit {
                   10357:     my ($symb,$courseid,$domain,$username)=@_;
                   10358:     {
                   10359: 	use integer;
                   10360: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10361: 	my $symbseed=numval($symb) << 22;
                   10362: 	my $namechck=unpack("%32C*",$username) << 17;
                   10363: 	my $nameseed=numval($username) << 12;
                   10364: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10365: 	my $courseseed=unpack("%32C*",$courseid);
                   10366: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10367: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10368: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10369: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10370: 	return $num;
                   10371:     }
                   10372: }
                   10373: 
                   10374: sub rndseed_64bit {
                   10375:     my ($symb,$courseid,$domain,$username)=@_;
                   10376:     {
                   10377: 	use integer;
                   10378: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10379: 	my $symbseed=numval($symb) << 10;
                   10380: 	my $namechck=unpack("%32S*",$username);
                   10381: 	
                   10382: 	my $nameseed=numval($username) << 21;
                   10383: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10384: 	my $courseseed=unpack("%32S*",$courseid);
                   10385: 	
                   10386: 	my $num1=$symbchck+$symbseed+$namechck;
                   10387: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10388: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10389: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10390: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10391: 	return "$num1,$num2";
1.155     albertel 10392:     }
1.366     albertel 10393: }
                   10394: 
1.443     albertel 10395: sub rndseed_64bit2 {
                   10396:     my ($symb,$courseid,$domain,$username)=@_;
                   10397:     {
                   10398: 	use integer;
                   10399: 	# strings need to be an even # of cahracters long, it it is odd the
                   10400:         # last characters gets thrown away
                   10401: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10402: 	my $symbseed=numval($symb) << 10;
                   10403: 	my $namechck=unpack("%32S*",$username.' ');
                   10404: 	
                   10405: 	my $nameseed=numval($username) << 21;
1.501     albertel 10406: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10407: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10408: 	
                   10409: 	my $num1=$symbchck+$symbseed+$namechck;
                   10410: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10411: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10412: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10413: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10414: 	return "$num1,$num2";
                   10415:     }
                   10416: }
                   10417: 
                   10418: sub rndseed_64bit3 {
                   10419:     my ($symb,$courseid,$domain,$username)=@_;
                   10420:     {
                   10421: 	use integer;
                   10422: 	# strings need to be an even # of cahracters long, it it is odd the
                   10423:         # last characters gets thrown away
                   10424: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10425: 	my $symbseed=numval2($symb) << 10;
                   10426: 	my $namechck=unpack("%32S*",$username.' ');
                   10427: 	
                   10428: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10429: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10430: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10431: 	
                   10432: 	my $num1=$symbchck+$symbseed+$namechck;
                   10433: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10434: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10435: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10436: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10437: 	
1.503     albertel 10438: 	return "$num1:$num2";
1.443     albertel 10439:     }
                   10440: }
                   10441: 
1.575     albertel 10442: sub rndseed_64bit4 {
                   10443:     my ($symb,$courseid,$domain,$username)=@_;
                   10444:     {
                   10445: 	use integer;
                   10446: 	# strings need to be an even # of cahracters long, it it is odd the
                   10447:         # last characters gets thrown away
                   10448: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10449: 	my $symbseed=numval3($symb) << 10;
                   10450: 	my $namechck=unpack("%32S*",$username.' ');
                   10451: 	
                   10452: 	my $nameseed=numval3($username) << 21;
                   10453: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10454: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10455: 	
                   10456: 	my $num1=$symbchck+$symbseed+$namechck;
                   10457: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10458: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10459: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10460: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10461: 	
1.575     albertel 10462: 	return "$num1:$num2";
                   10463:     }
                   10464: }
                   10465: 
1.675     albertel 10466: sub rndseed_64bit5 {
                   10467:     my ($symb,$courseid,$domain,$username)=@_;
                   10468:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   10469:     return "$num1:$num2";
                   10470: }
                   10471: 
1.366     albertel 10472: sub rndseed_CODE_64bit {
                   10473:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 10474:     {
1.366     albertel 10475: 	use integer;
1.443     albertel 10476: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 10477: 	my $symbseed=numval2($symb);
1.491     albertel 10478: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10479: 	my $CODEseed=numval(&getCODE());
1.443     albertel 10480: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 10481: 	my $num1=$symbseed+$CODEchck;
                   10482: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10483: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10484: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 10485: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10486: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 10487: 	return "$num1:$num2";
1.366     albertel 10488:     }
                   10489: }
                   10490: 
1.575     albertel 10491: sub rndseed_CODE_64bit4 {
                   10492:     my ($symb,$courseid,$domain,$username)=@_;
                   10493:     {
                   10494: 	use integer;
                   10495: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   10496: 	my $symbseed=numval3($symb);
                   10497: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10498: 	my $CODEseed=numval3(&getCODE());
                   10499: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10500: 	my $num1=$symbseed+$CODEchck;
                   10501: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10502: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10503: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 10504: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10505: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   10506: 	return "$num1:$num2";
                   10507:     }
                   10508: }
                   10509: 
1.675     albertel 10510: sub rndseed_CODE_64bit5 {
                   10511:     my ($symb,$courseid,$domain,$username)=@_;
                   10512:     my $code = &getCODE();
                   10513:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   10514:     return "$num1:$num2";
                   10515: }
                   10516: 
1.366     albertel 10517: sub setup_random_from_rndseed {
                   10518:     my ($rndseed)=@_;
1.503     albertel 10519:     if ($rndseed =~/([,:])/) {
                   10520: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 10521: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   10522:     } else {
                   10523: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 10524:     }
1.36      albertel 10525: }
                   10526: 
1.474     albertel 10527: sub latest_receipt_algorithm_id {
1.835     albertel 10528:     return 'receipt3';
1.474     albertel 10529: }
                   10530: 
1.480     www      10531: sub recunique {
                   10532:     my $fucourseid=shift;
                   10533:     my $unique;
1.835     albertel 10534:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   10535: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10536: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      10537:     } else {
                   10538: 	$unique=$perlvar{'lonReceipt'};
                   10539:     }
                   10540:     return unpack("%32C*",$unique);
                   10541: }
                   10542: 
                   10543: sub recprefix {
                   10544:     my $fucourseid=shift;
                   10545:     my $prefix;
1.835     albertel 10546:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   10547: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10548: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      10549:     } else {
                   10550: 	$prefix=$perlvar{'lonHostID'};
                   10551:     }
                   10552:     return unpack("%32C*",$prefix);
                   10553: }
                   10554: 
1.76      www      10555: sub ireceipt {
1.474     albertel 10556:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 10557: 
                   10558:     my $return =&recprefix($fucourseid).'-';
                   10559: 
                   10560:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   10561: 	$env{'request.state'} eq 'construct') {
                   10562: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   10563: 	return $return;
                   10564:     }
                   10565: 
1.76      www      10566:     my $cuname=unpack("%32C*",$funame);
                   10567:     my $cudom=unpack("%32C*",$fudom);
                   10568:     my $cucourseid=unpack("%32C*",$fucourseid);
                   10569:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      10570:     my $cunique=&recunique($fucourseid);
1.474     albertel 10571:     my $cpart=unpack("%32S*",$part);
1.835     albertel 10572:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   10573: 
1.790     albertel 10574: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 10575: 			       
                   10576: 	$return.= ($cunique%$cuname+
                   10577: 		   $cunique%$cudom+
                   10578: 		   $cusymb%$cuname+
                   10579: 		   $cusymb%$cudom+
                   10580: 		   $cucourseid%$cuname+
                   10581: 		   $cucourseid%$cudom+
                   10582: 		   $cpart%$cuname+
                   10583: 		   $cpart%$cudom);
                   10584:     } else {
                   10585: 	$return.= ($cunique%$cuname+
                   10586: 		   $cunique%$cudom+
                   10587: 		   $cusymb%$cuname+
                   10588: 		   $cusymb%$cudom+
                   10589: 		   $cucourseid%$cuname+
                   10590: 		   $cucourseid%$cudom);
                   10591:     }
                   10592:     return $return;
1.76      www      10593: }
                   10594: 
                   10595: sub receipt {
1.474     albertel 10596:     my ($part)=@_;
1.790     albertel 10597:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 10598:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      10599: }
1.260     ng       10600: 
1.790     albertel 10601: sub whichuser {
                   10602:     my ($passedsymb)=@_;
                   10603:     my ($symb,$courseid,$domain,$name,$publicuser);
                   10604:     if (defined($env{'form.grade_symb'})) {
                   10605: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   10606: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   10607: 	if (!$allowed &&
                   10608: 	    exists($env{'request.course.sec'}) &&
                   10609: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   10610: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   10611: 			      '/'.$env{'request.course.sec'});
                   10612: 	}
                   10613: 	if ($allowed) {
                   10614: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   10615: 	    $courseid=$tmp_courseid;
                   10616: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   10617: 	    ($name)=&get_env_multiple('form.grade_username');
                   10618: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   10619: 	}
                   10620:     }
                   10621:     if (!$passedsymb) {
                   10622: 	$symb=&symbread();
                   10623:     } else {
                   10624: 	$symb=$passedsymb;
                   10625:     }
                   10626:     $courseid=$env{'request.course.id'};
                   10627:     $domain=$env{'user.domain'};
                   10628:     $name=$env{'user.name'};
                   10629:     if ($name eq 'public' && $domain eq 'public') {
                   10630: 	if (!defined($env{'form.username'})) {
                   10631: 	    $env{'form.username'}.=time.rand(10000000);
                   10632: 	}
                   10633: 	$name.=$env{'form.username'};
                   10634:     }
                   10635:     return ($symb,$courseid,$domain,$name,$publicuser);
                   10636: 
                   10637: }
                   10638: 
1.36      albertel 10639: # ------------------------------------------------------------ Serves up a file
1.472     albertel 10640: # returns either the contents of the file or 
                   10641: # -1 if the file doesn't exist
1.481     raeburn  10642: #
                   10643: # if the target is a file that was uploaded via DOCS, 
                   10644: # a check will be made to see if a current copy exists on the local server,
                   10645: # if it does this will be served, otherwise a copy will be retrieved from
                   10646: # the home server for the course and stored in /home/httpd/html/userfiles on
                   10647: # the local server.   
1.472     albertel 10648: 
1.36      albertel 10649: sub getfile {
1.538     albertel 10650:     my ($file) = @_;
1.609     banghart 10651:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 10652:     &repcopy($file);
                   10653:     return &readfile($file);
                   10654: }
                   10655: 
                   10656: sub repcopy_userfile {
                   10657:     my ($file)=@_;
1.1142    raeburn  10658:     my $londocroot = $perlvar{'lonDocRoot'};
                   10659:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  10660:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 10661:     my ($cdom,$cnum,$filename) = 
1.811     albertel 10662: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 10663:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   10664:     if (-e "$file") {
1.828     www      10665: # we already have a local copy, check it out
1.538     albertel 10666: 	my @fileinfo = stat($file);
1.828     www      10667: 	my $rtncode;
                   10668: 	my $info;
1.538     albertel 10669: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 10670: 	if ($lwpresp ne 'ok') {
1.828     www      10671: # there is no such file anymore, even though we had a local copy
1.482     albertel 10672: 	    if ($rtncode eq '404') {
1.538     albertel 10673: 		unlink($file);
1.482     albertel 10674: 	    }
                   10675: 	    return -1;
                   10676: 	}
                   10677: 	if ($info < $fileinfo[9]) {
1.828     www      10678: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  10679: 	    return 'ok';
1.828     www      10680: 	} else {
                   10681: # the file is outdated, get rid of it
                   10682: 	    unlink($file);
1.482     albertel 10683: 	}
1.828     www      10684:     }
                   10685: # one way or the other, at this point, we don't have the file
                   10686: # construct the correct path for the file
                   10687:     my @parts = ($cdom,$cnum); 
                   10688:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   10689: 	push @parts, split(/\//,$1);
                   10690:     }
                   10691:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   10692:     foreach my $part (@parts) {
                   10693: 	$path .= '/'.$part;
                   10694: 	if (!-e $path) {
                   10695: 	    mkdir($path,0770);
1.482     albertel 10696: 	}
                   10697:     }
1.828     www      10698: # now the path exists for sure
                   10699: # get a user agent
                   10700:     my $ua=new LWP::UserAgent;
                   10701:     my $transferfile=$file.'.in.transfer';
                   10702: # FIXME: this should flock
                   10703:     if (-e $transferfile) { return 'ok'; }
                   10704:     my $request;
                   10705:     $uri=~s/^\///;
1.980     raeburn  10706:     my $homeserver = &homeserver($cnum,$cdom);
                   10707:     my $protocol = $protocol{$homeserver};
                   10708:     $protocol = 'http' if ($protocol ne 'https');
                   10709:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      10710:     my $response=$ua->request($request,$transferfile);
                   10711: # did it work?
                   10712:     if ($response->is_error()) {
                   10713: 	unlink($transferfile);
                   10714: 	&logthis("Userfile repcopy failed for $uri");
                   10715: 	return -1;
                   10716:     }
                   10717: # worked, rename the transfer file
                   10718:     rename($transferfile,$file);
1.607     raeburn  10719:     return 'ok';
1.481     raeburn  10720: }
                   10721: 
1.517     albertel 10722: sub tokenwrapper {
                   10723:     my $uri=shift;
1.980     raeburn  10724:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 10725:     $uri=~s|^/||;
1.620     albertel 10726:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 10727:     my $token=$1;
1.552     albertel 10728:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   10729:     if ($udom && $uname && $file) {
                   10730: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  10731:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  10732:         my $homeserver = &homeserver($uname,$udom);
                   10733:         my $protocol = $protocol{$homeserver};
                   10734:         $protocol = 'http' if ($protocol ne 'https');
                   10735:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 10736:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   10737:                                '&tokenissued='.$perlvar{'lonHostID'};
                   10738:     } else {
                   10739:         return '/adm/notfound.html';
                   10740:     }
                   10741: }
                   10742: 
1.828     www      10743: # call with reqtype HEAD: get last modification time
                   10744: # call with reqtype GET: get the file contents
                   10745: # Do not call this with reqtype GET for large files! It loads everything into memory
                   10746: #
1.481     raeburn  10747: sub getuploaded {
                   10748:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   10749:     $uri=~s/^\///;
1.980     raeburn  10750:     my $homeserver = &homeserver($cnum,$cdom);
                   10751:     my $protocol = $protocol{$homeserver};
                   10752:     $protocol = 'http' if ($protocol ne 'https');
                   10753:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  10754:     my $ua=new LWP::UserAgent;
                   10755:     my $request=new HTTP::Request($reqtype,$uri);
                   10756:     my $response=$ua->request($request);
                   10757:     $$rtncode = $response->code;
1.482     albertel 10758:     if (! $response->is_success()) {
                   10759: 	return 'failed';
                   10760:     }      
                   10761:     if ($reqtype eq 'HEAD') {
1.486     www      10762: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 10763:     } elsif ($reqtype eq 'GET') {
                   10764: 	$$info = $response->content;
1.472     albertel 10765:     }
1.482     albertel 10766:     return 'ok';
1.36      albertel 10767: }
                   10768: 
1.481     raeburn  10769: sub readfile {
                   10770:     my $file = shift;
                   10771:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   10772:     my $fh;
                   10773:     open($fh,"<$file");
                   10774:     my $a='';
1.800     albertel 10775:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  10776:     return $a;
                   10777: }
                   10778: 
1.36      albertel 10779: sub filelocation {
1.590     banghart 10780:     my ($dir,$file) = @_;
                   10781:     my $location;
                   10782:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 10783: 
                   10784:     if ($file =~ m-^/adm/-) {
                   10785: 	$file=~s-^/adm/wrapper/-/-;
                   10786: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   10787:     }
1.882     albertel 10788: 
1.1139    www      10789:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  10790:         $location = $file;
1.609     banghart 10791:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 10792:         my ($udom,$uname,$filename)=
1.811     albertel 10793:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 10794:         my $home=&homeserver($uname,$udom);
                   10795:         my $is_me=0;
                   10796:         my @ids=&current_machine_ids();
                   10797:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   10798:         if ($is_me) {
1.1117    foxr     10799:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 10800:         } else {
                   10801:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   10802:   	      $udom.'/'.$uname.'/'.$filename;
                   10803:         }
1.882     albertel 10804:     } elsif ($file =~ m-^/adm/-) {
                   10805: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 10806:     } else {
                   10807:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      10808:         $file=~s:^/(res|priv)/:/:;
                   10809:         my $space=$1;
1.590     banghart 10810:         if ( !( $file =~ m:^/:) ) {
                   10811:             $location = $dir. '/'.$file;
                   10812:         } else {
1.1142    raeburn  10813:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 10814:         }
1.59      albertel 10815:     }
1.590     banghart 10816:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 10817:     while ($location=~m{/\.\./}) {
                   10818: 	if ($location =~ m{/[^/]+/\.\./}) {
                   10819: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   10820: 	} else {
                   10821: 	    $location=~ s{/\.\./}{/}g;
                   10822: 	}
                   10823:     } #remove dir/..
1.590     banghart 10824:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   10825:     return $location;
1.46      www      10826: }
1.36      albertel 10827: 
1.46      www      10828: sub hreflocation {
                   10829:     my ($dir,$file)=@_;
1.980     raeburn  10830:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 10831: 	$file=filelocation($dir,$file);
1.700     albertel 10832:     } elsif ($file=~m-^/adm/-) {
                   10833: 	$file=~s-^/adm/wrapper/-/-;
                   10834: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 10835:     }
                   10836:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   10837: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   10838:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  10839: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   10840: 	        {/uploaded/$1/$2/}x;
1.46      www      10841:     }
1.913     albertel 10842:     if ($file=~ m{^/userfiles/}) {
                   10843: 	$file =~ s{^/userfiles/}{/uploaded/};
                   10844:     }
1.462     albertel 10845:     return $file;
1.465     albertel 10846: }
                   10847: 
1.1139    www      10848: 
                   10849: 
                   10850: 
                   10851: 
1.465     albertel 10852: sub current_machine_domains {
1.853     albertel 10853:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   10854: }
                   10855: 
                   10856: sub machine_domains {
                   10857:     my ($hostname) = @_;
1.465     albertel 10858:     my @domains;
1.838     albertel 10859:     my %hostname = &all_hostnames();
1.465     albertel 10860:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  10861: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 10862: 	if ($hostname eq $name) {
1.844     albertel 10863: 	    push(@domains,&host_domain($id));
1.465     albertel 10864: 	}
                   10865:     }
                   10866:     return @domains;
                   10867: }
                   10868: 
                   10869: sub current_machine_ids {
1.853     albertel 10870:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   10871: }
                   10872: 
                   10873: sub machine_ids {
                   10874:     my ($hostname) = @_;
                   10875:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 10876:     my @ids;
1.888     albertel 10877:     my %name_to_host = &all_names();
1.889     albertel 10878:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   10879: 	return @{ $name_to_host{$hostname} };
                   10880:     }
                   10881:     return;
1.31      www      10882: }
                   10883: 
1.824     raeburn  10884: sub additional_machine_domains {
                   10885:     my @domains;
                   10886:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   10887:     while( my $line = <$fh>) {
                   10888:         $line =~ s/\s//g;
                   10889:         push(@domains,$line);
                   10890:     }
                   10891:     return @domains;
                   10892: }
                   10893: 
                   10894: sub default_login_domain {
                   10895:     my $domain = $perlvar{'lonDefDomain'};
                   10896:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   10897:     foreach my $posdom (&current_machine_domains(),
                   10898:                         &additional_machine_domains()) {
                   10899:         if (lc($posdom) eq lc($testdomain)) {
                   10900:             $domain=$posdom;
                   10901:             last;
                   10902:         }
                   10903:     }
                   10904:     return $domain;
                   10905: }
                   10906: 
1.31      www      10907: # ------------------------------------------------------------- Declutters URLs
                   10908: 
                   10909: sub declutter {
                   10910:     my $thisfn=shift;
1.569     albertel 10911:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 10912:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      10913:     $thisfn=~s/^\///;
1.697     albertel 10914:     $thisfn=~s|^adm/wrapper/||;
                   10915:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      10916:     $thisfn=~s/^res\///;
1.1172    bisitz   10917:     $thisfn=~s/^priv\///;
1.1032    raeburn  10918:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   10919:         $thisfn=~s/\?.+$//;
                   10920:     }
1.268     www      10921:     return $thisfn;
                   10922: }
                   10923: 
                   10924: # ------------------------------------------------------------- Clutter up URLs
                   10925: 
                   10926: sub clutter {
                   10927:     my $thisfn='/'.&declutter(shift);
1.887     albertel 10928:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 10929: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      10930:        $thisfn='/res'.$thisfn; 
                   10931:     }
1.1031    raeburn  10932:     if ($thisfn !~m|^/adm|) {
                   10933: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 10934: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 10935: 	} else {
                   10936: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   10937: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 10938: 	    if ($embstyle eq 'ssi'
                   10939: 		|| ($embstyle eq 'hdn')
                   10940: 		|| ($embstyle eq 'rat')
                   10941: 		|| ($embstyle eq 'prv')
                   10942: 		|| ($embstyle eq 'ign')) {
                   10943: 		#do nothing with these
                   10944: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 10945: 		|| ($embstyle eq 'emb')
                   10946: 		|| ($embstyle eq 'wrp')) {
                   10947: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 10948: 	    } elsif ($embstyle eq 'unk'
                   10949: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 10950: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 10951: 	    } else {
1.718     www      10952: #		&logthis("Got a blank emb style");
1.695     albertel 10953: 	    }
1.694     albertel 10954: 	}
                   10955:     }
1.31      www      10956:     return $thisfn;
1.12      www      10957: }
                   10958: 
1.787     albertel 10959: sub clutter_with_no_wrapper {
                   10960:     my $uri = &clutter(shift);
                   10961:     if ($uri =~ m-^/adm/-) {
                   10962: 	$uri =~ s-^/adm/wrapper/-/-;
                   10963: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   10964:     }
                   10965:     return $uri;
                   10966: }
                   10967: 
1.557     albertel 10968: sub freeze_escape {
                   10969:     my ($value)=@_;
                   10970:     if (ref($value)) {
                   10971: 	$value=&nfreeze($value);
                   10972: 	return '__FROZEN__'.&escape($value);
                   10973:     }
                   10974:     return &escape($value);
                   10975: }
                   10976: 
1.11      www      10977: 
1.557     albertel 10978: sub thaw_unescape {
                   10979:     my ($value)=@_;
                   10980:     if ($value =~ /^__FROZEN__/) {
                   10981: 	substr($value,0,10,undef);
                   10982: 	$value=&unescape($value);
                   10983: 	return &thaw($value);
                   10984:     }
                   10985:     return &unescape($value);
                   10986: }
                   10987: 
1.436     albertel 10988: sub correct_line_ends {
                   10989:     my ($result)=@_;
                   10990:     $$result =~s/\r\n/\n/mg;
                   10991:     $$result =~s/\r/\n/mg;
1.415     albertel 10992: }
1.1       albertel 10993: # ================================================================ Main Program
                   10994: 
1.184     www      10995: sub goodbye {
1.204     albertel 10996:    &logthis("Starting Shut down");
1.443     albertel 10997: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 10998:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10999: #converted
1.599     albertel 11000: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 11001:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   11002: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   11003: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 11004: #1.1 only
1.870     albertel 11005: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   11006: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   11007: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   11008: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   11009:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 11010:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   11011:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      11012:    &flushcourselogs();
                   11013:    &logthis("Shutting down");
                   11014: }
                   11015: 
1.852     albertel 11016: sub get_dns {
1.869     albertel 11017:     my ($url,$func,$ignore_cache) = @_;
                   11018:     if (!$ignore_cache) {
                   11019: 	my ($content,$cached)=
                   11020: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   11021: 	if ($cached) {
                   11022: 	    &$func($content);
                   11023: 	    return;
                   11024: 	}
                   11025:     }
                   11026: 
                   11027:     my %alldns;
1.852     albertel 11028:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11029:     foreach my $dns (<$config>) {
                   11030: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  11031:         my $line = $1;
                   11032:         my ($host,$protocol) = split(/:/,$line);
                   11033:         if ($protocol ne 'https') {
                   11034:             $protocol = 'http';
                   11035:         }
                   11036: 	$alldns{$host} = $protocol;
1.869     albertel 11037:     }
                   11038:     while (%alldns) {
                   11039: 	my ($dns) = keys(%alldns);
1.852     albertel 11040: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  11041:         $ua->timeout(30);
1.979     raeburn  11042: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 11043: 	my $response=$ua->request($request);
1.979     raeburn  11044:         delete($alldns{$dns});
1.852     albertel 11045: 	next if ($response->is_error());
                   11046: 	my @content = split("\n",$response->content);
1.869     albertel 11047: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 11048: 	&$func(\@content);
1.869     albertel 11049: 	return;
1.852     albertel 11050:     }
                   11051:     close($config);
1.871     albertel 11052:     my $which = (split('/',$url))[3];
                   11053:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   11054:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 11055:     my @content = <$config>;
                   11056:     &$func(\@content);
                   11057:     return;
1.852     albertel 11058: }
1.327     albertel 11059: # ------------------------------------------------------------ Read domain file
                   11060: {
1.852     albertel 11061:     my $loaded;
1.846     albertel 11062:     my %domain;
                   11063: 
1.852     albertel 11064:     sub parse_domain_tab {
                   11065: 	my ($lines) = @_;
                   11066: 	foreach my $line (@$lines) {
                   11067: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11068: 
1.846     albertel 11069: 	    chomp($line);
1.852     albertel 11070: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11071: 	    my %this_domain;
                   11072: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11073: 			       'lang_def', 'city', 'longi', 'lati',
                   11074: 			       'primary') {
                   11075: 		$this_domain{$field} = shift(@elements);
                   11076: 	    }
                   11077: 	    $domain{$name} = \%this_domain;
1.852     albertel 11078: 	}
                   11079:     }
1.864     albertel 11080: 
                   11081:     sub reset_domain_info {
                   11082: 	undef($loaded);
                   11083: 	undef(%domain);
                   11084:     }
                   11085: 
1.852     albertel 11086:     sub load_domain_tab {
1.869     albertel 11087: 	my ($ignore_cache) = @_;
                   11088: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11089: 	my $fh;
                   11090: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11091: 	    my @lines = <$fh>;
                   11092: 	    &parse_domain_tab(\@lines);
1.448     albertel 11093: 	}
1.852     albertel 11094: 	close($fh);
                   11095: 	$loaded = 1;
1.327     albertel 11096:     }
1.846     albertel 11097: 
                   11098:     sub domain {
1.852     albertel 11099: 	&load_domain_tab() if (!$loaded);
                   11100: 
1.846     albertel 11101: 	my ($name,$what) = @_;
                   11102: 	return if ( !exists($domain{$name}) );
                   11103: 
                   11104: 	if (!$what) {
                   11105: 	    return $domain{$name}{'description'};
                   11106: 	}
                   11107: 	return $domain{$name}{$what};
                   11108:     }
1.974     raeburn  11109: 
                   11110:     sub domain_info {
                   11111:         &load_domain_tab() if (!$loaded);
                   11112:         return %domain;
                   11113:     }
                   11114: 
1.327     albertel 11115: }
                   11116: 
                   11117: 
1.1       albertel 11118: # ------------------------------------------------------------- Read hosts file
                   11119: {
1.838     albertel 11120:     my %hostname;
1.844     albertel 11121:     my %hostdom;
1.845     albertel 11122:     my %libserv;
1.852     albertel 11123:     my $loaded;
1.888     albertel 11124:     my %name_to_host;
1.1074    raeburn  11125:     my %internetdom;
1.1107    raeburn  11126:     my %LC_dns_serv;
1.852     albertel 11127: 
                   11128:     sub parse_hosts_tab {
                   11129: 	my ($file) = @_;
                   11130: 	foreach my $configline (@$file) {
                   11131: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11132:             chomp($configline);
                   11133: 	    if ($configline =~ /^\^/) {
                   11134:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11135:                     $LC_dns_serv{$1} = 1;
                   11136:                 }
                   11137:                 next;
                   11138:             }
1.1074    raeburn  11139: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11140: 	    $name=~s/\s//g;
                   11141: 	    if ($id && $domain && $role && $name) {
                   11142: 		$hostname{$id}=$name;
1.888     albertel 11143: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11144: 		$hostdom{$id}=$domain;
                   11145: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11146:                 if (defined($protocol)) {
                   11147:                     if ($protocol eq 'https') {
                   11148:                         $protocol{$id} = $protocol;
                   11149:                     } else {
                   11150:                         $protocol{$id} = 'http'; 
                   11151:                     }
1.968     raeburn  11152:                 } else {
1.969     raeburn  11153:                     $protocol{$id} = 'http';
1.968     raeburn  11154:                 }
1.1074    raeburn  11155:                 if (defined($intdom)) {
                   11156:                     $internetdom{$id} = $intdom;
                   11157:                 }
1.852     albertel 11158: 	    }
                   11159: 	}
                   11160:     }
1.864     albertel 11161:     
                   11162:     sub reset_hosts_info {
1.897     albertel 11163: 	&purge_remembered();
1.864     albertel 11164: 	&reset_domain_info();
                   11165: 	&reset_hosts_ip_info();
1.892     albertel 11166: 	undef(%name_to_host);
1.864     albertel 11167: 	undef(%hostname);
                   11168: 	undef(%hostdom);
                   11169: 	undef(%libserv);
                   11170: 	undef($loaded);
                   11171:     }
1.1       albertel 11172: 
1.852     albertel 11173:     sub load_hosts_tab {
1.869     albertel 11174: 	my ($ignore_cache) = @_;
                   11175: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11176: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11177: 	my @config = <$config>;
                   11178: 	&parse_hosts_tab(\@config);
                   11179: 	close($config);
                   11180: 	$loaded=1;
1.1       albertel 11181:     }
1.852     albertel 11182: 
1.838     albertel 11183:     sub hostname {
1.852     albertel 11184: 	&load_hosts_tab() if (!$loaded);
                   11185: 
1.838     albertel 11186: 	my ($lonid) = @_;
                   11187: 	return $hostname{$lonid};
                   11188:     }
1.845     albertel 11189: 
1.838     albertel 11190:     sub all_hostnames {
1.852     albertel 11191: 	&load_hosts_tab() if (!$loaded);
                   11192: 
1.838     albertel 11193: 	return %hostname;
                   11194:     }
1.845     albertel 11195: 
1.888     albertel 11196:     sub all_names {
                   11197: 	&load_hosts_tab() if (!$loaded);
                   11198: 
                   11199: 	return %name_to_host;
                   11200:     }
                   11201: 
1.974     raeburn  11202:     sub all_host_domain {
                   11203:         &load_hosts_tab() if (!$loaded);
                   11204:         return %hostdom;
                   11205:     }
                   11206: 
1.845     albertel 11207:     sub is_library {
1.852     albertel 11208: 	&load_hosts_tab() if (!$loaded);
                   11209: 
1.845     albertel 11210: 	return exists($libserv{$_[0]});
                   11211:     }
                   11212: 
                   11213:     sub all_library {
1.852     albertel 11214: 	&load_hosts_tab() if (!$loaded);
                   11215: 
1.845     albertel 11216: 	return %libserv;
                   11217:     }
                   11218: 
1.1062    droeschl 11219:     sub unique_library {
                   11220: 	#2x reverse removes all hostnames that appear more than once
                   11221:         my %unique = reverse &all_library();
                   11222:         return reverse %unique;
                   11223:     }
                   11224: 
1.841     albertel 11225:     sub get_servers {
1.852     albertel 11226: 	&load_hosts_tab() if (!$loaded);
                   11227: 
1.841     albertel 11228: 	my ($domain,$type) = @_;
                   11229: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11230: 	                                          : %hostname;
                   11231: 	my %result;
1.842     albertel 11232: 	if (ref($domain) eq 'ARRAY') {
                   11233: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11234: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11235: 		    $result{$host} = $hostname;
                   11236: 		}
                   11237: 	    }
                   11238: 	} else {
                   11239: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11240: 		if ($hostdom{$host} eq $domain) {
                   11241: 		    $result{$host} = $hostname;
                   11242: 		}
1.841     albertel 11243: 	    }
                   11244: 	}
                   11245: 	return %result;
                   11246:     }
1.845     albertel 11247: 
1.1062    droeschl 11248:     sub get_unique_servers {
                   11249:         my %unique = reverse &get_servers(@_);
                   11250: 	return reverse %unique;
                   11251:     }
                   11252: 
1.844     albertel 11253:     sub host_domain {
1.852     albertel 11254: 	&load_hosts_tab() if (!$loaded);
                   11255: 
1.844     albertel 11256: 	my ($lonid) = @_;
                   11257: 	return $hostdom{$lonid};
                   11258:     }
                   11259: 
1.841     albertel 11260:     sub all_domains {
1.852     albertel 11261: 	&load_hosts_tab() if (!$loaded);
                   11262: 
1.841     albertel 11263: 	my %seen;
                   11264: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11265: 	return @uniq;
                   11266:     }
1.1074    raeburn  11267: 
                   11268:     sub internet_dom {
                   11269:         &load_hosts_tab() if (!$loaded);
                   11270: 
                   11271:         my ($lonid) = @_;
                   11272:         return $internetdom{$lonid};
                   11273:     }
1.1107    raeburn  11274: 
                   11275:     sub is_LC_dns {
                   11276:         &load_hosts_tab() if (!$loaded);
                   11277: 
                   11278:         my ($hostname) = @_;
                   11279:         return exists($LC_dns_serv{$hostname});
                   11280:     }
                   11281: 
1.1       albertel 11282: }
                   11283: 
1.847     albertel 11284: { 
                   11285:     my %iphost;
1.856     albertel 11286:     my %name_to_ip;
                   11287:     my %lonid_to_ip;
1.869     albertel 11288: 
1.847     albertel 11289:     sub get_hosts_from_ip {
                   11290: 	my ($ip) = @_;
                   11291: 	my %iphosts = &get_iphost();
                   11292: 	if (ref($iphosts{$ip})) {
                   11293: 	    return @{$iphosts{$ip}};
                   11294: 	}
                   11295: 	return;
1.839     albertel 11296:     }
1.864     albertel 11297:     
                   11298:     sub reset_hosts_ip_info {
                   11299: 	undef(%iphost);
                   11300: 	undef(%name_to_ip);
                   11301: 	undef(%lonid_to_ip);
                   11302:     }
1.856     albertel 11303: 
                   11304:     sub get_host_ip {
                   11305: 	my ($lonid) = @_;
                   11306: 	if (exists($lonid_to_ip{$lonid})) {
                   11307: 	    return $lonid_to_ip{$lonid};
                   11308: 	}
                   11309: 	my $name=&hostname($lonid);
                   11310:    	my $ip = gethostbyname($name);
                   11311: 	return if (!$ip || length($ip) ne 4);
                   11312: 	$ip=inet_ntoa($ip);
                   11313: 	$name_to_ip{$name}   = $ip;
                   11314: 	$lonid_to_ip{$lonid} = $ip;
                   11315: 	return $ip;
                   11316:     }
1.847     albertel 11317:     
                   11318:     sub get_iphost {
1.869     albertel 11319: 	my ($ignore_cache) = @_;
1.894     albertel 11320: 
1.869     albertel 11321: 	if (!$ignore_cache) {
                   11322: 	    if (%iphost) {
                   11323: 		return %iphost;
                   11324: 	    }
                   11325: 	    my ($ip_info,$cached)=
                   11326: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11327: 	    if ($cached) {
                   11328: 		%iphost      = %{$ip_info->[0]};
                   11329: 		%name_to_ip  = %{$ip_info->[1]};
                   11330: 		%lonid_to_ip = %{$ip_info->[2]};
                   11331: 		return %iphost;
                   11332: 	    }
                   11333: 	}
1.894     albertel 11334: 
                   11335: 	# get yesterday's info for fallback
                   11336: 	my %old_name_to_ip;
                   11337: 	my ($ip_info,$cached)=
                   11338: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11339: 	if ($cached) {
                   11340: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11341: 	}
                   11342: 
1.888     albertel 11343: 	my %name_to_host = &all_names();
                   11344: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11345: 	    my $ip;
                   11346: 	    if (!exists($name_to_ip{$name})) {
                   11347: 		$ip = gethostbyname($name);
                   11348: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11349: 		    if (defined($old_name_to_ip{$name})) {
                   11350: 			$ip = $old_name_to_ip{$name};
                   11351: 			&logthis("Can't find $name defaulting to old $ip");
                   11352: 		    } else {
                   11353: 			&logthis("Name $name no IP found");
                   11354: 			next;
                   11355: 		    }
                   11356: 		} else {
                   11357: 		    $ip=inet_ntoa($ip);
1.847     albertel 11358: 		}
                   11359: 		$name_to_ip{$name} = $ip;
                   11360: 	    } else {
                   11361: 		$ip = $name_to_ip{$name};
1.653     albertel 11362: 	    }
1.888     albertel 11363: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11364: 		$lonid_to_ip{$id} = $ip;
                   11365: 	    }
                   11366: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11367: 	}
1.869     albertel 11368: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11369: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11370: 				      48*60*60);
1.869     albertel 11371: 
1.847     albertel 11372: 	return %iphost;
1.598     albertel 11373:     }
                   11374: 
1.992     raeburn  11375:     #
                   11376:     #  Given a DNS returns the loncapa host name for that DNS 
                   11377:     # 
                   11378:     sub host_from_dns {
                   11379:         my ($dns) = @_;
                   11380:         my @hosts;
                   11381:         my $ip;
                   11382: 
1.993     raeburn  11383:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11384:             $ip = $name_to_ip{$dns};
                   11385:         }
                   11386:         if (!$ip) {
                   11387:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11388:             if (length($ip) == 4) { 
                   11389: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11390:             }
                   11391:         }
                   11392:         if ($ip) {
                   11393: 	    @hosts = get_hosts_from_ip($ip);
                   11394: 	    return $hosts[0];
                   11395:         }
                   11396:         return undef;
1.986     foxr     11397:     }
1.992     raeburn  11398: 
1.1074    raeburn  11399:     sub get_internet_names {
                   11400:         my ($lonid) = @_;
                   11401:         return if ($lonid eq '');
                   11402:         my ($idnref,$cached)=
                   11403:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   11404:         if ($cached) {
                   11405:             return $idnref;
                   11406:         }
                   11407:         my $ip = &get_host_ip($lonid);
                   11408:         my @hosts = &get_hosts_from_ip($ip);
                   11409:         my %iphost = &get_iphost();
                   11410:         my (@idns,%seen);
                   11411:         foreach my $id (@hosts) {
                   11412:             my $dom = &host_domain($id);
                   11413:             my $prim_id = &domain($dom,'primary');
                   11414:             my $prim_ip = &get_host_ip($prim_id);
                   11415:             next if ($seen{$prim_ip});
                   11416:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   11417:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   11418:                     my $intdom = &internet_dom($id);
                   11419:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   11420:                         push(@idns,$intdom);
                   11421:                     }
                   11422:                 }
                   11423:             }
                   11424:             $seen{$prim_ip} = 1;
                   11425:         }
                   11426:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   11427:     }
                   11428: 
1.986     foxr     11429: }
                   11430: 
1.1079    raeburn  11431: sub all_loncaparevs {
                   11432:     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);
                   11433: }
                   11434: 
1.862     albertel 11435: BEGIN {
                   11436: 
                   11437: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   11438:     unless ($readit) {
                   11439: {
                   11440:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   11441:     %perlvar = (%perlvar,%{$configvars});
                   11442: }
                   11443: 
                   11444: 
1.1       albertel 11445: # ------------------------------------------------------ Read spare server file
                   11446: {
1.448     albertel 11447:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 11448: 
                   11449:     while (my $configline=<$config>) {
                   11450:        chomp($configline);
1.284     matthew  11451:        if ($configline) {
1.784     albertel 11452: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 11453: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 11454: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 11455:        }
                   11456:     }
1.448     albertel 11457:     close($config);
1.1       albertel 11458: }
1.11      www      11459: # ------------------------------------------------------------ Read permissions
                   11460: {
1.448     albertel 11461:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      11462: 
                   11463:     while (my $configline=<$config>) {
1.448     albertel 11464: 	chomp($configline);
                   11465: 	if ($configline) {
                   11466: 	    my ($role,$perm)=split(/ /,$configline);
                   11467: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   11468: 	}
1.11      www      11469:     }
1.448     albertel 11470:     close($config);
1.11      www      11471: }
                   11472: 
                   11473: # -------------------------------------------- Read plain texts for permissions
                   11474: {
1.448     albertel 11475:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      11476: 
                   11477:     while (my $configline=<$config>) {
1.448     albertel 11478: 	chomp($configline);
                   11479: 	if ($configline) {
1.742     raeburn  11480: 	    my ($short,@plain)=split(/:/,$configline);
                   11481:             %{$prp{$short}} = ();
                   11482: 	    if (@plain > 0) {
                   11483:                 $prp{$short}{'std'} = $plain[0];
                   11484:                 for (my $i=1; $i<@plain; $i++) {
                   11485:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   11486:                 }
                   11487:             }
1.448     albertel 11488: 	}
1.135     www      11489:     }
1.448     albertel 11490:     close($config);
1.135     www      11491: }
                   11492: 
                   11493: # ---------------------------------------------------------- Read package table
                   11494: {
1.448     albertel 11495:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      11496: 
                   11497:     while (my $configline=<$config>) {
1.483     albertel 11498: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 11499: 	chomp($configline);
                   11500: 	my ($short,$plain)=split(/:/,$configline);
                   11501: 	my ($pack,$name)=split(/\&/,$short);
                   11502: 	if ($plain ne '') {
                   11503: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   11504: 	    $packagetab{$short}=$plain; 
                   11505: 	}
1.11      www      11506:     }
1.448     albertel 11507:     close($config);
1.329     matthew  11508: }
                   11509: 
1.1073    raeburn  11510: # ---------------------------------------------------------- Read loncaparev table
                   11511: {
                   11512:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   11513:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   11514:             while (my $configline=<$config>) {
                   11515:                 chomp($configline);
                   11516:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   11517:                 $loncaparevs{$hostid}=$loncaparev;
                   11518:             }
                   11519:             close($config);
                   11520:         }
                   11521:     }
                   11522: }
                   11523: 
1.1074    raeburn  11524: # ---------------------------------------------------------- Read serverhostID table
                   11525: {
                   11526:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   11527:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   11528:             while (my $configline=<$config>) {
                   11529:                 chomp($configline);
                   11530:                 my ($name,$id)=split(/:/,$configline);
                   11531:                 $serverhomeIDs{$name}=$id;
                   11532:             }
                   11533:             close($config);
                   11534:         }
                   11535:     }
                   11536: }
                   11537: 
1.1079    raeburn  11538: {
                   11539:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   11540:     if (-e $file) {
                   11541:         my $parser = HTML::LCParser->new($file);
                   11542:         while (my $token = $parser->get_token()) {
                   11543:             if ($token->[0] eq 'S') {
                   11544:                 my $item = $token->[1];
                   11545:                 my $name = $token->[2]{'name'};
                   11546:                 my $value = $token->[2]{'value'};
                   11547:                 if ($item ne '' && $name ne '' && $value ne '') {
                   11548:                     my $release = $parser->get_text();
                   11549:                     $release =~ s/(^\s*|\s*$ )//gx;
                   11550:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   11551:                 }
                   11552:             }
                   11553:         }
                   11554:     }
1.1073    raeburn  11555: }
                   11556: 
1.1138    raeburn  11557: # ---------------------------------------------------------- Read managers table
                   11558: {
                   11559:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   11560:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   11561:             while (my $configline=<$config>) {
                   11562:                 chomp($configline);
                   11563:                 next if ($configline =~ /^\#/);
                   11564:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   11565:                     $managerstab{$configline} = 1;
                   11566:                 }
                   11567:             }
                   11568:             close($config);
                   11569:         }
                   11570:     }
                   11571: }
                   11572: 
1.329     matthew  11573: # ------------- set up temporary directory
                   11574: {
1.1117    foxr     11575:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  11576: 
1.11      www      11577: }
                   11578: 
1.794     albertel 11579: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   11580: 				'compress_threshold'=> 20_000,
                   11581:  			        });
1.185     www      11582: 
1.281     www      11583: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      11584: $dumpcount=0;
1.958     www      11585: $locknum=0;
1.22      www      11586: 
1.163     harris41 11587: &logtouch();
1.672     albertel 11588: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      11589: $readit=1;
1.564     albertel 11590:     {
                   11591: 	use integer;
                   11592: 	my $test=(2**32)+1;
1.568     albertel 11593: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 11594: 	&logthis(" Detected 64bit platform ($_64bit)");
                   11595:     }
1.195     www      11596: }
1.1       albertel 11597: }
1.179     www      11598: 
1.1       albertel 11599: 1;
1.191     harris41 11600: __END__
                   11601: 
1.243     albertel 11602: =pod
                   11603: 
1.191     harris41 11604: =head1 NAME
                   11605: 
1.243     albertel 11606: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 11607: 
                   11608: =head1 SYNOPSIS
                   11609: 
1.243     albertel 11610: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 11611: 
                   11612:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   11613: 
1.243     albertel 11614: Common parameters:
                   11615: 
                   11616: =over 4
                   11617: 
                   11618: =item *
                   11619: 
                   11620: $uname : an internal username (if $cname expecting a course Id specifically)
                   11621: 
                   11622: =item *
                   11623: 
                   11624: $udom : a domain (if $cdom expecting a course's domain specifically)
                   11625: 
                   11626: =item *
                   11627: 
                   11628: $symb : a resource instance identifier
                   11629: 
                   11630: =item *
                   11631: 
                   11632: $namespace : the name of a .db file that contains the data needed or
                   11633: being set.
                   11634: 
                   11635: =back
                   11636: 
1.394     bowersj2 11637: =head1 OVERVIEW
1.191     harris41 11638: 
1.394     bowersj2 11639: lonnet provides subroutines which interact with the
                   11640: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   11641: about classes, users, and resources.
1.243     albertel 11642: 
                   11643: For many of these objects you can also use this to store data about
                   11644: them or modify them in various ways.
1.191     harris41 11645: 
1.394     bowersj2 11646: =head2 Symbs
1.191     harris41 11647: 
1.394     bowersj2 11648: To identify a specific instance of a resource, LON-CAPA uses symbols
                   11649: or "symbs"X<symb>. These identifiers are built from the URL of the
                   11650: map, the resource number of the resource in the map, and the URL of
                   11651: the resource itself. The latter is somewhat redundant, but might help
                   11652: if maps change.
                   11653: 
                   11654: An example is
                   11655: 
                   11656:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   11657: 
                   11658: The respective map entry is
                   11659: 
                   11660:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   11661:   title="Problem 2">
                   11662:  </resource>
                   11663: 
                   11664: Symbs are used by the random number generator, as well as to store and
                   11665: restore data specific to a certain instance of for example a problem.
                   11666: 
                   11667: =head2 Storing And Retrieving Data
                   11668: 
                   11669: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   11670: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   11671: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   11672: is is the non-critical message twin of cstore. These functions are for
                   11673: handlers to store a perl hash to a user's permanent data space in an
                   11674: easy manner, and to retrieve it again on another call. It is expected
                   11675: that a handler would use this once at the beginning to retrieve data,
                   11676: and then again once at the end to send only the new data back.
                   11677: 
                   11678: The data is stored in the user's data directory on the user's
                   11679: homeserver under the ID of the course.
                   11680: 
                   11681: The hash that is returned by restore will have all of the previous
                   11682: value for all of the elements of the hash.
                   11683: 
                   11684: Example:
                   11685: 
                   11686:  #creating a hash
                   11687:  my %hash;
                   11688:  $hash{'foo'}='bar';
                   11689: 
                   11690:  #storing it
                   11691:  &Apache::lonnet::cstore(\%hash);
                   11692: 
                   11693:  #changing a value
                   11694:  $hash{'foo'}='notbar';
                   11695: 
                   11696:  #adding a new value
                   11697:  $hash{'bar'}='foo';
                   11698:  &Apache::lonnet::cstore(\%hash);
                   11699: 
                   11700:  #retrieving the hash
                   11701:  my %history=&Apache::lonnet::restore();
                   11702: 
                   11703:  #print the hash
                   11704:  foreach my $key (sort(keys(%history))) {
                   11705:    print("\%history{$key} = $history{$key}");
                   11706:  }
                   11707: 
                   11708: Will print out:
1.191     harris41 11709: 
1.394     bowersj2 11710:  %history{1:foo} = bar
                   11711:  %history{1:keys} = foo:timestamp
                   11712:  %history{1:timestamp} = 990455579
                   11713:  %history{2:bar} = foo
                   11714:  %history{2:foo} = notbar
                   11715:  %history{2:keys} = foo:bar:timestamp
                   11716:  %history{2:timestamp} = 990455580
                   11717:  %history{bar} = foo
                   11718:  %history{foo} = notbar
                   11719:  %history{timestamp} = 990455580
                   11720:  %history{version} = 2
                   11721: 
                   11722: Note that the special hash entries C<keys>, C<version> and
                   11723: C<timestamp> were added to the hash. C<version> will be equal to the
                   11724: total number of versions of the data that have been stored. The
                   11725: C<timestamp> attribute will be the UNIX time the hash was
                   11726: stored. C<keys> is available in every historical section to list which
                   11727: keys were added or changed at a specific historical revision of a
                   11728: hash.
                   11729: 
                   11730: B<Warning>: do not store the hash that restore returns directly. This
                   11731: will cause a mess since it will restore the historical keys as if the
                   11732: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 11733: 
1.394     bowersj2 11734: Calling convention:
1.191     harris41 11735: 
1.394     bowersj2 11736:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   11737:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 11738: 
1.394     bowersj2 11739: For more detailed information, see lonnet specific documentation.
1.191     harris41 11740: 
1.394     bowersj2 11741: =head1 RETURN MESSAGES
1.191     harris41 11742: 
1.394     bowersj2 11743: =over 4
1.191     harris41 11744: 
1.394     bowersj2 11745: =item * B<con_lost>: unable to contact remote host
1.191     harris41 11746: 
1.394     bowersj2 11747: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   11748: when the connection is brought back up
1.191     harris41 11749: 
1.394     bowersj2 11750: =item * B<con_failed>: unable to contact remote host and unable to save message
                   11751: for later delivery
1.191     harris41 11752: 
1.967     bisitz   11753: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 11754: 
1.394     bowersj2 11755: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 11756: that was requested
1.191     harris41 11757: 
1.243     albertel 11758: =back
1.191     harris41 11759: 
1.243     albertel 11760: =head1 PUBLIC SUBROUTINES
1.191     harris41 11761: 
1.243     albertel 11762: =head2 Session Environment Functions
1.191     harris41 11763: 
1.243     albertel 11764: =over 4
1.191     harris41 11765: 
1.394     bowersj2 11766: =item * 
                   11767: X<appenv()>
1.949     raeburn  11768: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 11769: the user envirnoment file, and will be restored for each access this
1.620     albertel 11770: user makes during this session, also modifies the %env for the current
1.949     raeburn  11771: process. Optional rolesarrayref - if defined contains a reference to an array
                   11772: of roles which are exempt from the restriction on modifying user.role entries 
                   11773: in the user's environment.db and in %env.    
1.191     harris41 11774: 
                   11775: =item *
1.394     bowersj2 11776: X<delenv()>
1.987     raeburn  11777: B<delenv($delthis,$regexp)>: removes all items from the session
                   11778: environment file that begin with $delthis. If the 
                   11779: optional second arg - $regexp - is true, $delthis is treated as a 
                   11780: regular expression, otherwise \Q$delthis\E is used. 
                   11781: The values are also deleted from the current processes %env.
1.191     harris41 11782: 
1.795     albertel 11783: =item * get_env_multiple($name) 
                   11784: 
                   11785: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   11786: values may be defined and end up as an array ref.
                   11787: 
                   11788: returns an array of values
                   11789: 
1.243     albertel 11790: =back
                   11791: 
                   11792: =head2 User Information
1.191     harris41 11793: 
1.243     albertel 11794: =over 4
1.191     harris41 11795: 
                   11796: =item *
1.394     bowersj2 11797: X<queryauthenticate()>
                   11798: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 11799: authentication scheme
                   11800: 
                   11801: =item *
1.394     bowersj2 11802: X<authenticate()>
1.1073    raeburn  11803: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 11804: authenticate user from domain's lib servers (first use the current
                   11805: one). C<$upass> should be the users password.
1.1073    raeburn  11806: $checkdefauth is optional (value is 1 if a check should be made to
                   11807:    authenticate user using default authentication method, and allow
                   11808:    account creation if username does not have account in the domain).
                   11809: $clientcancheckhost is optional (value is 1 if checking whether the
                   11810:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 11811: 
                   11812: =item *
1.394     bowersj2 11813: X<homeserver()>
                   11814: B<homeserver($uname,$udom)>: find the server which has
                   11815: the user's directory and files (there must be only one), this caches
                   11816: the answer, and also caches if there is a borken connection.
1.191     harris41 11817: 
                   11818: =item *
1.394     bowersj2 11819: X<idget()>
                   11820: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   11821: (IDs are a unique resource in a domain, there must be only 1 ID per
                   11822: username, and only 1 username per ID in a specific domain) (returns
                   11823: hash: id=>name,id=>name)
1.191     harris41 11824: 
                   11825: =item *
1.394     bowersj2 11826: X<idrget()>
                   11827: B<idrget($udom,@unames)>: find the IDs behind a list of
                   11828: usernames (returns hash: name=>id,name=>id)
1.191     harris41 11829: 
                   11830: =item *
1.394     bowersj2 11831: X<idput()>
                   11832: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 11833: 
                   11834: =item *
1.394     bowersj2 11835: X<rolesinit()>
1.1169    droeschl 11836: B<rolesinit($udom,$username)>: get user privileges.
                   11837: returns user role, first access and timer interval hashes
1.243     albertel 11838: 
                   11839: =item *
1.1171    droeschl 11840: X<privileged()>
                   11841: B<privileged($username,$domain)>: returns a true if user has a
                   11842: privileged and active role (i.e. su or dc), false otherwise.
                   11843: 
                   11844: =item *
1.551     albertel 11845: X<getsection()>
                   11846: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 11847: course $cname, return section name/number or '' for "not in course"
                   11848: and '-1' for "no section"
                   11849: 
                   11850: =item *
1.394     bowersj2 11851: X<userenvironment()>
                   11852: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 11853: passed in @what from the requested user's environment, returns a hash
                   11854: 
1.858     raeburn  11855: =item * 
                   11856: X<userlog_query()>
1.859     albertel 11857: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   11858: activity.log file. %filters defines filters applied when parsing the
                   11859: log file. These can be start or end timestamps, or the type of action
                   11860: - log to look for Login or Logout events, check for Checkin or
                   11861: Checkout, role for role selection. The response is in the form
                   11862: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   11863: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  11864: 
1.243     albertel 11865: =back
                   11866: 
                   11867: =head2 User Roles
                   11868: 
                   11869: =over 4
                   11870: 
                   11871: =item *
                   11872: 
1.810     raeburn  11873: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 11874:  F: full access
                   11875:  U,I,K: authentication modes (cxx only)
                   11876:  '': forbidden
                   11877:  1: user needs to choose course
                   11878:  2: browse allowed
1.766     albertel 11879:  A: passphrase authentication needed
1.243     albertel 11880: 
                   11881: =item *
                   11882: 
                   11883: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   11884: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   11885: and course level
                   11886: 
                   11887: =item *
                   11888: 
1.988     raeburn  11889: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   11890: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  11891: $type is Course (default) or Community.
1.988     raeburn  11892: If $forcedefault evaluates to true, text returned will be default 
                   11893: text for $type. Otherwise, if this is a course, the text returned 
                   11894: will be a custom name for the role (if defined in the course's 
                   11895: environment).  If no custom name is defined the default is returned.
                   11896:    
1.832     raeburn  11897: =item *
                   11898: 
1.935     raeburn  11899: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  11900: All arguments are optional. Returns a hash of a roles, either for
                   11901: co-author/assistant author roles for a user's Construction Space
1.906     albertel 11902: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  11903: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   11904: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   11905: For each key, value is set to colon-separated start and end times for
                   11906: the role.  If no username and domain are specified, will default to
1.934     raeburn  11907: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  11908: of role statuses (active, future or previous), roles 
                   11909: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   11910: to restrict the list of roles reported. If no array ref is 
                   11911: provided for types, will default to return only active roles.
1.834     albertel 11912: 
1.243     albertel 11913: =back
                   11914: 
                   11915: =head2 User Modification
                   11916: 
                   11917: =over 4
                   11918: 
                   11919: =item *
                   11920: 
1.957     raeburn  11921: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 11922: user for the level given by URL.  Optional start and end dates (leave empty
                   11923: string or zero for "no date")
1.191     harris41 11924: 
                   11925: =item *
                   11926: 
1.243     albertel 11927: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   11928: change a users, password, possible return values are: ok,
                   11929: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   11930: refused
1.191     harris41 11931: 
                   11932: =item *
                   11933: 
1.243     albertel 11934: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 11935: 
                   11936: =item *
                   11937: 
1.1058    raeburn  11938: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   11939:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   11940: 
                   11941: will update user information (firstname,middlename,lastname,generation,
                   11942: permanentemail), and if forceid is true, student/employee ID also.
                   11943: A user's institutional affiliation(s) can also be updated.
                   11944: User information fields will not be overwritten with empty entries 
                   11945: unless the field is included in the $candelete array reference.
                   11946: This array is included when a single user is modified via "Manage Users",
                   11947: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 11948: 
                   11949: =item *
                   11950: 
1.286     matthew  11951: modifystudent
                   11952: 
1.957     raeburn  11953: modify a student's enrollment and identification information.
1.286     matthew  11954: The course id is resolved based on the current users environment.  
                   11955: This means the envoking user must be a course coordinator or otherwise
                   11956: associated with a course.
                   11957: 
1.297     matthew  11958: This call is essentially a wrapper for lonnet::modifyuser and
                   11959: lonnet::modify_student_enrollment
1.286     matthew  11960: 
                   11961: Inputs: 
                   11962: 
                   11963: =over 4
                   11964: 
1.957     raeburn  11965: =item B<$udom> Student's loncapa domain
1.286     matthew  11966: 
1.957     raeburn  11967: =item B<$uname> Student's loncapa login name
1.286     matthew  11968: 
1.964     bisitz   11969: =item B<$uid> Student/Employee ID
1.286     matthew  11970: 
1.957     raeburn  11971: =item B<$umode> Student's authentication mode
1.286     matthew  11972: 
1.957     raeburn  11973: =item B<$upass> Student's password
1.286     matthew  11974: 
1.957     raeburn  11975: =item B<$first> Student's first name
1.286     matthew  11976: 
1.957     raeburn  11977: =item B<$middle> Student's middle name
1.286     matthew  11978: 
1.957     raeburn  11979: =item B<$last> Student's last name
1.286     matthew  11980: 
1.957     raeburn  11981: =item B<$gene> Student's generation
1.286     matthew  11982: 
1.957     raeburn  11983: =item B<$usec> Student's section in course
1.286     matthew  11984: 
                   11985: =item B<$end> Unix time of the roles expiration
                   11986: 
                   11987: =item B<$start> Unix time of the roles start date
                   11988: 
                   11989: =item B<$forceid> If defined, allow $uid to be changed
                   11990: 
                   11991: =item B<$desiredhome> server to use as home server for student
                   11992: 
1.957     raeburn  11993: =item B<$email> Student's permanent e-mail address
                   11994: 
                   11995: =item B<$type> Type of enrollment (auto or manual)
                   11996: 
1.963     raeburn  11997: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   11998: 
                   11999: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  12000: 
1.963     raeburn  12001: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  12002: 
1.963     raeburn  12003: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  12004: 
1.963     raeburn  12005: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  12006: 
1.286     matthew  12007: =back
1.297     matthew  12008: 
                   12009: =item *
                   12010: 
                   12011: modify_student_enrollment
                   12012: 
                   12013: Change a students enrollment status in a class.  The environment variable
                   12014: 'role.request.course' must be defined for this function to proceed.
                   12015: 
                   12016: Inputs:
                   12017: 
                   12018: =over 4
                   12019: 
                   12020: =item $udom, students domain
                   12021: 
                   12022: =item $uname, students name
                   12023: 
                   12024: =item $uid, students user id
                   12025: 
                   12026: =item $first, students first name
                   12027: 
                   12028: =item $middle
                   12029: 
                   12030: =item $last
                   12031: 
                   12032: =item $gene
                   12033: 
                   12034: =item $usec
                   12035: 
                   12036: =item $end
                   12037: 
                   12038: =item $start
                   12039: 
1.957     raeburn  12040: =item $type
                   12041: 
                   12042: =item $locktype
                   12043: 
                   12044: =item $cid
                   12045: 
                   12046: =item $selfenroll
                   12047: 
                   12048: =item $context
                   12049: 
1.297     matthew  12050: =back
                   12051: 
1.191     harris41 12052: 
                   12053: =item *
                   12054: 
1.243     albertel 12055: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   12056: custom role; give a custom role to a user for the level given by URL.  Specify
                   12057: name and domain of role author, and role name
1.191     harris41 12058: 
                   12059: =item *
                   12060: 
1.243     albertel 12061: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 12062: 
                   12063: =item *
                   12064: 
1.243     albertel 12065: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12066: 
                   12067: =back
                   12068: 
                   12069: =head2 Course Infomation
                   12070: 
                   12071: =over 4
1.191     harris41 12072: 
                   12073: =item *
                   12074: 
1.1118    foxr     12075: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12076: specified course id, including all environment settings for the
                   12077: course, the description of the course will be in the hash under the
                   12078: key 'description'
1.191     harris41 12079: 
1.1118    foxr     12080: $options is an optional parameter that if supplied is a hash reference that controls
                   12081: what how this function works.  It has the following key/values:
                   12082: 
                   12083: =over 4
                   12084: 
                   12085: =item freshen_cache
                   12086: 
                   12087: If defined, and the environment cache for the course is valid, it is 
                   12088: returned in the returned hash.
                   12089: 
                   12090: =item one_time
                   12091: 
                   12092: If defined, the last cache time is set to _now_
                   12093: 
                   12094: =item user
                   12095: 
                   12096: If defined, the supplied username is used instead of the current user.
                   12097: 
                   12098: 
                   12099: =back
                   12100: 
1.191     harris41 12101: =item *
                   12102: 
1.624     albertel 12103: resdata($name,$domain,$type,@which) : request for current parameter
                   12104: setting for a specific $type, where $type is either 'course' or 'user',
                   12105: @what should be a list of parameters to ask about. This routine caches
                   12106: answers for 5 minutes.
1.243     albertel 12107: 
1.877     foxr     12108: =item *
                   12109: 
                   12110: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12111: data base, returning a hash that is keyed by the resource name and has
                   12112: values that are the resource value.  I believe that the timestamps and
                   12113: versions are also returned.
                   12114: 
                   12115: 
1.243     albertel 12116: =back
                   12117: 
                   12118: =head2 Course Modification
                   12119: 
                   12120: =over 4
1.191     harris41 12121: 
                   12122: =item *
                   12123: 
1.243     albertel 12124: writecoursepref($courseid,%prefs) : write preferences (environment
                   12125: database) for a course
1.191     harris41 12126: 
                   12127: =item *
                   12128: 
1.1011    raeburn  12129: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12130: 
                   12131: =item *
                   12132: 
1.1038    raeburn  12133: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12134: 
1.1167    droeschl 12135: =item *
                   12136: 
                   12137: is_course($courseid), is_course($cdom, $cnum)
                   12138: 
                   12139: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12140: two component version $cdom, $cnum. It checks if the specified course exists.
                   12141: 
                   12142: Returns:
                   12143:     undef if the course doesn't exist, otherwise
                   12144:     in scalar context the combined courseid.
                   12145:     in list context the two components of the course identifier, domain and 
                   12146:     courseid.    
                   12147: 
1.243     albertel 12148: =back
                   12149: 
                   12150: =head2 Resource Subroutines
                   12151: 
                   12152: =over 4
1.191     harris41 12153: 
                   12154: =item *
                   12155: 
1.243     albertel 12156: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12157: 
                   12158: =item *
                   12159: 
1.243     albertel 12160: repcopy($filename) : subscribes to the requested file, and attempts to
                   12161: replicate from the owning library server, Might return
1.607     raeburn  12162: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12163: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12164: resource. Expects the local filesystem pathname
                   12165: (/home/httpd/html/res/....)
                   12166: 
                   12167: =back
                   12168: 
                   12169: =head2 Resource Information
                   12170: 
                   12171: =over 4
1.191     harris41 12172: 
                   12173: =item *
                   12174: 
1.243     albertel 12175: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12176: a vairety of different possible values, $varname should be a request
                   12177: string, and the other parameters can be used to specify who and what
                   12178: one is asking about.
                   12179: 
                   12180: Possible values for $varname are environment.lastname (or other item
                   12181: from the envirnment hash), user.name (or someother aspect about the
                   12182: user), resource.0.maxtries (or some other part and parameter of a
                   12183: resource)
1.204     albertel 12184: 
                   12185: =item *
                   12186: 
1.243     albertel 12187: directcondval($number) : get current value of a condition; reads from a state
                   12188: string
1.204     albertel 12189: 
                   12190: =item *
                   12191: 
1.243     albertel 12192: condval($condidx) : value of condition index based on state
1.204     albertel 12193: 
                   12194: =item *
                   12195: 
1.243     albertel 12196: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12197: resource's metadata, $what should be either a specific key, or either
                   12198: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12199: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12200: 
                   12201: this function automatically caches all requests
1.191     harris41 12202: 
                   12203: =item *
                   12204: 
1.243     albertel 12205: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12206: network of library servers; returns file handle of where SQL and regex results
                   12207: will be stored for query
1.191     harris41 12208: 
                   12209: =item *
                   12210: 
1.243     albertel 12211: symbread($filename) : return symbolic list entry (filename argument optional);
                   12212: returns the data handle
1.191     harris41 12213: 
                   12214: =item *
                   12215: 
1.243     albertel 12216: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 12217: a possible symb for the URL in $thisfn, and if is an encryypted
                   12218: resource that the user accessed using /enc/ returns a 1 on success, 0
                   12219: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 12220: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 12221: 
1.191     harris41 12222: 
                   12223: =item *
                   12224: 
1.243     albertel 12225: symbclean($symb) : removes versions numbers from a symb, returns the
                   12226: cleaned symb
1.191     harris41 12227: 
                   12228: =item *
                   12229: 
1.243     albertel 12230: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12231: course map, user must be in a course for it to work.
1.191     harris41 12232: 
                   12233: =item *
                   12234: 
1.243     albertel 12235: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12236: 
                   12237: =item *
                   12238: 
1.243     albertel 12239: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12240: a random seed, all arguments are optional, if they aren't sent it uses the
                   12241: environment to derive them. Note: if symb isn't sent and it can't get one
                   12242: from &symbread it will use the current time as its return value
1.191     harris41 12243: 
                   12244: =item *
                   12245: 
1.243     albertel 12246: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12247: unfakeable, receipt
1.191     harris41 12248: 
                   12249: =item *
                   12250: 
1.620     albertel 12251: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12252: 
                   12253: =item *
                   12254: 
1.243     albertel 12255: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12256: 
                   12257: =item *
                   12258: 
1.243     albertel 12259: 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 12260: 
                   12261: =item *
                   12262: 
1.243     albertel 12263: 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 12264: 
                   12265: =item *
                   12266: 
1.243     albertel 12267: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12268: 
                   12269: =item *
                   12270: 
1.243     albertel 12271: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12272: forcing spreadsheet to reevaluate the resource scores next time.
                   12273: 
                   12274: =back
                   12275: 
                   12276: =head2 Storing/Retreiving Data
                   12277: 
                   12278: =over 4
1.191     harris41 12279: 
                   12280: =item *
                   12281: 
1.243     albertel 12282: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12283: for this url; hashref needs to be given and should be a \%hashname; the
                   12284: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12285: be derived from the env
1.191     harris41 12286: 
                   12287: =item *
                   12288: 
1.243     albertel 12289: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12290: uses critical subroutine
1.191     harris41 12291: 
                   12292: =item *
                   12293: 
1.243     albertel 12294: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12295: all args are optional
1.191     harris41 12296: 
                   12297: =item *
                   12298: 
1.717     albertel 12299: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12300: dumps the complete (or key matching regexp) namespace into a hash
                   12301: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12302: normally &store()ed into
                   12303: 
                   12304: $range should be either an integer '100' (give me the first 100
                   12305:                                            matching records)
                   12306:               or be  two integers sperated by a - with no spaces
                   12307:                  '30-50' (give me the 30th through the 50th matching
                   12308:                           records)
                   12309: 
                   12310: 
                   12311: =item *
                   12312: 
                   12313: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12314: replaces a &store() version of data with a replacement set of data
                   12315: for a particular resource in a namespace passed in the $storehash hash 
                   12316: reference
                   12317: 
                   12318: =item *
                   12319: 
1.243     albertel 12320: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   12321: works very similar to store/cstore, but all data is stored in a
                   12322: temporary location and can be reset using tmpreset, $storehash should
                   12323: be a hash reference, returns nothing on success
1.191     harris41 12324: 
                   12325: =item *
                   12326: 
1.243     albertel 12327: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   12328: similar to restore, but all data is stored in a temporary location and
                   12329: can be reset using tmpreset. Returns a hash of values on success,
                   12330: error string otherwise.
1.191     harris41 12331: 
                   12332: =item *
                   12333: 
1.243     albertel 12334: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   12335: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 12336: 
                   12337: =item *
                   12338: 
1.243     albertel 12339: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12340: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 12341: 
                   12342: =item *
                   12343: 
1.243     albertel 12344: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   12345: namesp ($udom and $uname are optional)
1.191     harris41 12346: 
                   12347: =item *
                   12348: 
1.702     albertel 12349: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 12350: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 12351: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  12352: 
1.702     albertel 12353: $range should be either an integer '100' (give me the first 100
                   12354:                                            matching records)
                   12355:               or be  two integers sperated by a - with no spaces
                   12356:                  '30-50' (give me the 30th through the 50th matching
                   12357:                           records)
1.449     matthew  12358: =item *
                   12359: 
                   12360: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   12361: $store can be a scalar, an array reference, or if the amount to be 
                   12362: incremented is > 1, a hash reference.
                   12363: 
                   12364: ($udom and $uname are optional)
1.191     harris41 12365: 
                   12366: =item *
                   12367: 
1.243     albertel 12368: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   12369: ($udom and $uname are optional)
1.191     harris41 12370: 
                   12371: =item *
                   12372: 
1.243     albertel 12373: cput($namespace,$storehash,$udom,$uname) : critical put
                   12374: ($udom and $uname are optional)
1.191     harris41 12375: 
                   12376: =item *
                   12377: 
1.748     albertel 12378: newput($namespace,$storehash,$udom,$uname) :
                   12379: 
                   12380: Attempts to store the items in the $storehash, but only if they don't
                   12381: currently exist, if this succeeds you can be certain that you have 
                   12382: successfully created a new key value pair in the $namespace db.
                   12383: 
                   12384: 
                   12385: Args:
                   12386:  $namespace: name of database to store values to
                   12387:  $storehash: hashref to store to the db
                   12388:  $udom: (optional) domain of user containing the db
                   12389:  $uname: (optional) name of user caontaining the db
                   12390: 
                   12391: Returns:
                   12392:  'ok' -> succeeded in storing all keys of $storehash
                   12393:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   12394:                         least <key> already existed in the db (other
                   12395:                         requested keys may also already exist)
1.967     bisitz   12396:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 12397:  'con_lost' -> unable to contact request server
                   12398:  'refused' -> action was not allowed by remote machine
                   12399: 
                   12400: 
                   12401: =item *
                   12402: 
1.243     albertel 12403: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12404: reference filled in from namesp (encrypts the return communication)
                   12405: ($udom and $uname are optional)
1.191     harris41 12406: 
                   12407: =item *
                   12408: 
1.243     albertel 12409: log($udom,$name,$home,$message) : write to permanent log for user; use
                   12410: critical subroutine
                   12411: 
1.806     raeburn  12412: =item *
                   12413: 
1.860     raeburn  12414: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   12415: array reference filled in from namespace found in domain level on either
                   12416: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  12417: 
                   12418: =item *
                   12419: 
1.860     raeburn  12420: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   12421: domain level either on specified domain server ($uhome) or primary domain 
                   12422: server ($udom and $uhome are optional)
1.806     raeburn  12423: 
1.943     raeburn  12424: =item * 
                   12425: 
                   12426: get_domain_defaults($target_domain) : returns hash with defaults for
                   12427: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   12428: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   12429: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   12430: Values are retrieved from cache (if current), or from domain's configuration.db
                   12431: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   12432: or lonTabs/domain.tab. 
                   12433: 
                   12434: %domdefaults = &get_auth_defaults($target_domain);
                   12435: 
1.243     albertel 12436: =back
                   12437: 
                   12438: =head2 Network Status Functions
                   12439: 
                   12440: =over 4
1.191     harris41 12441: 
                   12442: =item *
                   12443: 
1.1137    raeburn  12444: dirlist() : return directory list based on URI (first arg).
                   12445: 
                   12446: Inputs: 1 required, 5 optional.
                   12447: 
                   12448: =over
                   12449: 
                   12450: =item 
                   12451: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   12452: 
                   12453: =item
                   12454: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   12455: 
                   12456: =item
                   12457: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   12458: 
                   12459: =item
                   12460: $getpropath - boolean: 1 if prepend path using &propath(). 
                   12461: 
                   12462: =item
                   12463: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   12464: 
                   12465: =item 
                   12466: $alternateRoot - path to prepend in place of path from $uri.
                   12467: 
                   12468: =back
                   12469: 
                   12470: Returns: Array of up to two items.
                   12471: 
                   12472: =over
                   12473: 
                   12474: a reference to an array of files/subdirectories
                   12475: 
                   12476: =over
                   12477: 
                   12478: Each element in the array of files/subdirectories is a & separated list of
                   12479: item name and the result of running stat on the item.  If dirlist was requested
                   12480: for a file instead of a directory, the item name will be ''. For a directory 
                   12481: listing, if the item is a metadata file, the element will end &N&M 
                   12482: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   12483: default copyright set (1).  
                   12484: 
                   12485: =back
                   12486: 
                   12487: a scalar containing error condition (if encountered).
                   12488: 
                   12489: =over
                   12490: 
                   12491: =item 
                   12492: no_host (no homeserver identified for $username:$domain).
                   12493: 
                   12494: =item 
                   12495: no_such_host (server contacted for listing not identified as valid host).
                   12496: 
                   12497: =item 
                   12498: con_lost (connection to remote server failed).
                   12499: 
                   12500: =item 
                   12501: refused (invalid $username:$domain received on lond side).
                   12502: 
                   12503: =item 
                   12504: no_such_dir (directory at specified path on lond side does not exist). 
                   12505: 
                   12506: =item 
                   12507: empty (directory at specified path on lond side is empty).
                   12508: 
                   12509: =over
                   12510: 
                   12511: This is currently not encountered because the &ls3, &ls2, 
                   12512: &ls (_handler) routines on the lond side do not filter out
                   12513: . and .. from a directory listing. 
                   12514: 
                   12515: =back
                   12516: 
                   12517: =back
                   12518: 
                   12519: =back
1.191     harris41 12520: 
                   12521: =item *
                   12522: 
1.243     albertel 12523: spareserver() : find server with least workload from spare.tab
                   12524: 
1.986     foxr     12525: 
                   12526: =item *
                   12527: 
                   12528: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   12529: if there is no corresponding loncapa host.
                   12530: 
1.243     albertel 12531: =back
                   12532: 
1.986     foxr     12533: 
1.243     albertel 12534: =head2 Apache Request
                   12535: 
                   12536: =over 4
1.191     harris41 12537: 
                   12538: =item *
                   12539: 
1.243     albertel 12540: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   12541: localhost, posts hash
                   12542: 
                   12543: =back
                   12544: 
                   12545: =head2 Data to String to Data
                   12546: 
                   12547: =over 4
1.191     harris41 12548: 
                   12549: =item *
                   12550: 
1.243     albertel 12551: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   12552: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 12553: 
                   12554: =item *
                   12555: 
1.243     albertel 12556: hashref2str($hashref) : convert a hashref into a string complete with
                   12557: escaping and '=' and '&' separators, supports elements that are
                   12558: arrayrefs and hashrefs
1.191     harris41 12559: 
                   12560: =item *
                   12561: 
1.243     albertel 12562: arrayref2str($arrayref) : convert an arrayref into a string complete
                   12563: with escaping and '&' separators, supports elements that are arrayrefs
                   12564: and hashrefs
1.191     harris41 12565: 
                   12566: =item *
                   12567: 
1.243     albertel 12568: str2hash($string) : convert string to hash using unescaping and
                   12569: splitting on '=' and '&', supports elements that are arrayrefs and
                   12570: hashrefs
1.191     harris41 12571: 
                   12572: =item *
                   12573: 
1.243     albertel 12574: str2array($string) : convert string to hash using unescaping and
                   12575: splitting on '&', supports elements that are arrayrefs and hashrefs
                   12576: 
                   12577: =back
                   12578: 
                   12579: =head2 Logging Routines
                   12580: 
                   12581: 
                   12582: These routines allow one to make log messages in the lonnet.log and
                   12583: lonnet.perm logfiles.
1.191     harris41 12584: 
1.1119    foxr     12585: =over 4
                   12586: 
1.191     harris41 12587: =item *
                   12588: 
1.243     albertel 12589: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 12590: 
                   12591: =item *
                   12592: 
1.243     albertel 12593: logthis() : append message to the normal lonnet.log file, it gets
                   12594: preiodically rolled over and deleted.
1.191     harris41 12595: 
                   12596: =item *
                   12597: 
1.243     albertel 12598: logperm() : append a permanent message to lonnet.perm.log, this log
                   12599: file never gets deleted by any automated portion of the system, only
                   12600: messages of critical importance should go in here.
                   12601: 
1.1119    foxr     12602: 
1.243     albertel 12603: =back
                   12604: 
                   12605: =head2 General File Helper Routines
                   12606: 
                   12607: =over 4
1.191     harris41 12608: 
                   12609: =item *
                   12610: 
1.481     raeburn  12611: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   12612: (a) files in /uploaded
                   12613:   (i) If a local copy of the file exists - 
                   12614:       compares modification date of local copy with last-modified date for 
                   12615:       definitive version stored on home server for course. If local copy is 
                   12616:       stale, requests a new version from the home server and stores it. 
                   12617:       If the original has been removed from the home server, then local copy 
                   12618:       is unlinked.
                   12619:   (ii) If local copy does not exist -
                   12620:       requests the file from the home server and stores it. 
                   12621:   
                   12622:   If $caller is 'uploadrep':  
                   12623:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   12624:     for request for files originally uploaded via DOCS. 
                   12625:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   12626:   
                   12627:   Otherwise:
                   12628:      This indicates a call from the content generation phase of the request.
                   12629:      -  returns the entire contents of the file or -1.
                   12630:      
                   12631: (b) files in /res
                   12632:    - returns the entire contents of a file or -1; 
                   12633:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 12634: 
1.712     albertel 12635: 
                   12636: =item *
                   12637: 
                   12638: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   12639:                   reference
                   12640: 
                   12641: returns either a stat() list of data about the file or an empty list
                   12642: if the file doesn't exist or couldn't find out about it (connection
                   12643: problems or user unknown)
                   12644: 
1.191     harris41 12645: =item *
                   12646: 
1.243     albertel 12647: filelocation($dir,$file) : returns file system location of a file
                   12648: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   12649: directory that relative $file lookups are to looked in ($dir of /a/dir
                   12650: and a file of ../bob will become /a/bob)
1.191     harris41 12651: 
                   12652: =item *
                   12653: 
                   12654: hreflocation($dir,$file) : returns file system location or a URL; same as
                   12655: filelocation except for hrefs
                   12656: 
                   12657: =item *
                   12658: 
                   12659: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   12660: 
1.243     albertel 12661: =back
                   12662: 
1.608     albertel 12663: =head2 Usererfile file routines (/uploaded*)
                   12664: 
                   12665: =over 4
                   12666: 
                   12667: =item *
                   12668: 
                   12669: userfileupload(): main rotine for putting a file in a user or course's
                   12670:                   filespace, arguments are,
                   12671: 
1.620     albertel 12672:  formname - required - this is the name of the element in $env where the
1.608     albertel 12673:            filename, and the contents of the file to create/modifed exist
1.620     albertel 12674:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   12675:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  12676:  context - if coursedoc, store the file in the course of the active role
                   12677:              of the current user; 
                   12678:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   12679:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 12680:  subdir - required - subdirectory to put the file in under ../userfiles/
                   12681:          if undefined, it will be placed in "unknown"
                   12682: 
                   12683:  (This routine calls clean_filename() to remove any dangerous
                   12684:  characters from the filename, and then calls finuserfileupload() to
                   12685:  complete the transaction)
                   12686: 
                   12687:  returns either the url of the uploaded file (/uploaded/....) if successful
                   12688:  and /adm/notfound.html if unsuccessful
                   12689: 
                   12690: =item *
                   12691: 
                   12692: clean_filename(): routine for cleaing a filename up for storage in
                   12693:                  userfile space, argument is:
                   12694: 
                   12695:  filename - proposed filename
                   12696: 
                   12697: returns: the new clean filename
                   12698: 
                   12699: =item *
                   12700: 
1.1090    raeburn  12701: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 12702: userspace, probably shouldn't be called directly
                   12703: 
                   12704:   docuname: username or courseid of destination for the file
                   12705:   docudom: domain of user/course of destination for the file
                   12706:   formname: same as for userfileupload()
1.1090    raeburn  12707:   fname: filename (including subdirectories) for the file
                   12708:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   12709:   allfiles: reference to hash used to store objects found by parser
                   12710:   codebase: reference to hash used for codebases of java objects found by parser
                   12711:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   12712:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   12713:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   12714:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   12715:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   12716:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  12717:   mimetype: reference to scalar to accommodate mime type determined
                   12718:             from File::MMagic if $parser = parse.
1.608     albertel 12719: 
                   12720:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  12721:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   12722:  was 'overwrite').
                   12723:  
1.608     albertel 12724: 
                   12725: =item *
                   12726: 
                   12727: renameuserfile(): renames an existing userfile to a new name
                   12728: 
                   12729:   Args:
                   12730:    docuname: username or courseid of destination for the file
                   12731:    docudom: domain of user/course of destination for the file
                   12732:    old: current file name (including any subdirs under userfiles)
                   12733:    new: desired file name (including any subdirs under userfiles)
                   12734: 
                   12735: =item *
                   12736: 
                   12737: mkdiruserfile(): creates a directory is a userfiles dir
                   12738: 
                   12739:   Args:
                   12740:    docuname: username or courseid of destination for the file
                   12741:    docudom: domain of user/course of destination for the file
                   12742:    dir: dir to create (including any subdirs under userfiles)
                   12743: 
                   12744: =item *
                   12745: 
                   12746: removeuserfile(): removes a file that exists in userfiles
                   12747: 
                   12748:   Args:
                   12749:    docuname: username or courseid of destination for the file
                   12750:    docudom: domain of user/course of destination for the file
                   12751:    fname: filname to delete (including any subdirs under userfiles)
                   12752: 
                   12753: =item *
                   12754: 
                   12755: removeuploadedurl(): convience function for removeuserfile()
                   12756: 
                   12757:   Args:
                   12758:    url:  a full /uploaded/... url to delete
                   12759: 
1.747     albertel 12760: =item * 
                   12761: 
                   12762: get_portfile_permissions():
                   12763:   Args:
                   12764:     domain: domain of user or course contain the portfolio files
                   12765:     user: name of user or num of course contain the portfolio files
                   12766:   Returns:
                   12767:     hashref of a dump of the proper file_permissions.db
                   12768:    
                   12769: 
                   12770: =item * 
                   12771: 
                   12772: get_access_controls():
                   12773: 
                   12774: Args:
                   12775:   current_permissions: the hash ref returned from get_portfile_permissions()
                   12776:   group: (optional) the group you want the files associated with
                   12777:   file: (optional) the file you want access info on
                   12778: 
                   12779: Returns:
1.749     raeburn  12780:     a hash (keys are file names) of hashes containing
                   12781:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   12782:         values are XML containing access control settings (see below) 
1.747     albertel 12783: 
                   12784: Internal notes:
                   12785: 
1.749     raeburn  12786:  access controls are stored in file_permissions.db as key=value pairs.
                   12787:     key -> path to file/file_name\0uniqueID:scope_end_start
                   12788:         where scope -> public,guest,course,group,domains or users.
                   12789:               end -> UNIX time for end of access (0 -> no end date)
                   12790:               start -> UNIX time for start of access
                   12791: 
                   12792:     value -> XML description of access control
                   12793:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   12794:             <start></start>
                   12795:             <end></end>
                   12796: 
                   12797:             <password></password>  for scope type = guest
                   12798: 
                   12799:             <domain></domain>     for scope type = course or group
                   12800:             <number></number>
                   12801:             <roles id="">
                   12802:              <role></role>
                   12803:              <access></access>
                   12804:              <section></section>
                   12805:              <group></group>
                   12806:             </roles>
                   12807: 
                   12808:             <dom></dom>         for scope type = domains
                   12809: 
                   12810:             <users>             for scope type = users
                   12811:              <user>
                   12812:               <uname></uname>
                   12813:               <udom></udom>
                   12814:              </user>
                   12815:             </users>
                   12816:            </scope> 
                   12817:               
                   12818:  Access data is also aggregated for each file in an additional key=value pair:
                   12819:  key -> path to file/file_name\0accesscontrol 
                   12820:  value -> reference to hash
                   12821:           hash contains key = value pairs
                   12822:           where key = uniqueID:scope_end_start
                   12823:                 value = UNIX time record was last updated
                   12824: 
                   12825:           Used to improve speed of look-ups of access controls for each file.  
                   12826:  
                   12827:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   12828: 
                   12829: modify_access_controls():
                   12830: 
                   12831: Modifies access controls for a portfolio file
                   12832: Args
                   12833: 1. file name
                   12834: 2. reference to hash of required changes,
                   12835: 3. domain
                   12836: 4. username
                   12837:   where domain,username are the domain of the portfolio owner 
                   12838:   (either a user or a course) 
                   12839: 
                   12840: Returns:
                   12841: 1. result of additions or updates ('ok' or 'error', with error message). 
                   12842: 2. result of deletions ('ok' or 'error', with error message).
                   12843: 3. reference to hash of any new or updated access controls.
                   12844: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   12845:    key = integer (inbound ID)
                   12846:    value = uniqueID  
1.747     albertel 12847: 
1.608     albertel 12848: =back
                   12849: 
1.243     albertel 12850: =head2 HTTP Helper Routines
                   12851: 
                   12852: =over 4
                   12853: 
1.191     harris41 12854: =item *
                   12855: 
                   12856: escape() : unpack non-word characters into CGI-compatible hex codes
                   12857: 
                   12858: =item *
                   12859: 
                   12860: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   12861: 
1.243     albertel 12862: =back
                   12863: 
                   12864: =head1 PRIVATE SUBROUTINES
                   12865: 
                   12866: =head2 Underlying communication routines (Shouldn't call)
                   12867: 
                   12868: =over 4
                   12869: 
                   12870: =item *
                   12871: 
                   12872: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   12873: 
                   12874: =item *
                   12875: 
                   12876: reply() : uses subreply to send a message to remote machine, logs all failures
                   12877: 
                   12878: =item *
                   12879: 
                   12880: critical() : passes a critical message to another server; if cannot
                   12881: get through then place message in connection buffer directory and
                   12882: returns con_delayed, if incapable of saving message, returns
                   12883: con_failed
                   12884: 
                   12885: =item *
                   12886: 
                   12887: reconlonc() : tries to reconnect lonc client processes.
                   12888: 
                   12889: =back
                   12890: 
                   12891: =head2 Resource Access Logging
                   12892: 
                   12893: =over 4
                   12894: 
                   12895: =item *
                   12896: 
                   12897: flushcourselogs() : flush (save) buffer logs and access logs
                   12898: 
                   12899: =item *
                   12900: 
                   12901: courselog($what) : save message for course in hash
                   12902: 
                   12903: =item *
                   12904: 
                   12905: courseacclog($what) : save message for course using &courselog().  Perform
                   12906: special processing for specific resource types (problems, exams, quizzes, etc).
                   12907: 
1.191     harris41 12908: =item *
                   12909: 
                   12910: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   12911: as a PerlChildExitHandler
1.243     albertel 12912: 
                   12913: =back
                   12914: 
                   12915: =head2 Other
                   12916: 
                   12917: =over 4
                   12918: 
                   12919: =item *
                   12920: 
                   12921: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 12922: 
                   12923: =back
                   12924: 
                   12925: =cut
1.877     foxr     12926: 

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