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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1290  ! raeburn     4: # $Id: lonnet.pm,v 1.1289 2015/06/16 20:24:59 damieng 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.1182    foxr       78: 
1.1173    foxr       79: use Encode;
                     80: 
1.1245    raeburn    81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     83:             %managerstab);
1.871     albertel   84: 
                     85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        88:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        89: 
1.1       albertel   90: use IO::Socket;
1.31      www        91: use GDBM_File;
1.208     albertel   92: use HTML::LCParser;
1.88      www        93: use Fcntl qw(:flock);
1.870     albertel   94: use Storable qw(thaw nfreeze);
1.1289    damieng    95: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   96: use Cache::Memcached;
1.676     albertel   97: use Digest::MD5;
1.790     albertel   98: use Math::Random;
1.1024    raeburn    99: use File::MMagic;
1.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1167    droeschl  103: use LONCAPA::Lond;
1.1117    foxr      104: 
1.1090    raeburn   105: use File::Copy;
1.676     albertel  106: 
1.195     www       107: my $readit;
1.1288    damieng   108: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  109: 
1.619     albertel  110: require Exporter;
                    111: 
                    112: our @ISA = qw (Exporter);
                    113: our @EXPORT = qw(%env);
                    114: 
1.449     matthew   115: 
1.1187    raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1187    raeburn   119:     sub write_log {
1.1188    raeburn   120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1184    raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1184    raeburn   130:         my $logentry = { 
                    131:                           $id => {
                    132:                                    'exe_uname' => $env{'user.name'},
                    133:                                    'exe_udom'  => $env{'user.domain'},
                    134:                                    'exe_time'  => $now,
                    135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    136:                                    'delflag'   => $delflag,
                    137:                                    'logentry'  => $storehash,
                    138:                                    'uname'     => $uname,
                    139:                                    'udom'      => $udom,
                    140:                                   }
                    141:                        };
                    142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       143:     }
                    144: }
1.1       albertel  145: 
1.163     harris41  146: sub logtouch {
                    147:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  148:     unless (-e "$execdir/logs/lonnet.log") {	
                    149: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  150: 	close $fh;
                    151:     }
                    152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    154: }
                    155: 
1.1       albertel  156: sub logthis {
                    157:     my $message=shift;
                    158:     my $execdir=$perlvar{'lonDaemons'};
                    159:     my $now=time;
                    160:     my $local=localtime($now);
1.448     albertel  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    163: 	print $fh $logstring;
1.448     albertel  164: 	close($fh);
                    165:     }
1.1       albertel  166:     return 1;
                    167: }
                    168: 
                    169: sub logperm {
                    170:     my $message=shift;
                    171:     my $execdir=$perlvar{'lonDaemons'};
                    172:     my $now=time;
                    173:     my $local=localtime($now);
1.448     albertel  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    175: 	print $fh "$now:$message:$local\n";
                    176: 	close($fh);
                    177:     }
1.1       albertel  178:     return 1;
                    179: }
                    180: 
1.850     albertel  181: sub create_connection {
1.853     albertel  182:     my ($hostname,$lonid) = @_;
1.851     albertel  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  184: 				     Type    => SOCK_STREAM,
                    185: 				     Timeout => 10);
                    186:     return 0 if (!$client);
1.890     albertel  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  188:     my $result = <$client>;
                    189:     chomp($result);
                    190:     return 1 if ($result eq 'done');
                    191:     return 0;
                    192: }
                    193: 
1.983     raeburn   194: sub get_server_timezone {
                    195:     my ($cnum,$cdom) = @_;
                    196:     my $home=&homeserver($cnum,$cdom);
                    197:     if ($home ne 'no_host') {
                    198:         my $cachetime = 24*3600;
                    199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    200:         if (defined($cached)) {
                    201:             return $timezone;
                    202:         } else {
                    203:             my $timezone = &reply('servertimezone',$home);
                    204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    205:         }
                    206:     }
                    207: }
1.850     albertel  208: 
1.1106    raeburn   209: sub get_server_distarch {
                    210:     my ($lonhost,$ignore_cache) = @_;
                    211:     if (defined($lonhost)) {
                    212:         if (!defined(&hostname($lonhost))) {
                    213:             return;
                    214:         }
                    215:         my $cachetime = 12*3600;
                    216:         if (!$ignore_cache) {
                    217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    218:             if (defined($cached)) {
                    219:                 return $distarch;
                    220:             }
                    221:         }
                    222:         my $rep = &reply('serverdistarch',$lonhost);
                    223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    225:                 $rep eq '') {
                    226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    227:         }
                    228:     }
                    229:     return;
                    230: }
                    231: 
1.993     raeburn   232: sub get_server_loncaparev {
1.1073    raeburn   233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   234:     if (defined($lonhost)) {
                    235:         if (!defined(&hostname($lonhost))) {
                    236:             undef($lonhost);
                    237:         }
                    238:     }
                    239:     if (!defined($lonhost)) {
                    240:         if (defined(&domain($dom,'primary'))) {
                    241:             $lonhost=&domain($dom,'primary');
                    242:             if ($lonhost eq 'no_host') {
                    243:                 undef($lonhost);
                    244:             }
                    245:         }
                    246:     }
                    247:     if (defined($lonhost)) {
1.1073    raeburn   248:         my $cachetime = 12*3600;
                    249:         if (!$ignore_cache) {
                    250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    251:             if (defined($cached)) {
                    252:                 return $loncaparev;
                    253:             }
                    254:         }
                    255:         my ($answer,$loncaparev);
                    256:         my @ids=&current_machine_ids();
                    257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    258:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   260:                 $loncaparev = $1;
                    261:             }
                    262:         } else {
                    263:             $answer = &reply('serverloncaparev',$lonhost);
                    264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    265:                 if ($caller eq 'loncron') {
                    266:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   267:                     $ua->timeout(4);
1.1073    raeburn   268:                     my $protocol = $protocol{$lonhost};
                    269:                     $protocol = 'http' if ($protocol ne 'https');
                    270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    271:                     my $request=new HTTP::Request('GET',$url);
                    272:                     my $response=$ua->request($request);
                    273:                     unless ($response->is_error()) {
                    274:                         my $content = $response->content;
1.1081    raeburn   275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   276:                             $loncaparev = $1;
                    277:                         }
                    278:                     }
                    279:                 } else {
                    280:                     $loncaparev = $loncaparevs{$lonhost};
                    281:                 }
1.1081    raeburn   282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   283:                 $loncaparev = $1;
                    284:             }
1.993     raeburn   285:         }
1.1073    raeburn   286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   287:     }
                    288: }
                    289: 
1.1074    raeburn   290: sub get_server_homeID {
                    291:     my ($hostname,$ignore_cache,$caller) = @_;
                    292:     unless ($ignore_cache) {
                    293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    294:         if (defined($cached)) {
                    295:             return $serverhomeID;
                    296:         }
                    297:     }
                    298:     my $cachetime = 12*3600;
                    299:     my $serverhomeID;
                    300:     if ($caller eq 'loncron') { 
                    301:         my @machine_ids = &machine_ids($hostname);
                    302:         foreach my $id (@machine_ids) {
                    303:             my $response = &reply('serverhomeID',$id);
                    304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    305:                 $serverhomeID = $response;
                    306:                 last;
                    307:             }
                    308:         }
                    309:         if ($serverhomeID eq '') {
                    310:             $serverhomeID = $machine_ids[-1];
                    311:         }
                    312:     } else {
                    313:         $serverhomeID = $serverhomeIDs{$hostname};
                    314:     }
                    315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    316: }
                    317: 
1.1121    raeburn   318: sub get_remote_globals {
                    319:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   320:     my ($result,%returnhash,%whatneeded);
                    321:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   322:         foreach my $what (sort(keys(%{$whathash}))) {
                    323:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   324:             my ($response,$cached);
1.1121    raeburn   325:             unless ($ignore_cache) {
1.1125    raeburn   326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   327:             }
                    328:             if (defined($cached)) {
1.1125    raeburn   329:                 $returnhash{$what} = $response;
1.1121    raeburn   330:             } else {
1.1125    raeburn   331:                 $whatneeded{$what} = 1;
1.1121    raeburn   332:             }
                    333:         }
1.1125    raeburn   334:         if (keys(%whatneeded) == 0) {
                    335:             $result = 'ok';
                    336:         } else {
1.1121    raeburn   337:             my $requested = &freeze_escape(\%whatneeded);
                    338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    340:                 ($rep eq 'unknown_cmd')) {
                    341:                 $result = $rep;
                    342:             } else {
                    343:                 $result = 'ok';
1.1121    raeburn   344:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   345:                 foreach my $item (@pairs) {
                    346:                     my ($key,$value)=split(/=/,$item,2);
                    347:                     my $what = &unescape($key);
                    348:                     my $hashid = $lonhost.'-'.$what;
                    349:                     $returnhash{$what}=&thaw_unescape($value);
                    350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   351:                 }
                    352:             }
                    353:         }
                    354:     }
1.1125    raeburn   355:     return ($result,\%returnhash);
1.1121    raeburn   356: }
                    357: 
1.1124    raeburn   358: sub remote_devalidate_cache {
1.1241    raeburn   359:     my ($lonhost,$cachekeys) = @_;
                    360:     my $items;
                    361:     return unless (ref($cachekeys) eq 'ARRAY');
                    362:     my $cachestr = join('&',@{$cachekeys});
                    363:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   364:     return $response;
                    365: }
                    366: 
1.1       albertel  367: # -------------------------------------------------- Non-critical communication
                    368: sub subreply {
                    369:     my ($cmd,$server)=@_;
1.838     albertel  370:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      371:     #
                    372:     #  With loncnew process trimming, there's a timing hole between lonc server
                    373:     #  process exit and the master server picking up the listen on the AF_UNIX
                    374:     #  socket.  In that time interval, a lock file will exist:
                    375: 
                    376:     my $lockfile=$peerfile.".lock";
                    377:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   378: 	sleep(0.1);
1.549     foxr      379:     }
                    380:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      381:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      382:     #
1.550     foxr      383:     #   We'll give the connection a few tries before abandoning it.  If
                    384:     #   connection is not possible, we'll con_lost back to the client.
                    385:     #   
                    386:     my $client;
                    387:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    388: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    389: 				      Type    => SOCK_STREAM,
                    390: 				      Timeout => 10);
1.869     albertel  391: 	if ($client) {
1.550     foxr      392: 	    last;		# Connected!
1.850     albertel  393: 	} else {
1.853     albertel  394: 	    &create_connection(&hostname($server),$server);
1.550     foxr      395: 	}
1.1289    damieng   396:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      397:     }
                    398:     my $answer;
                    399:     if ($client) {
1.704     albertel  400: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      401: 	$answer=<$client>;
                    402: 	if (!$answer) { $answer="con_lost"; }
                    403: 	chomp($answer);
                    404:     } else {
                    405: 	$answer = 'con_lost';	# Failed connection.
                    406:     }
1.1       albertel  407:     return $answer;
                    408: }
                    409: 
                    410: sub reply {
                    411:     my ($cmd,$server)=@_;
1.838     albertel  412:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  413:     my $answer=subreply($cmd,$server);
1.65      www       414:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  415:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       416:                 " $cmd to $server returned $answer</font>");
                    417:     }
1.1       albertel  418:     return $answer;
                    419: }
                    420: 
                    421: # ----------------------------------------------------------- Send USR1 to lonc
                    422: 
                    423: sub reconlonc {
1.891     albertel  424:     my ($lonid) = @_;
                    425:     my $hostname = &hostname($lonid);
                    426:     if ($lonid) {
                    427: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    428: 	if ($hostname && -e $peerfile) {
                    429: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    430: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    431: 					     Type    => SOCK_STREAM,
                    432: 					     Timeout => 10);
                    433: 	    if ($client) {
                    434: 		print $client ("reset_retries\n");
                    435: 		my $answer=<$client>;
                    436: 		#reset just this one.
                    437: 	    }
                    438: 	}
                    439: 	return;
                    440:     }
                    441: 
1.836     www       442:     &logthis("Trying to reconnect lonc");
1.1       albertel  443:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  444:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  445: 	my $loncpid=<$fh>;
                    446:         chomp($loncpid);
                    447:         if (kill 0 => $loncpid) {
                    448: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    449:             kill USR1 => $loncpid;
                    450:             sleep 1;
1.836     www       451:          } else {
1.12      www       452: 	    &logthis(
1.672     albertel  453:                "<font color=\"blue\">WARNING:".
1.12      www       454:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  455:         }
                    456:     } else {
1.836     www       457: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  458:     }
                    459: }
                    460: 
                    461: # ------------------------------------------------------ Critical communication
1.12      www       462: 
1.1       albertel  463: sub critical {
                    464:     my ($cmd,$server)=@_;
1.838     albertel  465:     unless (&hostname($server)) {
1.672     albertel  466:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       467:                " Critical message to unknown server ($server)</font>");
                    468:         return 'no_such_host';
                    469:     }
1.1       albertel  470:     my $answer=reply($cmd,$server);
                    471:     if ($answer eq 'con_lost') {
                    472: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  473: 	my $answer=reply($cmd,$server);
1.1       albertel  474:         if ($answer eq 'con_lost') {
                    475:             my $now=time;
                    476:             my $middlename=$cmd;
1.5       www       477:             $middlename=substr($middlename,0,16);
1.1       albertel  478:             $middlename=~s/\W//g;
                    479:             my $dfilename=
1.305     www       480:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    481:             $dumpcount++;
1.1       albertel  482:             {
1.448     albertel  483: 		my $dfh;
                    484: 		if (open($dfh,">$dfilename")) {
                    485: 		    print $dfh "$cmd\n"; 
                    486: 		    close($dfh);
                    487: 		}
1.1       albertel  488:             }
1.1288    damieng   489:             sleep 1;
1.1       albertel  490:             my $wcmd='';
                    491:             {
1.448     albertel  492: 		my $dfh;
                    493: 		if (open($dfh,"<$dfilename")) {
                    494: 		    $wcmd=<$dfh>; 
                    495: 		    close($dfh);
                    496: 		}
1.1       albertel  497:             }
                    498:             chomp($wcmd);
1.7       www       499:             if ($wcmd eq $cmd) {
1.672     albertel  500: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       501:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  502:                 &logperm("D:$server:$cmd");
                    503: 	        return 'con_delayed';
                    504:             } else {
1.672     albertel  505:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       506:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  507:                 &logperm("F:$server:$cmd");
                    508:                 return 'con_failed';
                    509:             }
                    510:         }
                    511:     }
                    512:     return $answer;
1.405     albertel  513: }
                    514: 
1.755     albertel  515: # ------------------------------------------- check if return value is an error
                    516: 
                    517: sub error {
                    518:     my ($result) = @_;
1.756     albertel  519:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  520: 	if ($2 == 2) { return undef; }
                    521: 	return $1;
                    522:     }
                    523:     return undef;
                    524: }
                    525: 
1.783     albertel  526: sub convert_and_load_session_env {
                    527:     my ($lonidsdir,$handle)=@_;
                    528:     my @profile;
                    529:     {
1.917     albertel  530: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    531: 	if (!$opened) {
1.915     albertel  532: 	    return 0;
                    533: 	}
1.783     albertel  534: 	flock($idf,LOCK_SH);
                    535: 	@profile=<$idf>;
                    536: 	close($idf);
                    537:     }
                    538:     my %temp_env;
                    539:     foreach my $line (@profile) {
1.786     albertel  540: 	if ($line !~ m/=/) {
                    541: 	    return 0;
                    542: 	}
1.783     albertel  543: 	chomp($line);
                    544: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    545: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    546:     }
                    547:     unlink("$lonidsdir/$handle.id");
                    548:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    549: 	    0640)) {
                    550: 	%disk_env = %temp_env;
                    551: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    552: 	untie(%disk_env);
                    553:     }
1.786     albertel  554:     return 1;
1.783     albertel  555: }
                    556: 
1.374     www       557: # ------------------------------------------- Transfer profile into environment
1.780     albertel  558: my $env_loaded;
                    559: sub transfer_profile_to_env {
1.788     albertel  560:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    561:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       562: 
1.720     albertel  563:     if (!defined($lonidsdir)) {
                    564: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    565:     }
                    566:     if (!defined($handle)) {
                    567:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    568:     }
                    569: 
1.786     albertel  570:     my $convert;
                    571:     {
1.917     albertel  572:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    573: 	if (!$opened) {
1.915     albertel  574: 	    return;
                    575: 	}
1.786     albertel  576: 	flock($idf,LOCK_SH);
                    577: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    578: 		&GDBM_READER(),0640)) {
                    579: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    580: 	    untie(%disk_env);
                    581: 	} else {
                    582: 	    $convert = 1;
                    583: 	}
                    584:     }
                    585:     if ($convert) {
                    586: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    587: 	    &logthis("Failed to load session, or convert session.");
                    588: 	}
1.374     www       589:     }
1.783     albertel  590: 
1.786     albertel  591:     my %remove;
1.783     albertel  592:     while ( my $envname = each(%env) ) {
1.433     matthew   593:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    594:             if ($time < time-300) {
1.783     albertel  595:                 $remove{$key}++;
1.433     matthew   596:             }
                    597:         }
                    598:     }
1.783     albertel  599: 
1.619     albertel  600:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  601:     $env_loaded=1;
1.783     albertel  602:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   603:         &delenv($expired_key);
1.374     www       604:     }
1.1       albertel  605: }
                    606: 
1.916     albertel  607: # ---------------------------------------------------- Check for valid session 
                    608: sub check_for_valid_session {
1.1245    raeburn   609:     my ($r,$name,$userhashref) = @_;
1.916     albertel  610:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   611:     if ($name eq '') {
                    612:         $name = 'lonID';
                    613:     }
                    614:     my $lonid=$cookies{$name};
1.916     albertel  615:     return undef if (!$lonid);
                    616: 
                    617:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   618:     my $lonidsdir;
                    619:     if ($name eq 'lonDAV') {
                    620:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    621:     } else {
                    622:         $lonidsdir=$r->dir_config('lonIDsDir');
                    623:     }
1.916     albertel  624:     return undef if (!-e "$lonidsdir/$handle.id");
                    625: 
1.917     albertel  626:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    627:     return undef if (!$opened);
1.916     albertel  628: 
                    629:     flock($idf,LOCK_SH);
                    630:     my %disk_env;
                    631:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    632: 	    &GDBM_READER(),0640)) {
                    633: 	return undef;	
                    634:     }
                    635: 
                    636:     if (!defined($disk_env{'user.name'})
                    637: 	|| !defined($disk_env{'user.domain'})) {
                    638: 	return undef;
                    639:     }
1.1245    raeburn   640: 
                    641:     if (ref($userhashref) eq 'HASH') {
                    642:         $userhashref->{'name'} = $disk_env{'user.name'};
                    643:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212    raeburn   644:     }
1.1245    raeburn   645: 
1.916     albertel  646:     return $handle;
                    647: }
                    648: 
1.830     albertel  649: sub timed_flock {
                    650:     my ($file,$lock_type) = @_;
                    651:     my $failed=0;
                    652:     eval {
                    653: 	local $SIG{__DIE__}='DEFAULT';
                    654: 	local $SIG{ALRM}=sub {
                    655: 	    $failed=1;
                    656: 	    die("failed lock");
                    657: 	};
                    658: 	alarm(13);
                    659: 	flock($file,$lock_type);
                    660: 	alarm(0);
                    661:     };
                    662:     if ($failed) {
                    663: 	return undef;
                    664:     } else {
                    665: 	return 1;
                    666:     }
                    667: }
                    668: 
1.5       www       669: # ---------------------------------------------------------- Append Environment
                    670: 
                    671: sub appenv {
1.949     raeburn   672:     my ($newenv,$roles) = @_;
                    673:     if (ref($newenv) eq 'HASH') {
                    674:         foreach my $key (keys(%{$newenv})) {
                    675:             my $refused = 0;
                    676: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    677:                 $refused = 1;
                    678:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   679:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   680:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    681:                         $refused = 0;
                    682:                     }
                    683:                 }
                    684:             }
                    685:             if ($refused) {
                    686:                 &logthis("<font color=\"blue\">WARNING: ".
                    687:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    688:                          .'</font>');
                    689: 	        delete($newenv->{$key});
                    690:             } else {
                    691:                 $env{$key}=$newenv->{$key};
                    692:             }
                    693:         }
                    694:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    695:         if ($opened
                    696: 	    && &timed_flock($env_file,LOCK_EX)
                    697: 	    &&
                    698: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    699: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    700: 	    while (my ($key,$value) = each(%{$newenv})) {
                    701: 	        $disk_env{$key} = $value;
                    702: 	    }
                    703: 	    untie(%disk_env);
1.35      www       704:         }
1.191     harris41  705:     }
1.56      www       706:     return 'ok';
                    707: }
                    708: # ----------------------------------------------------- Delete from Environment
                    709: 
                    710: sub delenv {
1.1104    raeburn   711:     my ($delthis,$regexp,$roles) = @_;
                    712:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    713:         my $refused = 1;
                    714:         if (ref($roles) eq 'ARRAY') {
                    715:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    716:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    717:                 $refused = 0;
                    718:             }
                    719:         }
                    720:         if ($refused) {
                    721:             &logthis("<font color=\"blue\">WARNING: ".
                    722:                      "Attempt to delete from environment ".$delthis);
                    723:             return 'error';
                    724:         }
1.56      www       725:     }
1.917     albertel  726:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    727:     if ($opened
1.915     albertel  728: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  729: 	&&
                    730: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    731: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  732: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   733: 	    if ($regexp) {
                    734:                 if ($key=~/^$delthis/) {
                    735:                     delete($env{$key});
                    736:                     delete($disk_env{$key});
                    737:                 } 
                    738:             } else {
                    739:                 if ($key=~/^\Q$delthis\E/) {
                    740: 		    delete($env{$key});
                    741: 		    delete($disk_env{$key});
                    742: 	        }
                    743:             }
1.448     albertel  744: 	}
1.783     albertel  745: 	untie(%disk_env);
1.5       www       746:     }
                    747:     return 'ok';
1.369     albertel  748: }
                    749: 
1.790     albertel  750: sub get_env_multiple {
                    751:     my ($name) = @_;
                    752:     my @values;
                    753:     if (defined($env{$name})) {
                    754:         # exists is it an array
                    755:         if (ref($env{$name})) {
                    756:             @values=@{ $env{$name} };
                    757:         } else {
                    758:             $values[0]=$env{$name};
                    759:         }
                    760:     }
                    761:     return(@values);
                    762: }
                    763: 
1.958     www       764: # ------------------------------------------------------------------- Locking
                    765: 
                    766: sub set_lock {
                    767:     my ($text)=@_;
                    768:     $locknum++;
                    769:     my $id=$$.'-'.$locknum;
                    770:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    771:              'session.lock.'.$id => $text});
                    772:     return $id;
                    773: }
                    774: 
                    775: sub get_locks {
                    776:     my $num=0;
                    777:     my %texts=();
                    778:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    779:        if ($lock=~/\w/) {
                    780:           $num++;
                    781:           $texts{$lock}=$env{'session.lock.'.$lock};
                    782:        }
                    783:    }
                    784:    return ($num,%texts);
                    785: }
                    786: 
                    787: sub remove_lock {
                    788:     my ($id)=@_;
                    789:     my $newlocks='';
                    790:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    791:        if (($lock=~/\w/) && ($lock ne $id)) {
                    792:           $newlocks.=','.$lock;
                    793:        }
                    794:     }
                    795:     &appenv({'session.locks' => $newlocks});
                    796:     &delenv('session.lock.'.$id);
                    797: }
                    798: 
                    799: sub remove_all_locks {
                    800:     my $activelocks=$env{'session.locks'};
                    801:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    802:        if ($lock=~/\w/) {
                    803:           &remove_lock($lock);
                    804:        }
                    805:     }
                    806: }
                    807: 
                    808: 
1.369     albertel  809: # ------------------------------------------ Find out current server userload
                    810: sub userload {
                    811:     my $numusers=0;
                    812:     {
                    813: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    814: 	my $filename;
                    815: 	my $curtime=time;
                    816: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  817: 	    next if ($filename eq '.' || $filename eq '..');
                    818: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  819: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  820: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  821: 	}
                    822: 	closedir(LONIDS);
                    823:     }
                    824:     my $userloadpercent=0;
                    825:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    826:     if ($maxuserload) {
1.371     albertel  827: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  828:     }
1.372     albertel  829:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  830:     return $userloadpercent;
1.283     www       831: }
                    832: 
1.1       albertel  833: # ------------------------------ Find server with least workload from spare.tab
1.11      www       834: 
1.1       albertel  835: sub spareserver {
1.1083    raeburn   836:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  837:     my $spare_server;
1.370     albertel  838:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  839:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    840:                                                      :  $userloadpercent;
1.1083    raeburn   841:     my ($uint_dom,$remotesessions);
                    842:     if (($udom ne '') && (&domain($udom) ne '')) {
                    843:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    844:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    845:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    846:         $remotesessions = $udomdefaults{'remotesessions'};
                    847:     }
1.1123    raeburn   848:     my $spareshash = &this_host_spares($udom);
                    849:     if (ref($spareshash) eq 'HASH') {
                    850:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    851:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   852:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    853:                                              $try_server));
1.1123    raeburn   854: 	        ($spare_server, $lowest_load) =
                    855: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    856:             }
1.1083    raeburn   857:         }
1.784     albertel  858: 
1.1123    raeburn   859:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    860: 
                    861:         if (!$found_server) {
                    862:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    863: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   864:                     next unless (&spare_can_host($udom,$uint_dom,
                    865:                                                  $remotesessions,$try_server));
1.1123    raeburn   866: 	            ($spare_server, $lowest_load) =
                    867: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    868:                 }
                    869: 	    }
                    870:         }
1.784     albertel  871:     }
                    872: 
                    873:     if (!$want_server_name) {
1.968     raeburn   874:         my $protocol = 'http';
                    875:         if ($protocol{$spare_server} eq 'https') {
                    876:             $protocol = $protocol{$spare_server};
                    877:         }
1.1001    raeburn   878:         if (defined($spare_server)) {
                    879:             my $hostname = &hostname($spare_server);
1.1083    raeburn   880:             if (defined($hostname)) {
1.1001    raeburn   881: 	        $spare_server = $protocol.'://'.$hostname;
                    882:             }
                    883:         }
1.784     albertel  884:     }
                    885:     return $spare_server;
                    886: }
                    887: 
                    888: sub compare_server_load {
1.1253    raeburn   889:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    890: 
                    891:     if ($required) {
                    892:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    893:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    894:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    895:         if (($major eq '' && $minor eq '') ||
                    896:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    897:             return ($spare_server,$lowest_load);
                    898:         }
                    899:     }
1.784     albertel  900: 
                    901:     my $loadans     = &reply('load',    $try_server);
                    902:     my $userloadans = &reply('userload',$try_server);
                    903: 
                    904:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   905: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  906:     }
                    907: 
                    908:     my $load;
                    909:     if ($loadans =~ /\d/) {
                    910: 	if ($userloadans =~ /\d/) {
                    911: 	    #both are numbers, pick the bigger one
                    912: 	    $load = ($loadans > $userloadans) ? $loadans 
                    913: 		                              : $userloadans;
1.411     albertel  914: 	} else {
1.784     albertel  915: 	    $load = $loadans;
1.411     albertel  916: 	}
1.784     albertel  917:     } else {
                    918: 	$load = $userloadans;
                    919:     }
                    920: 
                    921:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    922: 	$spare_server = $try_server;
                    923: 	$lowest_load  = $load;
1.370     albertel  924:     }
1.784     albertel  925:     return ($spare_server,$lowest_load);
1.202     matthew   926: }
1.914     albertel  927: 
                    928: # --------------------------- ask offload servers if user already has a session
                    929: sub find_existing_session {
                    930:     my ($udom,$uname) = @_;
1.1123    raeburn   931:     my $spareshash = &this_host_spares($udom);
                    932:     if (ref($spareshash) eq 'HASH') {
                    933:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    934:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    936:             }
                    937:         }
                    938:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    939:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    940:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    941:             }
                    942:         }
1.914     albertel  943:     }
                    944:     return;
                    945: }
                    946: 
                    947: # -------------------------------- ask if server already has a session for user
                    948: sub has_user_session {
                    949:     my ($lonid,$udom,$uname) = @_;
                    950:     my $result = &reply(join(':','userhassession',
                    951: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    952:     return 1 if ($result eq 'ok');
                    953: 
                    954:     return 0;
                    955: }
                    956: 
1.1076    raeburn   957: # --------- determine least loaded server in a user's domain which allows login
                    958: 
                    959: sub choose_server {
1.1259    raeburn   960:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn   961:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   962:     my %servers = &get_servers($udom);
1.1076    raeburn   963:     my $lowest_load = 30000;
1.1259    raeburn   964:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                    965:     if ($skiploadbal) {
                    966:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                    967:         unless (defined($cached)) {
                    968:             my $cachetime = 60*60*24;
                    969:             my %domconfig =
                    970:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                    971:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                    972:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                    973:                                            $cachetime);
                    974:             }
                    975:         }
                    976:     }
1.1076    raeburn   977:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn   978:         if ($skiploadbal) {
                    979:             if (ref($balancers) eq 'HASH') {
                    980:                 next if (exists($balancers->{$lonhost}));
                    981:             }
                    982:         }   
1.1115    raeburn   983:         my $loginvia;
                    984:         if ($checkloginvia) {
                    985:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   986:             if ($loginvia) {
                    987:                 my ($server,$path) = split(/:/,$loginvia);
                    988:                 ($login_host, $lowest_load) =
1.1253    raeburn   989:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn   990:                 if ($login_host eq $server) {
                    991:                     $portal_path = $path;
1.1151    raeburn   992:                     $isredirect = 1;
1.1116    raeburn   993:                 }
                    994:             } else {
                    995:                 ($login_host, $lowest_load) =
1.1253    raeburn   996:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn   997:                 if ($login_host eq $lonhost) {
                    998:                     $portal_path = '';
1.1151    raeburn   999:                     $isredirect = ''; 
1.1116    raeburn  1000:                 }
                   1001:             }
                   1002:         } else {
1.1076    raeburn  1003:             ($login_host, $lowest_load) =
1.1253    raeburn  1004:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1005:         }
                   1006:     }
                   1007:     if ($login_host ne '') {
1.1116    raeburn  1008:         $hostname = &hostname($login_host);
1.1076    raeburn  1009:     }
1.1151    raeburn  1010:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn  1011: }
                   1012: 
1.202     matthew  1013: # --------------------------------------------- Try to change a user's password
                   1014: 
                   1015: sub changepass {
1.799     raeburn  1016:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1017:     $currentpass = &escape($currentpass);
                   1018:     $newpass     = &escape($newpass);
1.1030    raeburn  1019:     my $lonhost = $perlvar{'lonHostID'};
                   1020:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1021: 		       $server);
                   1022:     if (! $answer) {
                   1023: 	&logthis("No reply on password change request to $server ".
                   1024: 		 "by $uname in domain $udom.");
                   1025:     } elsif ($answer =~ "^ok") {
                   1026:         &logthis("$uname in $udom successfully changed their password ".
                   1027: 		 "on $server.");
                   1028:     } elsif ($answer =~ "^pwchange_failure") {
                   1029: 	&logthis("$uname in $udom was unable to change their password ".
                   1030: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1031: 		 "or pwchange");
                   1032:     } elsif ($answer =~ "^non_authorized") {
                   1033:         &logthis("$uname in $udom did not get their password correct when ".
                   1034: 		 "attempting to change it on $server.");
                   1035:     } elsif ($answer =~ "^auth_mode_error") {
                   1036:         &logthis("$uname in $udom attempted to change their password despite ".
                   1037: 		 "not being locally or internally authenticated on $server.");
                   1038:     } elsif ($answer =~ "^unknown_user") {
                   1039:         &logthis("$uname in $udom attempted to change their password ".
                   1040: 		 "on $server but were unable to because $server is not ".
                   1041: 		 "their home server.");
                   1042:     } elsif ($answer =~ "^refused") {
                   1043: 	&logthis("$server refused to change $uname in $udom password because ".
                   1044: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1045:     } elsif ($answer =~ "invalid_client") {
                   1046:         &logthis("$server refused to change $uname in $udom password because ".
                   1047:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1048:     }
                   1049:     return $answer;
1.1       albertel 1050: }
                   1051: 
1.169     harris41 1052: # ----------------------- Try to determine user's current authentication scheme
                   1053: 
                   1054: sub queryauthenticate {
                   1055:     my ($uname,$udom)=@_;
1.456     albertel 1056:     my $uhome=&homeserver($uname,$udom);
                   1057:     if (!$uhome) {
                   1058: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1059: 	return 'no_host';
                   1060:     }
                   1061:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1062:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1063: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1064:     }
1.456     albertel 1065:     return $answer;
1.169     harris41 1066: }
                   1067: 
1.1       albertel 1068: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1069: 
1.1       albertel 1070: sub authenticate {
1.1073    raeburn  1071:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1072:     $upass=&escape($upass);
                   1073:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1074:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1075:     my $newhome;
1.836     www      1076:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1077: # Maybe the machine was offline and only re-appeared again recently?
                   1078:         &reconlonc();
                   1079: # One more
1.952     raeburn  1080: 	$uhome=&homeserver($uname,$udom,1);
                   1081:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1082:             if (defined(&domain($udom,'primary'))) {
                   1083:                 $newhome=&domain($udom,'primary');
                   1084:             }
                   1085:             if ($newhome ne '') {
                   1086:                 $uhome = $newhome;
                   1087:             }
                   1088:         }
1.836     www      1089: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1090: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1091: 	    return 'no_host';
                   1092:         }
1.1       albertel 1093:     }
1.1073    raeburn  1094:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1095:     if ($answer eq 'authorized') {
1.952     raeburn  1096:         if ($newhome) {
                   1097:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1098:             return 'no_account_on_host'; 
                   1099:         } else {
                   1100:             &logthis("User $uname at $udom authorized by $uhome");
                   1101:             return $uhome;
                   1102:         }
1.471     albertel 1103:     }
                   1104:     if ($answer eq 'non_authorized') {
                   1105: 	&logthis("User $uname at $udom rejected by $uhome");
                   1106: 	return 'no_host'; 
1.9       www      1107:     }
1.471     albertel 1108:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1109:     return 'no_host';
                   1110: }
                   1111: 
1.1073    raeburn  1112: sub can_host_session {
1.1074    raeburn  1113:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1114:     my $canhost = 1;
1.1074    raeburn  1115:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1116:     if (ref($remotesessions) eq 'HASH') {
                   1117:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1118:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1119:                 $canhost = 0;
                   1120:             } else {
                   1121:                 $canhost = 1;
                   1122:             }
                   1123:         }
                   1124:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1125:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1126:                 $canhost = 1;
                   1127:             } else {
                   1128:                 $canhost = 0;
                   1129:             }
                   1130:         }
                   1131:         if ($canhost) {
                   1132:             if ($remotesessions->{'version'} ne '') {
                   1133:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1134:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1135:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1136:                         my $major = $1;
                   1137:                         my $minor = $2;
                   1138:                         if (($major < $reqmajor ) ||
                   1139:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1140:                             $canhost = 0;
                   1141:                         }
                   1142:                     } else {
                   1143:                         $canhost = 0;
                   1144:                     }
                   1145:                 }
                   1146:             }
                   1147:         }
                   1148:     }
                   1149:     if ($canhost) {
                   1150:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1151:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1152:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1153:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1154:                 if (($uint_dom ne '') && 
                   1155:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1156:                     $canhost = 0;
                   1157:                 } else {
                   1158:                     $canhost = 1;
                   1159:                 }
                   1160:             }
                   1161:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1162:                 if (($uint_dom ne '') && 
                   1163:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1164:                     $canhost = 1;
                   1165:                 } else {
                   1166:                     $canhost = 0;
                   1167:                 }
                   1168:             }
                   1169:         }
                   1170:     }
                   1171:     return $canhost;
                   1172: }
                   1173: 
1.1083    raeburn  1174: sub spare_can_host {
                   1175:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1176:     my $canhost=1;
1.1279    raeburn  1177:     my $try_server_hostname = &hostname($try_server);
                   1178:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1179:     my $serverhomedom = &host_domain($serverhomeID);
                   1180:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1181:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1182:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1183:             $canhost = 0;
                   1184:         }
                   1185:     }
                   1186:     if (($canhost) && ($uint_dom)) {
                   1187:         my @intdoms;
                   1188:         my $internet_names = &get_internet_names($try_server);
                   1189:         if (ref($internet_names) eq 'ARRAY') {
                   1190:             @intdoms = @{$internet_names};
                   1191:         }
                   1192:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1193:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1194:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1195:                                          $remotesessions,
                   1196:                                          $defdomdefaults{'hostedsessions'});
                   1197:         }
1.1083    raeburn  1198:     }
                   1199:     return $canhost;
                   1200: }
                   1201: 
1.1123    raeburn  1202: sub this_host_spares {
                   1203:     my ($dom) = @_;
1.1126    raeburn  1204:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1205:     my @hosts = &current_machine_ids();
                   1206:     foreach my $lonhost (@hosts) {
                   1207:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1208:             $dom_in_use = $dom;
                   1209:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1210:             last;
                   1211:         }
                   1212:     }
1.1126    raeburn  1213:     if ($dom_in_use ne '') {
                   1214:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1215:     }
                   1216:     if (ref($result) ne 'HASH') {
                   1217:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1218:         $dom_in_use = &host_domain($lonhost_in_use);
                   1219:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1220:         if (ref($result) ne 'HASH') {
                   1221:             $result = \%spareid;
                   1222:         }
                   1223:     }
                   1224:     return $result;
                   1225: }
                   1226: 
                   1227: sub spares_for_offload  {
                   1228:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1229:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1230:     if (defined($cached)) {
                   1231:         return $result;
                   1232:     } else {
1.1126    raeburn  1233:         my $cachetime = 60*60*24;
                   1234:         my %domconfig =
                   1235:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1236:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1237:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1238:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1239:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1240:                 }
                   1241:             }
                   1242:         }
                   1243:     }
1.1126    raeburn  1244:     return;
1.1123    raeburn  1245: }
                   1246: 
1.1129    raeburn  1247: sub get_lonbalancer_config {
                   1248:     my ($servers) = @_;
                   1249:     my ($currbalancer,$currtargets);
                   1250:     if (ref($servers) eq 'HASH') {
                   1251:         foreach my $server (keys(%{$servers})) {
                   1252:             my %what = (
                   1253:                          spareid => 1,
                   1254:                          perlvar => 1,
                   1255:                        );
                   1256:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1257:             if ($result eq 'ok') {
                   1258:                 if (ref($returnhash) eq 'HASH') {
                   1259:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1260:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1261:                             $currbalancer = $server;
                   1262:                             $currtargets = {};
                   1263:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1264:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1265:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1266:                                 }
                   1267:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1268:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1269:                                 }
                   1270:                             }
                   1271:                             last;
                   1272:                         }
                   1273:                     }
                   1274:                 }
                   1275:             }
                   1276:         }
                   1277:     }
                   1278:     return ($currbalancer,$currtargets);
                   1279: }
                   1280: 
                   1281: sub check_loadbalancing {
                   1282:     my ($uname,$udom) = @_;
1.1191    raeburn  1283:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1284:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1285:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1286:     my @hosts = &current_machine_ids();
1.1129    raeburn  1287:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1288:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1289:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1290:     my $serverhomedom = &host_domain($lonhost);
                   1291: 
                   1292:     my $cachetime = 60*60*24;
                   1293: 
                   1294:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1295:         $dom_in_use = $udom;
                   1296:         $homeintdom = 1;
                   1297:     } else {
                   1298:         $dom_in_use = $serverhomedom;
                   1299:     }
                   1300:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1301:     unless (defined($cached)) {
                   1302:         my %domconfig =
                   1303:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1304:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1305:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1306:         }
                   1307:     }
                   1308:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1309:         ($is_balancer,$currtargets,$currrules) = 
                   1310:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1311:         if ($is_balancer) {
                   1312:             if (ref($currrules) eq 'HASH') {
                   1313:                 if ($homeintdom) {
                   1314:                     if ($uname ne '') {
                   1315:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1316:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1317:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1318:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1319:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1320:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1321:                             }
                   1322:                         }
                   1323:                         if ($rule_in_effect eq '') {
                   1324:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1325:                             if ($userenv{'inststatus'} ne '') {
                   1326:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1327:                                 my ($othertitle,$usertypes,$types) =
                   1328:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1329:                                 if (ref($types) eq 'ARRAY') {
                   1330:                                     foreach my $type (@{$types}) {
                   1331:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1332:                                             if (exists($currrules->{$type})) {
                   1333:                                                 $rule_in_effect = $currrules->{$type};
                   1334:                                             }
                   1335:                                         }
                   1336:                                     }
                   1337:                                 }
                   1338:                             } else {
                   1339:                                 if (exists($currrules->{'default'})) {
                   1340:                                     $rule_in_effect = $currrules->{'default'};
                   1341:                                 }
                   1342:                             }
                   1343:                         }
                   1344:                     } else {
                   1345:                         if (exists($currrules->{'default'})) {
                   1346:                             $rule_in_effect = $currrules->{'default'};
                   1347:                         }
                   1348:                     }
                   1349:                 } else {
                   1350:                     if ($currrules->{'_LC_external'} ne '') {
                   1351:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1352:                     }
                   1353:                 }
                   1354:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1355:                                                        $uname,$udom);
                   1356:             }
                   1357:         }
                   1358:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1359:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1360:         unless (defined($cached)) {
                   1361:             my %domconfig =
                   1362:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1363:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1364:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1365:             }
                   1366:         }
                   1367:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1368:             ($is_balancer,$currtargets,$currrules) = 
                   1369:                 &check_balancer_result($result,@hosts);
                   1370:             if ($is_balancer) {
1.1129    raeburn  1371:                 if (ref($currrules) eq 'HASH') {
                   1372:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1373:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1374:                     }
                   1375:                 }
                   1376:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1377:                                                        $uname,$udom);
                   1378:             }
                   1379:         } else {
                   1380:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1381:                 $is_balancer = 1;
                   1382:                 $offloadto = &this_host_spares($dom_in_use);
                   1383:             }
                   1384:         }
                   1385:     } else {
                   1386:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1387:             $is_balancer = 1;
                   1388:             $offloadto = &this_host_spares($dom_in_use);
                   1389:         }
                   1390:     }
1.1176    raeburn  1391:     if ($is_balancer) {
                   1392:         my $lowest_load = 30000;
                   1393:         if (ref($offloadto) eq 'HASH') {
                   1394:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1395:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1396:                     ($otherserver,$lowest_load) =
                   1397:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1398:                 }
1.1129    raeburn  1399:             }
1.1176    raeburn  1400:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1401: 
1.1176    raeburn  1402:             if (!$found_server) {
                   1403:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1404:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1405:                         ($otherserver,$lowest_load) =
                   1406:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1407:                     }
                   1408:                 }
                   1409:             }
                   1410:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1411:             if (@{$offloadto} == 1) {
                   1412:                 $otherserver = $offloadto->[0];
                   1413:             } elsif (@{$offloadto} > 1) {
                   1414:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1415:                     ($otherserver,$lowest_load) =
                   1416:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1417:                 }
                   1418:             }
                   1419:         }
1.1176    raeburn  1420:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1421:             $is_balancer = 0;
                   1422:             if ($uname ne '' && $udom ne '') {
                   1423:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1424:                     
                   1425:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1426:                              'user.loadbalcheck.time' => time});
                   1427:                 }
1.1129    raeburn  1428:             }
                   1429:         }
                   1430:     }
                   1431:     return ($is_balancer,$otherserver);
                   1432: }
                   1433: 
1.1191    raeburn  1434: sub check_balancer_result {
                   1435:     my ($result,@hosts) = @_;
                   1436:     my ($is_balancer,$currtargets,$currrules);
                   1437:     if (ref($result) eq 'HASH') {
                   1438:         if ($result->{'lonhost'} ne '') {
                   1439:             my $currbalancer = $result->{'lonhost'};
                   1440:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1441:                 $is_balancer = 1;
                   1442:                 $currtargets = $result->{'targets'};
                   1443:                 $currrules = $result->{'rules'};
                   1444:             }
                   1445:         } else {
                   1446:             foreach my $key (keys(%{$result})) {
                   1447:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1448:                     (ref($result->{$key}) eq 'HASH')) {
                   1449:                     $is_balancer = 1;
                   1450:                     $currrules = $result->{$key}{'rules'};
                   1451:                     $currtargets = $result->{$key}{'targets'};
                   1452:                     last;
                   1453:                 }
                   1454:             }
                   1455:         }
                   1456:     }
                   1457:     return ($is_balancer,$currtargets,$currrules);
                   1458: }
                   1459: 
1.1129    raeburn  1460: sub get_loadbalancer_targets {
                   1461:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1462:     my $offloadto;
1.1175    raeburn  1463:     if ($rule_in_effect eq 'none') {
                   1464:         return [$perlvar{'lonHostID'}];
                   1465:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1466:         $offloadto = $currtargets;
                   1467:     } else {
                   1468:         if ($rule_in_effect eq 'homeserver') {
                   1469:             my $homeserver = &homeserver($uname,$udom);
                   1470:             if ($homeserver ne 'no_host') {
                   1471:                 $offloadto = [$homeserver];
                   1472:             }
                   1473:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1474:             my %domconfig =
                   1475:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1476:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1477:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1478:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1479:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1480:                     }
                   1481:                 }
                   1482:             } else {
1.1178    raeburn  1483:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1484:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1485:                 if (&hostname($remotebalancer) ne '') {
                   1486:                     $offloadto = [$remotebalancer];
                   1487:                 }
                   1488:             }
                   1489:         } elsif (&hostname($rule_in_effect) ne '') {
                   1490:             $offloadto = [$rule_in_effect];
                   1491:         }
                   1492:     }
                   1493:     return $offloadto;
                   1494: }
                   1495: 
1.1127    raeburn  1496: sub internet_dom_servers {
                   1497:     my ($dom) = @_;
                   1498:     my (%uniqservers,%servers);
                   1499:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1500:     my @machinedoms = &machine_domains($primaryserver);
                   1501:     foreach my $mdom (@machinedoms) {
                   1502:         my %currservers = %servers;
                   1503:         my %server = &get_servers($mdom);
                   1504:         %servers = (%currservers,%server);
                   1505:     }
                   1506:     my %by_hostname;
                   1507:     foreach my $id (keys(%servers)) {
                   1508:         push(@{$by_hostname{$servers{$id}}},$id);
                   1509:     }
                   1510:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1511:         if (@{$by_hostname{$hostname}} > 1) {
                   1512:             my $match = 0;
                   1513:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1514:                 if (&host_domain($id) eq $dom) {
                   1515:                     $uniqservers{$id} = $hostname;
                   1516:                     $match = 1;
                   1517:                 }
                   1518:             }
                   1519:             unless ($match) {
                   1520:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1521:             }
                   1522:         } else {
                   1523:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1524:         }
                   1525:     }
                   1526:     return %uniqservers;
                   1527: }
                   1528: 
1.1       albertel 1529: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1530: 
1.599     albertel 1531: my %homecache;
1.1       albertel 1532: sub homeserver {
1.230     stredwic 1533:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1534:     my $index="$uname:$udom";
1.426     albertel 1535: 
1.599     albertel 1536:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1537: 
                   1538:     my %servers = &get_servers($udom,'library');
                   1539:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1540:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1541: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1542: 
                   1543: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1544: 	if ($answer eq 'found') {
                   1545: 	    delete($badServerCache{$tryserver}); 
                   1546: 	    return $homecache{$index}=$tryserver;
                   1547: 	} elsif ($answer eq 'no_host') {
                   1548: 	    $badServerCache{$tryserver}=1;
                   1549: 	}
1.1       albertel 1550:     }    
                   1551:     return 'no_host';
1.70      www      1552: }
                   1553: 
                   1554: # ------------------------------------- Find the usernames behind a list of IDs
                   1555: 
                   1556: sub idget {
                   1557:     my ($udom,@ids)=@_;
                   1558:     my %returnhash=();
                   1559:     
1.841     albertel 1560:     my %servers = &get_servers($udom,'library');
                   1561:     foreach my $tryserver (keys(%servers)) {
                   1562: 	my $idlist=join('&',@ids);
                   1563: 	$idlist=~tr/A-Z/a-z/; 
                   1564: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1565: 	my @answer=();
                   1566: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1567: 	    @answer=split(/\&/,$reply);
                   1568: 	}                    ;
                   1569: 	my $i;
                   1570: 	for ($i=0;$i<=$#ids;$i++) {
                   1571: 	    if ($answer[$i]) {
                   1572: 		$returnhash{$ids[$i]}=$answer[$i];
                   1573: 	    } 
                   1574: 	}
                   1575:     } 
1.70      www      1576:     return %returnhash;
                   1577: }
                   1578: 
                   1579: # ------------------------------------- Find the IDs behind a list of usernames
                   1580: 
                   1581: sub idrget {
                   1582:     my ($udom,@unames)=@_;
                   1583:     my %returnhash=();
1.800     albertel 1584:     foreach my $uname (@unames) {
                   1585:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1586:     }
1.70      www      1587:     return %returnhash;
                   1588: }
                   1589: 
                   1590: # ------------------------------- Store away a list of names and associated IDs
                   1591: 
                   1592: sub idput {
                   1593:     my ($udom,%ids)=@_;
                   1594:     my %servers=();
1.800     albertel 1595:     foreach my $uname (keys(%ids)) {
                   1596: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1597:         my $uhom=&homeserver($uname,$udom);
1.70      www      1598:         if ($uhom ne 'no_host') {
1.800     albertel 1599:             my $id=&escape($ids{$uname});
1.70      www      1600:             $id=~tr/A-Z/a-z/;
1.800     albertel 1601:             my $esc_unam=&escape($uname);
1.70      www      1602: 	    if ($servers{$uhom}) {
1.800     albertel 1603: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1604:             } else {
1.800     albertel 1605:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1606:             }
                   1607:         }
1.191     harris41 1608:     }
1.800     albertel 1609:     foreach my $server (keys(%servers)) {
                   1610:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1611:     }
1.344     www      1612: }
                   1613: 
1.1231    raeburn  1614: # ---------------------------------------- Delete unwanted IDs from ids.db file 
                   1615: 
                   1616: sub iddel {
                   1617:     my ($udom,$idshashref,$uhome)=@_;
                   1618:     my %result=();
                   1619:     unless (ref($idshashref) eq 'HASH') {
                   1620:         return %result;
                   1621:     }
                   1622:     my %servers=();
                   1623:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1624:         my $uhom;
                   1625:         if ($uhome) {
                   1626:             $uhom = $uhome;
                   1627:         } else {
                   1628:             $uhom=&homeserver($uname,$udom);
                   1629:         }
                   1630:         if ($uhom ne 'no_host') {
                   1631:             if ($servers{$uhom}) {
                   1632:                 $servers{$uhom}.='&'.&escape($id);
                   1633:             } else {
                   1634:                 $servers{$uhom}=&escape($id);
                   1635:             }
                   1636:         }
                   1637:     }
                   1638:     foreach my $server (keys(%servers)) {
                   1639:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1640:     }
                   1641:     return %result;
                   1642: }
                   1643: 
1.1023    raeburn  1644: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1645: sub dump_dom {
1.1165    droeschl 1646:     my ($namespace, $udom, $regexp) = @_;
                   1647: 
                   1648:     $udom ||= $env{'user.domain'};
                   1649: 
                   1650:     return () unless $udom;
                   1651: 
                   1652:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1653: }
                   1654: 
1.1023    raeburn  1655: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1656: 
                   1657: sub get_dom {
1.860     raeburn  1658:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1659:     return if ($udom eq 'public');
1.806     raeburn  1660:     my $items='';
                   1661:     foreach my $item (@$storearr) {
                   1662:         $items.=&escape($item).'&';
                   1663:     }
                   1664:     $items=~s/\&$//;
1.860     raeburn  1665:     if (!$udom) {
                   1666:         $udom=$env{'user.domain'};
1.1267    raeburn  1667:         return if ($udom eq 'public');
1.860     raeburn  1668:         if (defined(&domain($udom,'primary'))) {
                   1669:             $uhome=&domain($udom,'primary');
                   1670:         } else {
1.874     albertel 1671:             undef($uhome);
1.860     raeburn  1672:         }
                   1673:     } else {
                   1674:         if (!$uhome) {
                   1675:             if (defined(&domain($udom,'primary'))) {
                   1676:                 $uhome=&domain($udom,'primary');
                   1677:             }
                   1678:         }
                   1679:     }
                   1680:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1681:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1682:         my %returnhash;
1.875     albertel 1683:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1684:             return %returnhash;
                   1685:         }
1.806     raeburn  1686:         my @pairs=split(/\&/,$rep);
                   1687:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1688:             return @pairs;
                   1689:         }
                   1690:         my $i=0;
                   1691:         foreach my $item (@$storearr) {
                   1692:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1693:             $i++;
                   1694:         }
                   1695:         return %returnhash;
                   1696:     } else {
1.880     banghart 1697:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1698:     }
                   1699: }
                   1700: 
                   1701: # -------------------------------------------- put items in domain db files 
                   1702: 
                   1703: sub put_dom {
1.860     raeburn  1704:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1705:     if (!$udom) {
                   1706:         $udom=$env{'user.domain'};
                   1707:         if (defined(&domain($udom,'primary'))) {
                   1708:             $uhome=&domain($udom,'primary');
                   1709:         } else {
1.874     albertel 1710:             undef($uhome);
1.860     raeburn  1711:         }
                   1712:     } else {
                   1713:         if (!$uhome) {
                   1714:             if (defined(&domain($udom,'primary'))) {
                   1715:                 $uhome=&domain($udom,'primary');
                   1716:             }
                   1717:         }
                   1718:     } 
                   1719:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1720:         my $items='';
                   1721:         foreach my $item (keys(%$storehash)) {
                   1722:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1723:         }
                   1724:         $items=~s/\&$//;
                   1725:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1726:     } else {
1.860     raeburn  1727:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1728:     }
                   1729: }
                   1730: 
1.1023    raeburn  1731: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1732: sub newput_dom {
1.1023    raeburn  1733:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1734:     my $result;
                   1735:     if (!$udom) {
                   1736:         $udom=$env{'user.domain'};
                   1737:     }
1.1023    raeburn  1738:     if ($udom) {
                   1739:         my $uname = &get_domainconfiguser($udom);
                   1740:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1741:     }
                   1742:     return $result;
                   1743: }
                   1744: 
1.1023    raeburn  1745: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1746: sub del_dom {
1.1023    raeburn  1747:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1748:     if (ref($storearr) eq 'ARRAY') {
                   1749:         if (!$udom) {
                   1750:             $udom=$env{'user.domain'};
                   1751:         }
1.1023    raeburn  1752:         if ($udom) {
                   1753:             my $uname = &get_domainconfiguser($udom); 
                   1754:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1755:         }
                   1756:     }
                   1757: }
                   1758: 
1.1023    raeburn  1759: # ----------------------------------construct domainconfig user for a domain 
                   1760: sub get_domainconfiguser {
                   1761:     my ($udom) = @_;
                   1762:     return $udom.'-domainconfig';
                   1763: }
                   1764: 
1.837     raeburn  1765: sub retrieve_inst_usertypes {
                   1766:     my ($udom) = @_;
                   1767:     my (%returnhash,@order);
1.989     raeburn  1768:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1769:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1770:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  1771:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1772:     } else {
                   1773:         if (defined(&domain($udom,'primary'))) {
                   1774:             my $uhome=&domain($udom,'primary');
                   1775:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1776:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  1777:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1778:                 return (\%returnhash,\@order);
                   1779:             }
                   1780:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1781:             my @pairs=split(/\&/,$hashitems);
                   1782:             foreach my $item (@pairs) {
                   1783:                 my ($key,$value)=split(/=/,$item,2);
                   1784:                 $key = &unescape($key);
                   1785:                 next if ($key =~ /^error: 2 /);
                   1786:                 $returnhash{$key}=&thaw_unescape($value);
                   1787:             }
                   1788:             my @esc_order = split(/\&/,$orderitems);
                   1789:             foreach my $item (@esc_order) {
                   1790:                 push(@order,&unescape($item));
                   1791:             }
                   1792:         } else {
1.1256    raeburn  1793:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1794:         }
1.1256    raeburn  1795:         return (\%returnhash,\@order);
1.837     raeburn  1796:     }
                   1797: }
                   1798: 
1.868     raeburn  1799: sub is_domainimage {
                   1800:     my ($url) = @_;
                   1801:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1802:         if (&domain($1) ne '') {
                   1803:             return '1';
                   1804:         }
                   1805:     }
                   1806:     return;
                   1807: }
                   1808: 
1.899     raeburn  1809: sub inst_directory_query {
                   1810:     my ($srch) = @_;
                   1811:     my $udom = $srch->{'srchdomain'};
                   1812:     my %results;
                   1813:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1814:     my $outcome;
1.899     raeburn  1815:     if ($homeserver ne '') {
1.904     albertel 1816: 	my $queryid=&reply("querysend:instdirsearch:".
                   1817: 			   &escape($srch->{'srchby'}).':'.
                   1818: 			   &escape($srch->{'srchterm'}).':'.
                   1819: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1820: 	my $host=&hostname($homeserver);
                   1821: 	if ($queryid !~/^\Q$host\E\_/) {
                   1822: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1823: 	    return;
                   1824: 	}
                   1825: 	my $response = &get_query_reply($queryid);
                   1826: 	my $maxtries = 5;
                   1827: 	my $tries = 1;
                   1828: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1829: 	    $response = &get_query_reply($queryid);
                   1830: 	    $tries ++;
                   1831: 	}
                   1832: 
                   1833:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1834:             if ($response eq 'unavailable') {
                   1835:                 $outcome = $response;
                   1836:             } else {
                   1837:                 $outcome = 'ok';
                   1838:                 my @matches = split(/\n/,$response);
                   1839:                 foreach my $match (@matches) {
                   1840:                     my ($key,$value) = split(/=/,$match);
                   1841:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1842:                 }
1.899     raeburn  1843:             }
                   1844:         }
                   1845:     }
1.909     raeburn  1846:     return ($outcome,%results);
1.899     raeburn  1847: }
                   1848: 
                   1849: sub usersearch {
                   1850:     my ($srch) = @_;
                   1851:     my $dom = $srch->{'srchdomain'};
                   1852:     my %results;
                   1853:     my %libserv = &all_library();
                   1854:     my $query = 'usersearch';
                   1855:     foreach my $tryserver (keys(%libserv)) {
                   1856:         if (&host_domain($tryserver) eq $dom) {
                   1857:             my $host=&hostname($tryserver);
                   1858:             my $queryid=
1.911     raeburn  1859:                 &reply("querysend:".&escape($query).':'.
                   1860:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1861:                        &escape($srch->{'srchtype'}).':'.
                   1862:                        &escape($srch->{'srchterm'}),$tryserver);
                   1863:             if ($queryid !~/^\Q$host\E\_/) {
                   1864:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1865:                 next;
1.899     raeburn  1866:             }
                   1867:             my $reply = &get_query_reply($queryid);
                   1868:             my $maxtries = 1;
                   1869:             my $tries = 1;
                   1870:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1871:                 $reply = &get_query_reply($queryid);
                   1872:                 $tries ++;
                   1873:             }
                   1874:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1875:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1876:             } else {
1.911     raeburn  1877:                 my @matches;
                   1878:                 if ($reply =~ /\n/) {
                   1879:                     @matches = split(/\n/,$reply);
                   1880:                 } else {
                   1881:                     @matches = split(/\&/,$reply);
                   1882:                 }
1.899     raeburn  1883:                 foreach my $match (@matches) {
                   1884:                     my ($uname,$udom,%userhash);
1.911     raeburn  1885:                     foreach my $entry (split(/:/,$match)) {
                   1886:                         my ($key,$value) =
                   1887:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1888:                         $userhash{$key} = $value;
                   1889:                         if ($key eq 'username') {
                   1890:                             $uname = $value;
                   1891:                         } elsif ($key eq 'domain') {
                   1892:                             $udom = $value;
1.911     raeburn  1893:                         }
1.899     raeburn  1894:                     }
                   1895:                     $results{$uname.':'.$udom} = \%userhash;
                   1896:                 }
                   1897:             }
                   1898:         }
                   1899:     }
                   1900:     return %results;
                   1901: }
                   1902: 
1.912     raeburn  1903: sub get_instuser {
                   1904:     my ($udom,$uname,$id) = @_;
                   1905:     my $homeserver = &domain($udom,'primary');
                   1906:     my ($outcome,%results);
                   1907:     if ($homeserver ne '') {
                   1908:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1909:                            &escape($id).':'.&escape($udom),$homeserver);
                   1910:         my $host=&hostname($homeserver);
                   1911:         if ($queryid !~/^\Q$host\E\_/) {
                   1912:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1913:             return;
                   1914:         }
                   1915:         my $response = &get_query_reply($queryid);
                   1916:         my $maxtries = 5;
                   1917:         my $tries = 1;
                   1918:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1919:             $response = &get_query_reply($queryid);
                   1920:             $tries ++;
                   1921:         }
                   1922:         if (!&error($response) && $response ne 'refused') {
                   1923:             if ($response eq 'unavailable') {
                   1924:                 $outcome = $response;
                   1925:             } else {
                   1926:                 $outcome = 'ok';
                   1927:                 my @matches = split(/\n/,$response);
                   1928:                 foreach my $match (@matches) {
                   1929:                     my ($key,$value) = split(/=/,$match);
                   1930:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1931:                 }
                   1932:             }
                   1933:         }
                   1934:     }
                   1935:     my %userinfo;
                   1936:     if (ref($results{$uname}) eq 'HASH') {
                   1937:         %userinfo = %{$results{$uname}};
                   1938:     } 
                   1939:     return ($outcome,%userinfo);
                   1940: }
                   1941: 
1.1290  ! raeburn  1942: sub get_multiple_instusers {
        !          1943:     my ($udom,$users,$caller) = @_;
        !          1944:     my ($outcome,$results);
        !          1945:     if (ref($users) eq 'HASH') {
        !          1946:         my $count = keys(%{$users}); 
        !          1947:         my $requested = &freeze_escape($users);
        !          1948:         my $homeserver = &domain($udom,'primary');
        !          1949:         if ($homeserver ne '') {
        !          1950:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
        !          1951:             my $host=&hostname($homeserver);
        !          1952:             if ($queryid !~/^\Q$host\E\_/) {
        !          1953:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
        !          1954:                          ' for host: '.$homeserver.'in domain '.$udom);
        !          1955:                 return ($outcome,$results);
        !          1956:             }
        !          1957:             my $response = &get_query_reply($queryid);
        !          1958:             my $maxtries = 5;
        !          1959:             if ($count > 100) {
        !          1960:                 $maxtries = 1+int($count/20);
        !          1961:             }
        !          1962:             my $tries = 1;
        !          1963:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
        !          1964:                 $response = &get_query_reply($queryid);
        !          1965:                 $tries ++;
        !          1966:             }
        !          1967:             if ($response eq '') {
        !          1968:                 $results = {};
        !          1969:                 foreach my $key (keys(%{$users})) {
        !          1970:                     my ($uname,$id);
        !          1971:                     if ($caller eq 'id') {
        !          1972:                         $id = $key;
        !          1973:                     } else {
        !          1974:                         $uname = $key;
        !          1975:                     }
        !          1976:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
        !          1977:                     if ($resp eq 'ok') {
        !          1978:                         %{$results} = (%{$results}, %info);
        !          1979:                         $outcome = 'ok';
        !          1980:                     } else {
        !          1981:                         $outcome = $resp;
        !          1982:                         last;
        !          1983:                     }
        !          1984:                 }
        !          1985:             } elsif(!&error($response) && ($response ne 'refused')) {
        !          1986:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
        !          1987:                     $outcome = $response;
        !          1988:                 } else {
        !          1989:                     ($outcome,my $userdata) = split(/:/,$response,2);
        !          1990:                     if ($outcome eq 'ok') {
        !          1991:                         $results = &thaw_unescape($userdata); 
        !          1992:                     }
        !          1993:                 }
        !          1994:             }
        !          1995:         }
        !          1996:     }
        !          1997:     return ($outcome,$results);
        !          1998: }
        !          1999: 
1.912     raeburn  2000: sub inst_rulecheck {
1.923     raeburn  2001:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2002:     my %returnhash;
                   2003:     if ($udom ne '') {
                   2004:         if (ref($rules) eq 'ARRAY') {
                   2005:             @{$rules} = map {&escape($_);} (@{$rules});
                   2006:             my $rulestr = join(':',@{$rules});
                   2007:             my $homeserver=&domain($udom,'primary');
                   2008:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2009:                 my $response;
                   2010:                 if ($item eq 'username') {                
                   2011:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2012:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2013:                                               $homeserver));
1.923     raeburn  2014:                 } elsif ($item eq 'id') {
                   2015:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2016:                                               ':'.&escape($id).':'.$rulestr,
                   2017:                                               $homeserver));
1.945     raeburn  2018:                 } elsif ($item eq 'selfcreate') {
                   2019:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2020:                                                &escape($udom).':'.&escape($uname).
                   2021:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2022:                 }
1.912     raeburn  2023:                 if ($response ne 'refused') {
                   2024:                     my @pairs=split(/\&/,$response);
                   2025:                     foreach my $item (@pairs) {
                   2026:                         my ($key,$value)=split(/=/,$item,2);
                   2027:                         $key = &unescape($key);
                   2028:                         next if ($key =~ /^error: 2 /);
                   2029:                         $returnhash{$key}=&thaw_unescape($value);
                   2030:                     }
                   2031:                 }
                   2032:             }
                   2033:         }
                   2034:     }
                   2035:     return %returnhash;
                   2036: }
                   2037: 
                   2038: sub inst_userrules {
1.923     raeburn  2039:     my ($udom,$check) = @_;
1.912     raeburn  2040:     my (%ruleshash,@ruleorder);
                   2041:     if ($udom ne '') {
                   2042:         my $homeserver=&domain($udom,'primary');
                   2043:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2044:             my $response;
                   2045:             if ($check eq 'id') {
                   2046:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2047:                                  $homeserver);
1.943     raeburn  2048:             } elsif ($check eq 'email') {
                   2049:                 $response=&reply('instemailrules:'.&escape($udom),
                   2050:                                  $homeserver);
1.923     raeburn  2051:             } else {
                   2052:                 $response=&reply('instuserrules:'.&escape($udom),
                   2053:                                  $homeserver);
                   2054:             }
1.912     raeburn  2055:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2056:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2057:                 ($response ne 'no_such_host')) {
                   2058:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2059:                 my @pairs=split(/\&/,$hashitems);
                   2060:                 foreach my $item (@pairs) {
                   2061:                     my ($key,$value)=split(/=/,$item,2);
                   2062:                     $key = &unescape($key);
                   2063:                     next if ($key =~ /^error: 2 /);
                   2064:                     $ruleshash{$key}=&thaw_unescape($value);
                   2065:                 }
                   2066:                 my @esc_order = split(/\&/,$orderitems);
                   2067:                 foreach my $item (@esc_order) {
                   2068:                     push(@ruleorder,&unescape($item));
                   2069:                 }
                   2070:             }
                   2071:         }
                   2072:     }
                   2073:     return (\%ruleshash,\@ruleorder);
                   2074: }
                   2075: 
1.976     raeburn  2076: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2077: 
                   2078: sub get_domain_defaults {
1.1240    raeburn  2079:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2080:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2081:     my $cachetime = 60*60*24;
1.1240    raeburn  2082:     unless ($ignore_cache) {
                   2083:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2084:         if (defined($cached)) {
                   2085:             if (ref($result) eq 'HASH') {
                   2086:                 return %{$result};
                   2087:             }
1.943     raeburn  2088:         }
                   2089:     }
                   2090:     my %domdefaults;
                   2091:     my %domconfig =
1.989     raeburn  2092:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2093:                                   'requestcourses','inststatus',
1.1183    raeburn  2094:                                   'coursedefaults','usersessions',
1.1258    raeburn  2095:                                   'requestauthor','selfenrollment',
                   2096:                                   'coursecategories'],$domain);
1.1254    raeburn  2097:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2098:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2099:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2100:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2101:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2102:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2103:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2104:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2105:     } else {
                   2106:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2107:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2108:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2109:     }
1.976     raeburn  2110:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2111:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2112:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2113:         } else {
                   2114:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2115:         }
1.1177    raeburn  2116:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2117:         foreach my $item (@usertools) {
                   2118:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2119:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2120:             }
                   2121:         }
1.1229    raeburn  2122:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2123:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2124:         }
1.976     raeburn  2125:     }
1.985     raeburn  2126:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1246    raeburn  2127:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2128:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2129:         }
                   2130:     }
1.1183    raeburn  2131:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2132:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2133:     }
1.989     raeburn  2134:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2135:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2136:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2137:         }
                   2138:     }
1.1047    raeburn  2139:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2140:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2141:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2142:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2143:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2144:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2145:         }
1.1254    raeburn  2146:         foreach my $type (@coursetypes) {
                   2147:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2148:                 unless ($type eq 'community') {
                   2149:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2150:                 }
                   2151:             }
                   2152:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2153:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2154:             }
1.1277    raeburn  2155:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2156:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2157:                     $domdefaults{$type.'postsubtimeout'} = 
                   2158:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2159:                 }
                   2160:             }
1.1230    raeburn  2161:         }
1.1286    raeburn  2162:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2163:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2164:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2165:                 if (@clonecodes) {
                   2166:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2167:                 }
                   2168:             }
                   2169:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2170:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2171:         }
1.1047    raeburn  2172:     }
1.1073    raeburn  2173:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2174:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2175:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2176:         }
                   2177:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2178:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2179:         }
1.1279    raeburn  2180:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2181:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2182:         }
1.1073    raeburn  2183:     }
1.1254    raeburn  2184:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2185:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2186:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2187:                             'approval','limit');
                   2188:             foreach my $type (@coursetypes) {
                   2189:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2190:                     my @mgrdc = ();
                   2191:                     foreach my $item (@settings) {
                   2192:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2193:                             push(@mgrdc,$item);
                   2194:                         }
                   2195:                     }
                   2196:                     if (@mgrdc) {
                   2197:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2198:                     }
                   2199:                 }
                   2200:             }
                   2201:         }
                   2202:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2203:             foreach my $type (@coursetypes) {
                   2204:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2205:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2206:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2207:                     }
                   2208:                 }
                   2209:             }
                   2210:         }
                   2211:     }
1.1258    raeburn  2212:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2213:         $domdefaults{'catauth'} = 'std';
                   2214:         $domdefaults{'catunauth'} = 'std';
                   2215:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2216:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2217:         }
                   2218:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2219:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2220:         }
                   2221:     }
1.1219    raeburn  2222:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2223:     return %domdefaults;
                   2224: }
                   2225: 
1.344     www      2226: # --------------------------------------------------- Assign a key to a student
                   2227: 
                   2228: sub assign_access_key {
1.364     www      2229: #
                   2230: # a valid key looks like uname:udom#comments
                   2231: # comments are being appended
                   2232: #
1.498     www      2233:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2234:     $kdom=
1.620     albertel 2235:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2236:     $knum=
1.620     albertel 2237:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2238:     $cdom=
1.620     albertel 2239:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2240:     $cnum=
1.620     albertel 2241:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2242:     $udom=$env{'user.name'} unless (defined($udom));
                   2243:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2244:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2245:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2246:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2247:                                                   # assigned to this person
                   2248:                                                   # - this should not happen,
1.345     www      2249:                                                   # unless something went wrong
                   2250:                                                   # the first time around
                   2251: # ready to assign
1.364     www      2252:         $logentry=$1.'; '.$logentry;
1.496     www      2253:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2254:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2255: # key now belongs to user
1.346     www      2256: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2257:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2258:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2259:                 return 'ok';
                   2260:             } else {
                   2261:                 return 
                   2262:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2263: 	    }
                   2264:         } else {
                   2265:             return 'error: Could not assign key, try again later.';
                   2266:         }
1.364     www      2267:     } elsif (!$existing{$ckey}) {
1.345     www      2268: # the key does not exist
                   2269: 	return 'error: The key does not exist';
                   2270:     } else {
                   2271: # the key is somebody else's
                   2272: 	return 'error: The key is already in use';
                   2273:     }
1.344     www      2274: }
                   2275: 
1.364     www      2276: # ------------------------------------------ put an additional comment on a key
                   2277: 
                   2278: sub comment_access_key {
                   2279: #
                   2280: # a valid key looks like uname:udom#comments
                   2281: # comments are being appended
                   2282: #
                   2283:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2284:     $cdom=
1.620     albertel 2285:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2286:     $cnum=
1.620     albertel 2287:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2288:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2289:     if ($existing{$ckey}) {
                   2290:         $existing{$ckey}.='; '.$logentry;
                   2291: # ready to assign
1.367     www      2292:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2293:                                                  $cdom,$cnum) eq 'ok') {
                   2294: 	    return 'ok';
                   2295:         } else {
                   2296: 	    return 'error: Count not store comment.';
                   2297:         }
                   2298:     } else {
                   2299: # the key does not exist
                   2300: 	return 'error: The key does not exist';
                   2301:     }
                   2302: }
                   2303: 
1.344     www      2304: # ------------------------------------------------------ Generate a set of keys
                   2305: 
                   2306: sub generate_access_keys {
1.364     www      2307:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2308:     $cdom=
1.620     albertel 2309:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2310:     $cnum=
1.620     albertel 2311:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2312:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2313:     unless (($cdom) && ($cnum)) { return 0; }
                   2314:     if ($number>10000) { return 0; }
                   2315:     sleep(2); # make sure don't get same seed twice
                   2316:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2317:     my $total=0;
                   2318:     for (my $i=1;$i<=$number;$i++) {
                   2319:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2320:                   sprintf("%lx",int(100000*rand)).'-'.
                   2321:                   sprintf("%lx",int(100000*rand));
                   2322:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2323:        $newkey=~s/0/h/g; # and also 0 and O
                   2324:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2325:        if ($existing{$newkey}) {
                   2326:            $i--;
                   2327:        } else {
1.364     www      2328: 	  if (&put('accesskeys',
                   2329:               { $newkey => '# generated '.localtime().
1.620     albertel 2330:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2331:                            '; '.$logentry },
                   2332: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2333:               $total++;
                   2334: 	  }
                   2335:        }
                   2336:     }
1.620     albertel 2337:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2338:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2339:     return $total;
                   2340: }
                   2341: 
                   2342: # ------------------------------------------------------- Validate an accesskey
                   2343: 
                   2344: sub validate_access_key {
                   2345:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2346:     $cdom=
1.620     albertel 2347:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2348:     $cnum=
1.620     albertel 2349:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2350:     $udom=$env{'user.domain'} unless (defined($udom));
                   2351:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2352:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2353:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2354: }
                   2355: 
                   2356: # ------------------------------------- Find the section of student in a course
1.652     albertel 2357: sub devalidate_getsection_cache {
                   2358:     my ($udom,$unam,$courseid)=@_;
                   2359:     my $hashid="$udom:$unam:$courseid";
                   2360:     &devalidate_cache_new('getsection',$hashid);
                   2361: }
1.298     matthew  2362: 
1.815     albertel 2363: sub courseid_to_courseurl {
                   2364:     my ($courseid) = @_;
                   2365:     #already url style courseid
                   2366:     return $courseid if ($courseid =~ m{^/});
                   2367: 
                   2368:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2369: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2370: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2371: 	return "/$cdom/$cnum";
                   2372:     }
                   2373: 
                   2374:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2375:     if (exists($courseinfo{'num'})) {
                   2376: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2377:     }
                   2378: 
                   2379:     return undef;
                   2380: }
                   2381: 
1.298     matthew  2382: sub getsection {
                   2383:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2384:     my $cachetime=1800;
1.551     albertel 2385: 
                   2386:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2387:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2388:     if (defined($cached)) { return $result; }
                   2389: 
1.298     matthew  2390:     my %Pending; 
                   2391:     my %Expired;
                   2392:     #
                   2393:     # Each role can either have not started yet (pending), be active, 
                   2394:     #    or have expired.
                   2395:     #
                   2396:     # If there is an active role, we are done.
                   2397:     #
                   2398:     # If there is more than one role which has not started yet, 
                   2399:     #     choose the one which will start sooner
                   2400:     # If there is one role which has not started yet, return it.
                   2401:     #
                   2402:     # If there is more than one expired role, choose the one which ended last.
                   2403:     # If there is a role which has expired, return it.
                   2404:     #
1.815     albertel 2405:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2406:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2407:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2408:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2409:         my $section=$1;
                   2410:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2411:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2412:         my $now=time;
1.548     albertel 2413:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2414:             $Expired{$end}=$section;
                   2415:             next;
                   2416:         }
1.548     albertel 2417:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2418:             $Pending{$start}=$section;
                   2419:             next;
                   2420:         }
1.599     albertel 2421:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2422:     }
                   2423:     #
                   2424:     # Presumedly there will be few matching roles from the above
                   2425:     # loop and the sorting time will be negligible.
                   2426:     if (scalar(keys(%Pending))) {
                   2427:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2428:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2429:     } 
                   2430:     if (scalar(keys(%Expired))) {
                   2431:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2432:         my $time = pop(@sorted);
1.599     albertel 2433:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2434:     }
1.599     albertel 2435:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2436: }
1.70      www      2437: 
1.599     albertel 2438: sub save_cache {
                   2439:     &purge_remembered();
1.722     albertel 2440:     #&Apache::loncommon::validate_page();
1.620     albertel 2441:     undef(%env);
1.780     albertel 2442:     undef($env_loaded);
1.599     albertel 2443: }
1.452     albertel 2444: 
1.599     albertel 2445: my $to_remember=-1;
                   2446: my %remembered;
                   2447: my %accessed;
                   2448: my $kicks=0;
                   2449: my $hits=0;
1.849     albertel 2450: sub make_key {
                   2451:     my ($name,$id) = @_;
1.872     albertel 2452:     if (length($id) > 65 
                   2453: 	&& length(&escape($id)) > 200) {
                   2454: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2455:     }
1.849     albertel 2456:     return &escape($name.':'.$id);
                   2457: }
                   2458: 
1.599     albertel 2459: sub devalidate_cache_new {
                   2460:     my ($name,$id,$debug) = @_;
                   2461:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2462:     $id=&make_key($name,$id);
1.599     albertel 2463:     $memcache->delete($id);
                   2464:     delete($remembered{$id});
                   2465:     delete($accessed{$id});
                   2466: }
                   2467: 
                   2468: sub is_cached_new {
                   2469:     my ($name,$id,$debug) = @_;
1.849     albertel 2470:     $id=&make_key($name,$id);
1.599     albertel 2471:     if (exists($remembered{$id})) {
1.1133    foxr     2472: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2473: 	$accessed{$id}=[&gettimeofday()];
                   2474: 	$hits++;
                   2475: 	return ($remembered{$id},1);
                   2476:     }
                   2477:     my $value = $memcache->get($id);
                   2478:     if (!(defined($value))) {
                   2479: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2480: 	return (undef,undef);
1.416     albertel 2481:     }
1.599     albertel 2482:     if ($value eq '__undef__') {
                   2483: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2484: 	$value=undef;
                   2485:     }
                   2486:     &make_room($id,$value,$debug);
                   2487:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2488:     return ($value,1);
                   2489: }
                   2490: 
                   2491: sub do_cache_new {
                   2492:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2493:     $id=&make_key($name,$id);
1.599     albertel 2494:     my $setvalue=$value;
                   2495:     if (!defined($setvalue)) {
                   2496: 	$setvalue='__undef__';
                   2497:     }
1.623     albertel 2498:     if (!defined($time) ) {
                   2499: 	$time=600;
                   2500:     }
1.599     albertel 2501:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2502:     my $result = $memcache->set($id,$setvalue,$time);
                   2503:     if (! $result) {
1.872     albertel 2504: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2505: 	$memcache->disconnect_all();
1.872     albertel 2506:     }
1.600     albertel 2507:     # need to make a copy of $value
1.919     albertel 2508:     &make_room($id,$value,$debug);
1.599     albertel 2509:     return $value;
                   2510: }
                   2511: 
                   2512: sub make_room {
                   2513:     my ($id,$value,$debug)=@_;
1.919     albertel 2514: 
                   2515:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2516:                                     : $value;
1.599     albertel 2517:     if ($to_remember<0) { return; }
                   2518:     $accessed{$id}=[&gettimeofday()];
                   2519:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2520:     my $to_kick;
                   2521:     my $max_time=0;
                   2522:     foreach my $other (keys(%accessed)) {
                   2523: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2524: 	    $to_kick=$other;
                   2525: 	    $max_time=&tv_interval($accessed{$other});
                   2526: 	}
                   2527:     }
                   2528:     delete($remembered{$to_kick});
                   2529:     delete($accessed{$to_kick});
                   2530:     $kicks++;
                   2531:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2532:     return;
                   2533: }
                   2534: 
1.599     albertel 2535: sub purge_remembered {
1.604     albertel 2536:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2537:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2538:     undef(%remembered);
                   2539:     undef(%accessed);
1.428     albertel 2540: }
1.70      www      2541: # ------------------------------------- Read an entry from a user's environment
                   2542: 
                   2543: sub userenvironment {
                   2544:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2545:     my $items;
                   2546:     foreach my $item (@what) {
                   2547:         $items.=&escape($item).'&';
                   2548:     }
                   2549:     $items=~s/\&$//;
1.70      www      2550:     my %returnhash=();
1.1009    raeburn  2551:     my $uhome = &homeserver($unam,$udom);
                   2552:     unless ($uhome eq 'no_host') {
                   2553:         my @answer=split(/\&/, 
                   2554:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2555:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2556:             return %returnhash;
                   2557:         }
1.1009    raeburn  2558:         my $i;
                   2559:         for ($i=0;$i<=$#what;$i++) {
                   2560: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2561:         }
1.70      www      2562:     }
                   2563:     return %returnhash;
1.1       albertel 2564: }
                   2565: 
1.617     albertel 2566: # ---------------------------------------------------------- Get a studentphoto
                   2567: sub studentphoto {
                   2568:     my ($udom,$unam,$ext) = @_;
                   2569:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2570:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2571:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2572:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2573:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2574:             } else {
                   2575:                 my ($result,$perm_reqd)=
1.707     albertel 2576: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2577:                 if ($result eq 'ok') {
                   2578:                     if (!($perm_reqd eq 'yes')) {
                   2579:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2580:                     }
                   2581:                 }
                   2582:             }
                   2583:         }
                   2584:     } else {
                   2585:         my ($result,$perm_reqd) = 
1.707     albertel 2586: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2587:         if ($result eq 'ok') {
                   2588:             if (!($perm_reqd eq 'yes')) {
                   2589:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2590:             }
                   2591:         }
                   2592:     }
                   2593:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2594: }
                   2595: 
                   2596: sub retrievestudentphoto {
                   2597:     my ($udom,$unam,$ext,$type) = @_;
                   2598:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2599:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2600:     if ($ret eq 'ok') {
                   2601:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2602:         if ($type eq 'thumbnail') {
                   2603:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2604:         }
                   2605:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2606:         return $tokenurl;
                   2607:     } else {
                   2608:         if ($type eq 'thumbnail') {
                   2609:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2610:         } else { 
                   2611:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2612:         }
1.617     albertel 2613:     }
                   2614: }
                   2615: 
1.263     www      2616: # -------------------------------------------------------------------- New chat
                   2617: 
                   2618: sub chatsend {
1.724     raeburn  2619:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2620:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2621:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2622:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2623:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2624: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2625: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2626: }
                   2627: 
                   2628: # ------------------------------------------ Find current version of a resource
                   2629: 
                   2630: sub getversion {
                   2631:     my $fname=&clutter(shift);
1.1189    raeburn  2632:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2633:     return &currentversion(&filelocation('',$fname));
                   2634: }
                   2635: 
                   2636: sub currentversion {
                   2637:     my $fname=shift;
                   2638:     my $author=$fname;
                   2639:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2640:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2641:     my $home=&homeserver($uname,$udom);
1.292     www      2642:     if ($home eq 'no_host') { 
                   2643:         return -1; 
                   2644:     }
1.1112    www      2645:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2646:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2647: 	return -1;
                   2648:     }
1.1112    www      2649:     return $answer;
1.263     www      2650: }
                   2651: 
1.1111    www      2652: #
                   2653: # Return special version number of resource if set by override, empty otherwise
                   2654: #
                   2655: sub usedversion {
                   2656:     my $fname=shift;
                   2657:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2658:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2659:     if ($urlversion) { return $urlversion; }
                   2660:     return '';
                   2661: }
                   2662: 
1.1       albertel 2663: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2664: 
1.1       albertel 2665: sub subscribe {
                   2666:     my $fname=shift;
1.761     raeburn  2667:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2668:     $fname=~s/[\n\r]//g;
1.1       albertel 2669:     my $author=$fname;
                   2670:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2671:     my ($udom,$uname)=split(/\//,$author);
                   2672:     my $home=homeserver($uname,$udom);
1.335     albertel 2673:     if ($home eq 'no_host') {
                   2674:         return 'not_found';
1.1       albertel 2675:     }
                   2676:     my $answer=reply("sub:$fname",$home);
1.64      www      2677:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2678: 	$answer.=' by '.$home;
                   2679:     }
1.1       albertel 2680:     return $answer;
                   2681: }
                   2682:     
1.8       www      2683: # -------------------------------------------------------------- Replicate file
                   2684: 
                   2685: sub repcopy {
                   2686:     my $filename=shift;
1.23      www      2687:     $filename=~s/\/+/\//g;
1.1142    raeburn  2688:     my $londocroot = $perlvar{'lonDocRoot'};
                   2689:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2690:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2691:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2692: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2693: 	return &repcopy_userfile($filename);
                   2694:     }
1.532     albertel 2695:     $filename=~s/[\n\r]//g;
1.8       www      2696:     my $transname="$filename.in.transfer";
1.828     www      2697: # FIXME: this should flock
1.607     raeburn  2698:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2699:     my $remoteurl=subscribe($filename);
1.64      www      2700:     if ($remoteurl =~ /^con_lost by/) {
                   2701: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2702:            return 'unavailable';
1.8       www      2703:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2704: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2705: 	   return 'not_found';
1.64      www      2706:     } elsif ($remoteurl =~ /^rejected by/) {
                   2707: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2708:            return 'forbidden';
1.20      www      2709:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2710:            return 'ok';
1.8       www      2711:     } else {
1.290     www      2712:         my $author=$filename;
                   2713:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2714:         my ($udom,$uname)=split(/\//,$author);
                   2715:         my $home=homeserver($uname,$udom);
                   2716:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2717:            my @parts=split(/\//,$filename);
                   2718:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2719:            if ($path ne "$londocroot/res") {
1.8       www      2720:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2721: 	       return 'bad_request';
1.8       www      2722:            }
                   2723:            my $count;
                   2724:            for ($count=5;$count<$#parts;$count++) {
                   2725:                $path.="/$parts[$count]";
                   2726:                if ((-e $path)!=1) {
                   2727: 		   mkdir($path,0777);
                   2728:                }
                   2729:            }
                   2730:            my $ua=new LWP::UserAgent;
                   2731:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2732:            my $response=$ua->request($request,$transname);
                   2733:            if ($response->is_error()) {
                   2734: 	       unlink($transname);
                   2735:                my $message=$response->status_line;
1.672     albertel 2736:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2737:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2738:                return 'unavailable';
1.8       www      2739:            } else {
1.16      www      2740: 	       if ($remoteurl!~/\.meta$/) {
                   2741:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2742:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2743:                   if ($mresponse->is_error()) {
                   2744: 		      unlink($filename.'.meta');
                   2745:                       &logthis(
1.672     albertel 2746:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2747:                   }
                   2748: 	       }
1.8       www      2749:                rename($transname,$filename);
1.607     raeburn  2750:                return 'ok';
1.8       www      2751:            }
1.290     www      2752:        }
1.8       www      2753:     }
1.330     www      2754: }
                   2755: 
                   2756: # ------------------------------------------------ Get server side include body
                   2757: sub ssi_body {
1.381     albertel 2758:     my ($filelink,%form)=@_;
1.606     matthew  2759:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2760:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2761:     }
1.953     www      2762:     my $output='';
                   2763:     my $response;
1.980     raeburn  2764:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2765:        ($output,$response)=&externalssi($filelink);
1.953     www      2766:     } else {
1.1004    droeschl 2767:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2768:        $filelink .= 'inhibitmenu=yes';
1.953     www      2769:        ($output,$response)=&ssi($filelink,%form);
                   2770:     }
1.778     albertel 2771:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2772:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2773:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2774:     if (wantarray) {
                   2775:         return ($output, $response);
                   2776:     } else {
                   2777:         return $output;
                   2778:     }
1.8       www      2779: }
                   2780: 
1.15      www      2781: # --------------------------------------------------------- Server Side Include
                   2782: 
1.782     albertel 2783: sub absolute_url {
                   2784:     my ($host_name) = @_;
                   2785:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2786:     if ($host_name eq '') {
                   2787: 	$host_name = $ENV{'SERVER_NAME'};
                   2788:     }
                   2789:     return $protocol.$host_name;
                   2790: }
                   2791: 
1.942     foxr     2792: #
                   2793: #   Server side include.
                   2794: # Parameters:
                   2795: #  fn     Possibly encrypted resource name/id.
                   2796: #  form   Hash that describes how the rendering should be done
                   2797: #         and other things.
1.944     foxr     2798: # Returns:
1.950     raeburn  2799: #   Scalar context: The content of the response.
                   2800: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2801: #     
1.15      www      2802: sub ssi {
                   2803: 
1.944     foxr     2804:     my ($fn,%form)=@_;
1.15      www      2805:     my $ua=new LWP::UserAgent;
1.23      www      2806:     my $request;
1.711     albertel 2807: 
                   2808:     $form{'no_update_last_known'}=1;
1.895     albertel 2809:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2810:     if (%form) {
1.782     albertel 2811:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 2812:       $request->content(join('&',map { 
                   2813:             my $name = escape($_);
                   2814:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   2815:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   2816:             : &escape($form{$_}) );    
                   2817:         } keys(%form)));
1.23      www      2818:     } else {
1.782     albertel 2819:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2820:     }
                   2821: 
1.15      www      2822:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2823:     my $response= $ua->request($request);
1.1182    foxr     2824:     my $content = $response->content;
                   2825: 
                   2826: 
1.944     foxr     2827:     if (wantarray) {
1.1173    foxr     2828: 	return ($content, $response);
1.944     foxr     2829:     } else {
1.1173    foxr     2830: 	return $content;
1.942     foxr     2831:     }
1.324     www      2832: }
                   2833: 
                   2834: sub externalssi {
                   2835:     my ($url)=@_;
                   2836:     my $ua=new LWP::UserAgent;
                   2837:     my $request=new HTTP::Request('GET',$url);
                   2838:     my $response=$ua->request($request);
1.954     raeburn  2839:     if (wantarray) {
                   2840:         return ($response->content, $response);
                   2841:     } else {
                   2842:         return $response->content;
                   2843:     }
1.15      www      2844: }
1.254     www      2845: 
1.492     albertel 2846: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2847: 
                   2848: sub allowuploaded {
                   2849:     my ($srcurl,$url)=@_;
                   2850:     $url=&clutter(&declutter($url));
                   2851:     my $dir=$url;
                   2852:     $dir=~s/\/[^\/]+$//;
                   2853:     my %httpref=();
                   2854:     my $httpurl=&hreflocation('',$url);
                   2855:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2856:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2857: }
1.477     raeburn  2858: 
1.1193    raeburn  2859: #
                   2860: # Determine if the current user should be able to edit a particular resource,
                   2861: # when viewing in course context.
                   2862: # (a) When viewing resource used to determine if "Edit" item is included in 
                   2863: #     Functions.
                   2864: # (b) When displaying folder contents in course editor, used to determine if
                   2865: #     "Edit" link will be displayed alongside resource.
                   2866: #
1.1196    raeburn  2867: #  input: six args -- filename (decluttered), course number, course domain,
                   2868: #                   url, symb (if registered) and group (if this is a group
                   2869: #                   item -- e.g., bulletin board, group page etc.).
                   2870: #  output: array of five scalars -- 
1.1193    raeburn  2871: #          $cfile -- url for file editing if editable on current server
                   2872: #          $home -- homeserver of resource (i.e., for author if published,
                   2873: #                                           or course if uploaded.).
                   2874: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  2875: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   2876: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  2877: #
                   2878: 
                   2879: sub can_edit_resource {
1.1194    raeburn  2880:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   2881:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   2882: #
                   2883: # For aboutme pages user can only edit his/her own.
                   2884: #
1.1199    raeburn  2885:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  2886:         my ($sdom,$sname) = ($1,$2);
                   2887:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   2888:             $home = $env{'user.home'};
                   2889:             $cfile = $resurl;
                   2890:             if ($env{'form.forceedit'}) {
                   2891:                 $forceview = 1;
                   2892:             } else {
                   2893:                 $forceedit = 1;
                   2894:             }
                   2895:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   2896:         } else {
                   2897:             return;
                   2898:         }
                   2899:     }
                   2900: 
                   2901:     if ($env{'request.course.id'}) {
                   2902:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   2903:         if ($group ne '') {
                   2904: # if this is a group homepage or group bulletin board, check group privs
                   2905:             my $allowed = 0;
1.1197    raeburn  2906:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   2907:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  2908:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  2909:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   2910:                     $allowed = 1;
                   2911:                 }
1.1197    raeburn  2912:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   2913:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   2914:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  2915:                     $allowed = 1;
                   2916:                 }
                   2917:             }
                   2918:             if ($allowed) {
                   2919:                 $home=&homeserver($cnum,$cdom);
                   2920:                 if ($env{'form.forceedit'}) {
                   2921:                     $forceview = 1;
                   2922:                 } else {
                   2923:                     $forceedit = 1;
                   2924:                 }
                   2925:                 $cfile = $resurl;
                   2926:             } else {
                   2927:                 return;
                   2928:             }
                   2929:         } else {
1.1208    raeburn  2930:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2931:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   2932:                     return;
                   2933:                 }
                   2934:             } elsif (!$crsedit) {
1.1194    raeburn  2935: #
                   2936: # No edit allowed where CC has switched to student role.
                   2937: #
                   2938:                 return;
                   2939:             }
                   2940:         }
                   2941:     }
                   2942: 
1.1193    raeburn  2943:     if ($file ne '') {
                   2944:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  2945:             if (&is_course_upload($file,$cnum,$cdom)) {
                   2946:                 $uploaded = 1;
                   2947:                 $incourse = 1;
1.1193    raeburn  2948:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   2949:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  2950:                     if ($env{'form.forceedit'}) {
                   2951:                         $forceview = 1;
                   2952:                     } else {
                   2953:                         $forceedit = 1;
                   2954:                     }
1.1194    raeburn  2955:                 }
                   2956:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   2957:                 $incourse = 1;
                   2958:                 if ($env{'form.forceedit'}) {
                   2959:                     $forceview = 1;
                   2960:                 } else {
                   2961:                     $forceedit = 1;
                   2962:                 }
                   2963:                 $cfile = $resurl;
                   2964:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   2965:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   2966:                     $incourse = 1;
                   2967:                     if ($env{'form.forceedit'}) {
                   2968:                         $forceview = 1;
                   2969:                     } else {
                   2970:                         $forceedit = 1;
                   2971:                     }
                   2972:                     $cfile = $resurl;
1.1199    raeburn  2973:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  2974:                     $incourse = 1;
                   2975:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  2976:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  2977:                     $incourse = 1;
1.1199    raeburn  2978:                     if ($env{'form.forceedit'}) {
                   2979:                         $forceview = 1;
                   2980:                     } else {
                   2981:                         $forceedit = 1;
                   2982:                     }
                   2983:                     $cfile = $resurl;
1.1208    raeburn  2984:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   2985:                     $incourse = 1;
                   2986:                     if ($env{'form.forceedit'}) {
                   2987:                         $forceview = 1;
                   2988:                     } else {
                   2989:                         $forceedit = 1;
                   2990:                     }
                   2991:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  2992:                 }
                   2993:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   2994:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   2995:                 if (&is_on_map($template)) { 
                   2996:                     $incourse = 1;
                   2997:                     $forceview = 1;
                   2998:                     $cfile = $template;
1.1193    raeburn  2999:                 }
1.1199    raeburn  3000:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3001:                     $incourse = 1;
                   3002:                     if ($env{'form.forceedit'}) {
                   3003:                         $forceview = 1;
                   3004:                     } else {
                   3005:                         $forceedit = 1;
                   3006:                     }
                   3007:                     $cfile = $resurl;
                   3008:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3009:                 $incourse = 1;
                   3010:                 $forceview = 1;
                   3011:                 if ($symb) {
                   3012:                     my ($map,$id,$res)=&decode_symb($symb);
                   3013:                     $env{'request.symb'} = $symb;
                   3014:                     $cfile = &clutter($res);
                   3015:                 } else {
                   3016:                     $cfile = $env{'form.suppurl'};
                   3017:                     $cfile =~ s{^http://}{};
                   3018:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3019:                 }
1.1234    raeburn  3020:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3021:                 if ($env{'form.forceedit'}) {
                   3022:                     $forceview = 1;
                   3023:                 } else {
                   3024:                     $forceedit = 1;
                   3025:                 }
                   3026:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3027:             }
                   3028:         }
1.1194    raeburn  3029:         if ($uploaded || $incourse) {
                   3030:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3031:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3032:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3033:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3034:             # Check that the user has permission to edit this resource
                   3035:             my $setpriv = 1;
                   3036:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3037:             if (defined($cfudom)) {
                   3038:                 $home=&homeserver($cfuname,$cfudom);
                   3039:                 $cfile=$file;
                   3040:             }
                   3041:         }
1.1194    raeburn  3042:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3043:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3044:             my @ids=&current_machine_ids();
                   3045:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3046:                 $switchserver=1;
                   3047:             }
                   3048:         }
                   3049:     }
1.1194    raeburn  3050:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3051: }
                   3052: 
                   3053: sub is_course_upload {
                   3054:     my ($file,$cnum,$cdom) = @_;
                   3055:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3056:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3057:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3058:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3059:         return 1;
                   3060:     }
                   3061:     return;
                   3062: }
                   3063: 
1.1194    raeburn  3064: sub in_course {
1.1195    raeburn  3065:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3066:     if ($hideprivileged) {
                   3067:         my $skipuser;
1.1219    raeburn  3068:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3069:         my @possdoms = ($cdom);  
                   3070:         if ($coursehash{'checkforpriv'}) { 
                   3071:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3072:         }
                   3073:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3074:             $skipuser = 1;
                   3075:             if ($coursehash{'nothideprivileged'}) {
                   3076:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3077:                     my $user;
                   3078:                     if ($item =~ /:/) {
                   3079:                         $user = $item;
                   3080:                     } else {
                   3081:                         $user = join(':',split(/[\@]/,$item));
                   3082:                     }
                   3083:                     if ($user eq $uname.':'.$udom) {
                   3084:                         undef($skipuser);
                   3085:                         last;
                   3086:                     }
                   3087:                 }
                   3088:             }
                   3089:             if ($skipuser) {
                   3090:                 return 0;
                   3091:             }
                   3092:         }
                   3093:     }
1.1194    raeburn  3094:     $type ||= 'any';
                   3095:     if (!defined($cdom) || !defined($cnum)) {
                   3096:         my $cid  = $env{'request.course.id'};
                   3097:         $cdom = $env{'course.'.$cid.'.domain'};
                   3098:         $cnum = $env{'course.'.$cid.'.num'};
                   3099:     }
                   3100:     my $typesref;
1.1195    raeburn  3101:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3102:         $typesref = ['active','previous','future'];
                   3103:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3104:         $typesref = [$type];
                   3105:     }
                   3106:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3107:                               $typesref,undef,[$cdom]);
                   3108:     my ($tmp) = keys(%roles);
                   3109:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3110:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3111:     if (@course_roles > 0) {
                   3112:         return 1;
                   3113:     }
                   3114:     return 0;
                   3115: }
                   3116: 
1.478     albertel 3117: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3118: # input: action, courseID, current domain, intended
1.637     raeburn  3119: #        path to file, source of file, instruction to parse file for objects,
                   3120: #        ref to hash for embedded objects,
                   3121: #        ref to hash for codebase of java objects.
1.1095    raeburn  3122: #        reference to scalar to accommodate mime type determined
                   3123: #          from File::MMagic if $parser = parse.
1.637     raeburn  3124: #
1.485     raeburn  3125: # output: url to file (if action was uploaddoc), 
                   3126: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3127: #
1.478     albertel 3128: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3129: # course.
1.477     raeburn  3130: #
1.478     albertel 3131: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3132: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3133: #          course's home server.
1.477     raeburn  3134: #
1.478     albertel 3135: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3136: #          be copied from $source (current location) to 
                   3137: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3138: #         and will then be copied to
                   3139: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3140: #         course's home server.
1.485     raeburn  3141: #
1.481     raeburn  3142: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3143: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3144: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3145: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3146: #         in course's home server.
1.637     raeburn  3147: #
1.477     raeburn  3148: 
                   3149: sub process_coursefile {
1.1095    raeburn  3150:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3151:         $mimetype)=@_;
1.477     raeburn  3152:     my $fetchresult;
1.638     albertel 3153:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3154:     if ($action eq 'propagate') {
1.638     albertel 3155:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3156: 			     $home);
1.481     raeburn  3157:     } else {
1.477     raeburn  3158:         my $fpath = '';
                   3159:         my $fname = $file;
1.478     albertel 3160:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3161:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3162:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3163:         if ($action eq 'copy') {
                   3164:             if ($source eq '') {
                   3165:                 $fetchresult = 'no source file';
                   3166:                 return $fetchresult;
                   3167:             } else {
                   3168:                 my $destination = $filepath.'/'.$fname;
                   3169:                 rename($source,$destination);
                   3170:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3171:                                  $home);
1.481     raeburn  3172:             }
                   3173:         } elsif ($action eq 'uploaddoc') {
                   3174:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3175:             print $fh $env{'form.'.$source};
1.481     raeburn  3176:             close($fh);
1.637     raeburn  3177:             if ($parser eq 'parse') {
1.1024    raeburn  3178:                 my $mm = new File::MMagic;
1.1095    raeburn  3179:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3180:                 if ($type eq 'text/html') {
1.1024    raeburn  3181:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3182:                     unless ($parse_result eq 'ok') {
                   3183:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3184:                     }
1.637     raeburn  3185:                 }
1.1095    raeburn  3186:                 if (ref($mimetype)) {
                   3187:                     $$mimetype = $type;
                   3188:                 } 
1.637     raeburn  3189:             }
1.477     raeburn  3190:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3191:                                  $home);
1.481     raeburn  3192:             if ($fetchresult eq 'ok') {
                   3193:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3194:             } else {
                   3195:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3196:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3197:                 return '/adm/notfound.html';
                   3198:             }
1.477     raeburn  3199:         }
                   3200:     }
1.485     raeburn  3201:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3202:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3203:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3204:     }
                   3205:     return $fetchresult;
                   3206: }
                   3207: 
1.637     raeburn  3208: sub build_filepath {
                   3209:     my ($fpath) = @_;
                   3210:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3211:     unless ($fpath eq '') {
                   3212:         my @parts=split('/',$fpath);
                   3213:         foreach my $part (@parts) {
                   3214:             $filepath.= '/'.$part;
                   3215:             if ((-e $filepath)!=1) {
                   3216:                 mkdir($filepath,0777);
                   3217:             }
                   3218:         }
                   3219:     }
                   3220:     return $filepath;
                   3221: }
                   3222: 
                   3223: sub store_edited_file {
1.638     albertel 3224:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3225:     my $file = $primary_url;
                   3226:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3227:     my $fpath = '';
                   3228:     my $fname = $file;
                   3229:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3230:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3231:     my $filepath = &build_filepath($fpath);
                   3232:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3233:     print $fh $content;
                   3234:     close($fh);
1.638     albertel 3235:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3236:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3237: 			  $home);
1.637     raeburn  3238:     if ($$fetchresult eq 'ok') {
                   3239:         return '/uploaded/'.$fpath.'/'.$fname;
                   3240:     } else {
1.638     albertel 3241:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3242: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3243:         return '/adm/notfound.html';
                   3244:     }
                   3245: }
                   3246: 
1.531     albertel 3247: sub clean_filename {
1.831     albertel 3248:     my ($fname,$args)=@_;
1.315     www      3249: # Replace Windows backslashes by forward slashes
1.257     www      3250:     $fname=~s/\\/\//g;
1.831     albertel 3251:     if (!$args->{'keep_path'}) {
                   3252:         # Get rid of everything but the actual filename
                   3253: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3254:     }
1.315     www      3255: # Replace spaces by underscores
                   3256:     $fname=~s/\s+/\_/g;
                   3257: # Replace all other weird characters by nothing
1.831     albertel 3258:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3259: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3260: # numbers
                   3261:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3262:     return $fname;
                   3263: }
1.1051    raeburn  3264: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3265: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3266: # image with the same aspect ratio as the original, but with dimensions which do 
                   3267: # not exceed $resizewidth and $resizeheight.
                   3268:  
1.984     neumanie 3269: sub resizeImage {
1.1051    raeburn  3270:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3271:     my $ima = Image::Magick->new;
                   3272:     my $resized;
                   3273:     if (-e $img_path) {
                   3274:         $ima->Read($img_path);
                   3275:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3276:             my $width = $ima->Get('width');
                   3277:             my $height = $ima->Get('height');
                   3278:             if ($width > $resizewidth) {
                   3279: 	        my $factor = $width/$resizewidth;
                   3280:                 my $newheight = $height/$factor;
                   3281:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3282:                 $resized = 1;
                   3283:             }
                   3284:         }
                   3285:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3286:             my $width = $ima->Get('width');
                   3287:             my $height = $ima->Get('height');
                   3288:             if ($height > $resizeheight) {
                   3289:                 my $factor = $height/$resizeheight;
                   3290:                 my $newwidth = $width/$factor;
                   3291:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3292:                 $resized = 1;
                   3293:             }
                   3294:         }
                   3295:         if ($resized) {
                   3296:             $ima->Write($img_path);
                   3297:         }
                   3298:     }
                   3299:     return;
1.977     amueller 3300: }
                   3301: 
1.608     albertel 3302: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3303: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3304: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3305: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3306: #                                    canceloverwrite, or ''. 
                   3307: #                   if 'coursedoc': upload to the current course
                   3308: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3309: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3310: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3311: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3312: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3313: #        $allfiles - reference to hash for embedded objects
                   3314: #        $codebase - reference to hash for codebase of java objects
                   3315: #        $desuname - username for permanent storage of uploaded file
                   3316: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3317: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3318: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3319: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3320: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3321: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3322: #                    from File::MMagic.
1.858     raeburn  3323: # 
1.686     albertel 3324: # output: url of file in userspace, or error: <message> 
                   3325: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3326: 
1.531     albertel 3327: sub userfileupload {
1.1090    raeburn  3328:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3329:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3330:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3331:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3332:     $fname=&clean_filename($fname);
1.1090    raeburn  3333:     # See if there is anything left
1.257     www      3334:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3335:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3336:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3337:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3338:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3339:         my $now = time;
1.1090    raeburn  3340:         my $filepath;
1.1095    raeburn  3341:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3342:              $filepath = 'tmp/helprequests/'.$now;
                   3343:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3344:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3345:                          '_'.$env{'user.domain'}.'/pending';
                   3346:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3347:             my ($docuname,$docudom);
                   3348:             if ($destudom) {
                   3349:                 $docudom = $destudom;
                   3350:             } else {
                   3351:                 $docudom = $env{'user.domain'};
                   3352:             }
                   3353:             if ($destuname) {
                   3354:                 $docuname = $destuname;
                   3355:             } else {
                   3356:                 $docuname = $env{'user.name'};
                   3357:             }
                   3358:             if (exists($env{'form.group'})) {
                   3359:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3360:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3361:             }
                   3362:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3363:             if ($context eq 'canceloverwrite') {
                   3364:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3365:                 if (-e  $tempfile) {
                   3366:                     my @info = stat($tempfile);
                   3367:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3368:                         unlink($tempfile);
                   3369:                     }
                   3370:                 }
                   3371:                 return;
1.523     raeburn  3372:             }
                   3373:         }
1.1090    raeburn  3374:         # Create the directory if not present
1.741     raeburn  3375:         my @parts=split(/\//,$filepath);
                   3376:         my $fullpath = $perlvar{'lonDaemons'};
                   3377:         for (my $i=0;$i<@parts;$i++) {
                   3378:             $fullpath .= '/'.$parts[$i];
                   3379:             if ((-e $fullpath)!=1) {
                   3380:                 mkdir($fullpath,0777);
                   3381:             }
                   3382:         }
                   3383:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3384:         print $fh $env{'form.'.$formname};
                   3385:         close($fh);
1.1090    raeburn  3386:         if ($context eq 'existingfile') {
                   3387:             my @info = stat($fullpath.'/'.$fname);
                   3388:             return ($fullpath.'/'.$fname,$info[9]);
                   3389:         } else {
                   3390:             return $fullpath.'/'.$fname;
                   3391:         }
1.523     raeburn  3392:     }
1.995     raeburn  3393:     if ($subdir eq 'scantron') {
                   3394:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3395:     } else {
1.995     raeburn  3396:         $fname="$subdir/$fname";
                   3397:     }
1.1090    raeburn  3398:     if ($context eq 'coursedoc') {
1.638     albertel 3399: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3400: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3401:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3402:             return &finishuserfileupload($docuname,$docudom,
                   3403: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3404: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3405:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3406:         } else {
1.1218    raeburn  3407:             if ($env{'form.folder'}) {
                   3408:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3409:             }
1.638     albertel 3410:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3411: 				       $fname,$formname,$parser,
1.1095    raeburn  3412: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3413:         }
1.719     banghart 3414:     } elsif (defined($destuname)) {
                   3415:         my $docuname=$destuname;
                   3416:         my $docudom=$destudom;
1.860     raeburn  3417: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3418: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3419:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3420:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3421:     } else {
1.638     albertel 3422:         my $docuname=$env{'user.name'};
                   3423:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3424:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3425:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3426:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3427:         }
1.860     raeburn  3428: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3429: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3430:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3431:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3432:     }
1.271     www      3433: }
                   3434: 
                   3435: sub finishuserfileupload {
1.860     raeburn  3436:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3437:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3438:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3439:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3440:   
1.860     raeburn  3441:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3442:     $file=$fname;
                   3443:     if ($fname=~m|/|) {
                   3444:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3445: 	$path.=$fnamepath.'/';
                   3446:     }
1.259     www      3447:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3448:     my $count;
                   3449:     for ($count=4;$count<=$#parts;$count++) {
                   3450:         $filepath.="/$parts[$count]";
                   3451:         if ((-e $filepath)!=1) {
                   3452: 	    mkdir($filepath,0777);
                   3453:         }
                   3454:     }
1.984     neumanie 3455: 
1.258     www      3456: # Save the file
                   3457:     {
1.701     albertel 3458: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3459: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3460: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3461: 	    return '/adm/notfound.html';
                   3462: 	}
1.1090    raeburn  3463:         if ($context eq 'overwrite') {
1.1117    foxr     3464:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3465:             my $target = $filepath.'/'.$file;
                   3466:             if (-e $source) {
                   3467:                 my @info = stat($source);
                   3468:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3469:                     unless (&File::Copy::move($source,$target)) {
                   3470:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3471:                         return "Moving from $source failed";
                   3472:                     }
                   3473:                 } else {
                   3474:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3475:                 }
                   3476:             } else {
                   3477:                 return "Temporary file: $source missing";
                   3478:             }
                   3479:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3480: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3481: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3482: 	    return '/adm/notfound.html';
                   3483: 	}
1.570     albertel 3484: 	close(FH);
1.1051    raeburn  3485:         if ($resizewidth && $resizeheight) {
                   3486:             my $mm = new File::MMagic;
                   3487:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3488:             if ($mime_type =~ m{^image/}) {
                   3489: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3490:             }  
1.977     amueller 3491: 	}
1.258     www      3492:     }
1.1152    raeburn  3493:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3494:         if (ref($mimetype)) {
                   3495:             if ($$mimetype eq '') {
                   3496:                 my $mm = new File::MMagic;
                   3497:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3498:                 $$mimetype = $type;
                   3499:             }
                   3500:         }
                   3501:     }
1.637     raeburn  3502:     if ($parser eq 'parse') {
1.1152    raeburn  3503:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3504:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3505:                                                        $allfiles,$codebase);
                   3506:             unless ($parse_result eq 'ok') {
                   3507:                 &logthis('Failed to parse '.$filepath.$file.
                   3508: 	   	         ' for embedded media: '.$parse_result); 
                   3509:             }
1.637     raeburn  3510:         }
                   3511:     }
1.860     raeburn  3512:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3513:         my $input = $filepath.'/'.$file;
                   3514:         my $output = $filepath.'/'.'tn-'.$file;
                   3515:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3516:         system("convert -sample $thumbsize $input $output");
                   3517:         if (-e $filepath.'/'.'tn-'.$file) {
                   3518:             $fetchthumb  = 1; 
                   3519:         }
                   3520:     }
1.858     raeburn  3521:  
1.259     www      3522: # Notify homeserver to grep it
                   3523: #
1.984     neumanie 3524:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3525:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3526:     if ($fetchresult eq 'ok') {
1.860     raeburn  3527:         if ($fetchthumb) {
                   3528:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3529:             if ($thumbresult ne 'ok') {
                   3530:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3531:                          $docuhome.': '.$thumbresult);
                   3532:             }
                   3533:         }
1.259     www      3534: #
1.258     www      3535: # Return the URL to it
1.494     albertel 3536:         return '/uploaded/'.$path.$file;
1.263     www      3537:     } else {
1.494     albertel 3538:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3539: 		 ': '.$fetchresult);
1.263     www      3540:         return '/adm/notfound.html';
1.858     raeburn  3541:     }
1.493     albertel 3542: }
                   3543: 
1.637     raeburn  3544: sub extract_embedded_items {
1.961     raeburn  3545:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3546:     my @state = ();
1.1164    raeburn  3547:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3548:     my %javafiles = (
                   3549:                       codebase => '',
                   3550:                       code => '',
                   3551:                       archive => ''
                   3552:                     );
                   3553:     my %mediafiles = (
                   3554:                       src => '',
                   3555:                       movie => '',
                   3556:                      );
1.648     raeburn  3557:     my $p;
                   3558:     if ($content) {
                   3559:         $p = HTML::LCParser->new($content);
                   3560:     } else {
1.961     raeburn  3561:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3562:     }
1.641     albertel 3563:     while (my $t=$p->get_token()) {
1.640     albertel 3564: 	if ($t->[0] eq 'S') {
                   3565: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3566: 	    push(@state, $tagname);
1.648     raeburn  3567:             if (lc($tagname) eq 'allow') {
                   3568:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3569:             }
1.640     albertel 3570: 	    if (lc($tagname) eq 'img') {
                   3571: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3572: 	    }
1.886     albertel 3573: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3574:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3575:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3576:                 }
1.886     albertel 3577: 	    }
1.645     raeburn  3578:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3579:                 my $src;
1.645     raeburn  3580:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3581:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3582:                 } else {
1.1164    raeburn  3583:                     if ($attr->{'src'} ne '') {
                   3584:                         $src = $attr->{'src'};
                   3585:                         &add_filetype($allfiles,$src,'src');
                   3586:                     }
                   3587:                 }
                   3588:                 my $text = $p->get_trimmed_text();
                   3589:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3590:                     my @swfargs = split(/,/,$1);
                   3591:                     foreach my $item (@swfargs) {
                   3592:                         $item =~ s/["']//g;
                   3593:                         $item =~ s/^\s+//;
                   3594:                         $item =~ s/\s+$//;
                   3595:                     }
                   3596:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3597:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3598:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3599:                         } else {
                   3600:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3601:                         }
                   3602:                     }
1.645     raeburn  3603:                 }
                   3604:             }
                   3605:             if (lc($tagname) eq 'link') {
                   3606:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3607:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3608:                 }
                   3609:             }
1.640     albertel 3610: 	    if (lc($tagname) eq 'object' ||
                   3611: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3612: 		foreach my $item (keys(%javafiles)) {
                   3613: 		    $javafiles{$item} = '';
                   3614: 		}
1.1164    raeburn  3615:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3616:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3617:                 }
1.640     albertel 3618: 	    }
                   3619: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3620: 		my $name = lc($attr->{'name'});
                   3621: 		foreach my $item (keys(%javafiles)) {
                   3622: 		    if ($name eq $item) {
                   3623: 			$javafiles{$item} = $attr->{'value'};
                   3624: 			last;
                   3625: 		    }
                   3626: 		}
1.1164    raeburn  3627:                 my $pathfrom;
1.640     albertel 3628: 		foreach my $item (keys(%mediafiles)) {
                   3629: 		    if ($name eq $item) {
1.1164    raeburn  3630:                         $pathfrom = $attr->{'value'};
                   3631:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3632: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3633: 			last;
                   3634: 		    }
                   3635: 		}
1.1164    raeburn  3636:                 if ($name eq 'flashvars') {
                   3637:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3638:                 }
                   3639:                 if ($pathfrom ne '') {
                   3640:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3641:                                          $pathfrom);
                   3642:                 }
1.640     albertel 3643: 	    }
                   3644: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3645: 		foreach my $item (keys(%javafiles)) {
                   3646: 		    if ($attr->{$item}) {
                   3647: 			$javafiles{$item} = $attr->{$item};
                   3648: 			last;
                   3649: 		    }
                   3650: 		}
                   3651: 		foreach my $item (keys(%mediafiles)) {
                   3652: 		    if ($attr->{$item}) {
                   3653: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3654: 			last;
                   3655: 		    }
                   3656: 		}
1.1164    raeburn  3657:                 if (lc($tagname) eq 'embed') {
                   3658:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3659:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3660:                                              $attr->{'src'});
                   3661:                     }
                   3662:                 }
1.640     albertel 3663: 	    }
1.1243    raeburn  3664:             if (lc($tagname) eq 'iframe') {
                   3665:                 my $src = $attr->{'src'} ;
                   3666:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3667:                     &add_filetype($allfiles,$src,'src');
                   3668:                 } elsif ($src =~ m{^/}) {
                   3669:                     if ($env{'request.course.id'}) {
                   3670:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3671:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3672:                         my $url = &hreflocation('',$fullpath);
                   3673:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3674:                             my $relpath = $1;
                   3675:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3676:                                 &add_filetype($allfiles,$1,'src');
                   3677:                             }
                   3678:                         }
                   3679:                     }
                   3680:                 }
                   3681:             }
1.1164    raeburn  3682:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3683:                 pop(@state);
1.1164    raeburn  3684:             }
1.640     albertel 3685: 	} elsif ($t->[0] eq 'E') {
                   3686: 	    my ($tagname) = ($t->[1]);
                   3687: 	    if ($javafiles{'codebase'} ne '') {
                   3688: 		$javafiles{'codebase'} .= '/';
                   3689: 	    }  
                   3690: 	    if (lc($tagname) eq 'applet' ||
                   3691: 		lc($tagname) eq 'object' ||
                   3692: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3693: 		) {
                   3694: 		foreach my $item (keys(%javafiles)) {
                   3695: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3696: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3697: 			&add_filetype($allfiles,$file,$item);
                   3698: 		    }
                   3699: 		}
                   3700: 	    } 
                   3701: 	    pop @state;
                   3702: 	}
                   3703:     }
1.1164    raeburn  3704:     foreach my $id (sort(keys(%flashvars))) {
                   3705:         if ($shockwave{$id} ne '') {
                   3706:             my @pairs = split(/\&/,$flashvars{$id});
                   3707:             foreach my $pair (@pairs) {
                   3708:                 my ($key,$value) = split(/\=/,$pair);
                   3709:                 if ($key eq 'thumb') {
                   3710:                     &add_filetype($allfiles,$value,$key);
                   3711:                 } elsif ($key eq 'content') {
                   3712:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3713:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3714:                     if ($ext ne '') {
                   3715:                         &add_filetype($allfiles,$path.$value,$ext);
                   3716:                     }
                   3717:                 }
                   3718:             }
                   3719:         }
                   3720:     }
1.637     raeburn  3721:     return 'ok';
                   3722: }
                   3723: 
1.639     albertel 3724: sub add_filetype {
                   3725:     my ($allfiles,$file,$type)=@_;
                   3726:     if (exists($allfiles->{$file})) {
                   3727: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3728: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3729: 	}
                   3730:     } else {
                   3731: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3732:     }
                   3733: }
                   3734: 
1.1164    raeburn  3735: sub embedded_dependency {
                   3736:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3737:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3738:         if (($identifier ne '') &&
                   3739:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3740:             ($pathfrom ne '')) {
                   3741:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3742:             foreach my $dep (@{$related->{$identifier}}) {
                   3743:                 &add_filetype($allfiles,$path.$dep,'object');
                   3744:             }
                   3745:         }
                   3746:     }
                   3747:     return;
                   3748: }
                   3749: 
1.493     albertel 3750: sub removeuploadedurl {
1.984     neumanie 3751:     my ($url)=@_;	
                   3752:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3753:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3754: }
                   3755: 
                   3756: sub removeuserfile {
                   3757:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3758:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3759:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3760:     if ($result eq 'ok') {	
1.798     raeburn  3761:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3762:             my $metafile = $fname.'.meta';
                   3763:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3764: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3765:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3766:             my $sqlresult = 
1.823     albertel 3767:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3768:                                         'portfolio_metadata',$group,
                   3769:                                         'delete');
1.798     raeburn  3770:         }
                   3771:     }
                   3772:     return $result;
1.257     www      3773: }
1.15      www      3774: 
1.530     albertel 3775: sub mkdiruserfile {
                   3776:     my ($docuname,$docudom,$dir)=@_;
                   3777:     my $home=&homeserver($docuname,$docudom);
                   3778:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3779: }
                   3780: 
1.531     albertel 3781: sub renameuserfile {
                   3782:     my ($docuname,$docudom,$old,$new)=@_;
                   3783:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3784:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3785:                         &escape("$old").':'.&escape("$new"),$home);
                   3786:     if ($result eq 'ok') {
                   3787:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3788:             my $oldmeta = $old.'.meta';
                   3789:             my $newmeta = $new.'.meta';
                   3790:             my $metaresult = 
                   3791:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3792: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3793:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3794:             my $sqlresult = 
1.823     albertel 3795:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3796:                                         'portfolio_metadata',$group,
                   3797:                                         'delete');
1.798     raeburn  3798:         }
                   3799:     }
                   3800:     return $result;
1.531     albertel 3801: }
                   3802: 
1.14      www      3803: # ------------------------------------------------------------------------- Log
                   3804: 
                   3805: sub log {
                   3806:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3807:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3808: }
                   3809: 
                   3810: # ------------------------------------------------------------------ Course Log
1.352     www      3811: #
                   3812: # This routine flushes several buffers of non-mission-critical nature
                   3813: #
1.157     www      3814: 
                   3815: sub flushcourselogs {
1.352     www      3816:     &logthis('Flushing log buffers');
                   3817: #
                   3818: # course logs
                   3819: # This is a log of all transactions in a course, which can be used
                   3820: # for data mining purposes
                   3821: #
                   3822: # It also collects the courseid database, which lists last transaction
                   3823: # times and course titles for all courseids
                   3824: #
                   3825:     my %courseidbuffer=();
1.921     raeburn  3826:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3827:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3828: 		          &escape($courselogs{$crsid}),
                   3829: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3830: 	    delete $courselogs{$crsid};
                   3831:         } else {
                   3832:             &logthis('Failed to flush log buffer for '.$crsid);
                   3833:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3834:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3835:                         " exceeded maximum size, deleting.</font>");
                   3836:                delete $courselogs{$crsid};
                   3837:             }
1.352     www      3838:         }
1.920     raeburn  3839:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3840:             'description' => $coursedescrbuf{$crsid},
                   3841:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3842:             'type'        => $coursetypebuf{$crsid},
                   3843:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3844:         };
1.191     harris41 3845:     }
1.352     www      3846: #
                   3847: # Write course id database (reverse lookup) to homeserver of courses 
                   3848: # Is used in pickcourse
                   3849: #
1.840     albertel 3850:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3851:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3852:                                     $courseidbuffer{$crs_home},
                   3853:                                     $crs_home,'timeonly');
1.352     www      3854:     }
                   3855: #
                   3856: # File accesses
                   3857: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3858: #
1.449     matthew  3859:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3860:         if ($entry =~ /___count$/) {
                   3861:             my ($dom,$name);
1.807     albertel 3862:             ($dom,$name,undef)=
1.811     albertel 3863: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3864:             if (! defined($dom) || $dom eq '' || 
                   3865:                 ! defined($name) || $name eq '') {
1.620     albertel 3866:                 my $cid = $env{'request.course.id'};
                   3867:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3868:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3869:             }
1.450     matthew  3870:             my $value = $accesshash{$entry};
                   3871:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3872:             my %temphash=($url => $value);
1.449     matthew  3873:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3874:             if ($result eq 'ok') {
                   3875:                 delete $accesshash{$entry};
                   3876:             }
                   3877:         } else {
1.811     albertel 3878:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3879:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3880:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3881:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3882:                 delete $accesshash{$entry};
                   3883:             }
1.185     www      3884:         }
1.191     harris41 3885:     }
1.352     www      3886: #
                   3887: # Roles
                   3888: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3889: #
1.800     albertel 3890:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3891:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3892: 	    split(/\:/,$entry);
                   3893:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3894:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3895:                 $rudom,$runame) eq 'ok') {
                   3896: 	    delete $userrolehash{$entry};
                   3897:         }
                   3898:     }
1.662     raeburn  3899: #
                   3900: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3901: #
                   3902:     my %domrolebuffer = ();
1.1000    raeburn  3903:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3904:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3905:         if ($domrolebuffer{$rudom}) {
                   3906:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3907:                       '='.&escape($domainrolehash{$entry});
                   3908:         } else {
                   3909:             $domrolebuffer{$rudom}.=&escape($entry).
                   3910:                       '='.&escape($domainrolehash{$entry});
                   3911:         }
                   3912:         delete $domainrolehash{$entry};
                   3913:     }
                   3914:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3915: 	my %servers = &get_servers($dom,'library');
                   3916: 	foreach my $tryserver (keys(%servers)) {
                   3917: 	    unless (&reply('domroleput:'.$dom.':'.
                   3918: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3919: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3920: 	    }
1.662     raeburn  3921:         }
                   3922:     }
1.186     www      3923:     $dumpcount++;
1.157     www      3924: }
                   3925: 
                   3926: sub courselog {
                   3927:     my $what=shift;
1.158     www      3928:     $what=time.':'.$what;
1.620     albertel 3929:     unless ($env{'request.course.id'}) { return ''; }
                   3930:     $coursedombuf{$env{'request.course.id'}}=
                   3931:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3932:     $coursenumbuf{$env{'request.course.id'}}=
                   3933:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3934:     $coursehombuf{$env{'request.course.id'}}=
                   3935:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3936:     $coursedescrbuf{$env{'request.course.id'}}=
                   3937:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3938:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3939:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3940:     $courseownerbuf{$env{'request.course.id'}}=
                   3941:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3942:     $coursetypebuf{$env{'request.course.id'}}=
                   3943:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3944:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3945: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3946:     } else {
1.620     albertel 3947: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3948:     }
1.620     albertel 3949:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3950: 	&flushcourselogs();
                   3951:     }
1.158     www      3952: }
                   3953: 
                   3954: sub courseacclog {
                   3955:     my $fnsymb=shift;
1.620     albertel 3956:     unless ($env{'request.course.id'}) { return ''; }
                   3957:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3958:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3959:         $what.=':POST';
1.583     matthew  3960:         # FIXME: Probably ought to escape things....
1.800     albertel 3961: 	foreach my $key (keys(%env)) {
                   3962:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3963:                 my $formitem = $1;
                   3964:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3965:                     $what.=':'.$formitem.'='.$env{$key};
                   3966:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3967:                     $what.=':'.$formitem.'='.$env{$key};
                   3968:                 }
1.158     www      3969:             }
1.191     harris41 3970:         }
1.583     matthew  3971:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3972:         # FIXME: We should not be depending on a form parameter that someone
                   3973:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3974:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3975:             $what.= ':POST';
                   3976:             # FIXME: Probably ought to escape things....
                   3977:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3978:                                  'crsdiscuss') {
1.620     albertel 3979:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3980:             }
                   3981:         }
1.158     www      3982:     }
                   3983:     &courselog($what);
1.149     www      3984: }
                   3985: 
1.185     www      3986: sub countacc {
                   3987:     my $url=&declutter(shift);
1.458     matthew  3988:     return if (! defined($url) || $url eq '');
1.620     albertel 3989:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3990: #
                   3991: # Mark that this url was used in this course
                   3992: #
1.620     albertel 3993:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3994: #
                   3995: # Increase the access count for this resource in this child process
                   3996: #
1.281     www      3997:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3998:     $accesshash{$key}++;
1.185     www      3999: }
1.349     www      4000: 
1.361     www      4001: sub linklog {
                   4002:     my ($from,$to)=@_;
                   4003:     $from=&declutter($from);
                   4004:     $to=&declutter($to);
                   4005:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4006:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4007: }
1.1160    www      4008: 
                   4009: sub statslog {
                   4010:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4011:     if ($users<2) { return; }
                   4012:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4013:             'course'       => $env{'request.course.id'},
                   4014:             'sections'     => '"all"',
                   4015:             'num_students' => $users,
                   4016:             'part'         => $part,
                   4017:             'symb'         => $symb,
                   4018:             'mean_tries'   => $av_attempts,
                   4019:             'deg_of_diff'  => $degdiff});
                   4020:     foreach my $key (keys(%dynstore)) {
                   4021:         $accesshash{$key}=$dynstore{$key};
                   4022:     }
                   4023: }
1.361     www      4024:   
1.349     www      4025: sub userrolelog {
                   4026:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4027:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4028:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4029:        $userrolehash
                   4030:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4031:                     =$tend.':'.$tstart;
1.662     raeburn  4032:     }
1.1169    droeschl 4033:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4034:        $userrolehash
                   4035:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4036:                     =$tend.':'.$tstart;
                   4037:     }
1.1169    droeschl 4038:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  4039:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4040:        $domainrolehash
                   4041:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4042:                     = $tend.':'.$tstart;
                   4043:     }
1.351     www      4044: }
                   4045: 
1.957     raeburn  4046: sub courserolelog {
                   4047:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4048:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4049:         my $cdom = $1;
                   4050:         my $cnum = $2;
                   4051:         my $sec = $3;
                   4052:         my $namespace = 'rolelog';
                   4053:         my %storehash = (
                   4054:                            role    => $trole,
                   4055:                            start   => $tstart,
                   4056:                            end     => $tend,
                   4057:                            selfenroll => $selfenroll,
                   4058:                            context    => $context,
                   4059:                         );
                   4060:         if ($trole eq 'gr') {
                   4061:             $namespace = 'groupslog';
                   4062:             $storehash{'group'} = $sec;
                   4063:         } else {
                   4064:             $storehash{'section'} = $sec;
                   4065:         }
1.1188    raeburn  4066:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4067:                    $domain,$cnum,$cdom);
1.1184    raeburn  4068:         if (($trole ne 'st') || ($sec ne '')) {
                   4069:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4070:         }
                   4071:     }
                   4072:     return;
                   4073: }
                   4074: 
1.1184    raeburn  4075: sub domainrolelog {
                   4076:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4077:     if ($area =~ m{^/($match_domain)/$}) {
                   4078:         my $cdom = $1;
                   4079:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4080:         my $namespace = 'rolelog';
                   4081:         my %storehash = (
                   4082:                            role    => $trole,
                   4083:                            start   => $tstart,
                   4084:                            end     => $tend,
                   4085:                            context => $context,
                   4086:                         );
1.1188    raeburn  4087:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4088:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4089:     }
                   4090:     return;
                   4091: 
                   4092: }
                   4093: 
                   4094: sub coauthorrolelog {
                   4095:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4096:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4097:         my $audom = $1;
                   4098:         my $auname = $2;
                   4099:         my $namespace = 'rolelog';
                   4100:         my %storehash = (
                   4101:                            role    => $trole,
                   4102:                            start   => $tstart,
                   4103:                            end     => $tend,
                   4104:                            context => $context,
                   4105:                         );
1.1188    raeburn  4106:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4107:                    $domain,$auname,$audom);
1.1184    raeburn  4108:     }
                   4109:     return;
                   4110: }
                   4111: 
1.351     www      4112: sub get_course_adv_roles {
1.948     raeburn  4113:     my ($cid,$codes) = @_;
1.620     albertel 4114:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4115:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4116:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4117:     my %nothide=();
1.800     albertel 4118:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4119:         if ($user !~ /:/) {
                   4120: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4121:         } else {
                   4122:             $nothide{$user}=1;
                   4123:         }
1.470     www      4124:     }
1.1219    raeburn  4125:     my @possdoms = ($coursehash{'domain'});
                   4126:     if ($coursehash{'checkforpriv'}) {
                   4127:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4128:     }
1.351     www      4129:     my %returnhash=();
                   4130:     my %dumphash=
                   4131:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4132:     my $now=time;
1.997     raeburn  4133:     my %privileged;
1.1000    raeburn  4134:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4135: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4136:         if (($tstart) && ($tstart<0)) { next; }
                   4137:         if (($tend) && ($tend<$now)) { next; }
                   4138:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4139:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4140: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4141:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4142:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4143: 	if ($role eq 'cr') { next; }
1.948     raeburn  4144:         if ($codes) {
                   4145:             if ($section) { $role .= ':'.$section; }
                   4146:             if ($returnhash{$role}) {
                   4147:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4148:             } else {
                   4149:                 $returnhash{$role}=$username.':'.$domain;
                   4150:             }
1.351     www      4151:         } else {
1.988     raeburn  4152:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4153:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4154:             if ($returnhash{$key}) {
                   4155: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4156:             } else {
                   4157:                 $returnhash{$key}=$username.':'.$domain;
                   4158:             }
1.351     www      4159:         }
1.948     raeburn  4160:     }
1.400     www      4161:     return %returnhash;
                   4162: }
                   4163: 
                   4164: sub get_my_roles {
1.937     raeburn  4165:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4166:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4167:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4168:     my (%dumphash,%nothide);
1.1086    raeburn  4169:     if ($context eq 'userroles') {
1.1166    raeburn  4170:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4171:     } else {
1.1219    raeburn  4172:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4173:         if ($hidepriv) {
                   4174:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4175:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4176:                 if ($user !~ /:/) {
                   4177:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4178:                 } else {
                   4179:                     $nothide{$user} = 1;
                   4180:                 }
                   4181:             }
                   4182:         }
1.858     raeburn  4183:     }
1.400     www      4184:     my %returnhash=();
                   4185:     my $now=time;
1.999     raeburn  4186:     my %privileged;
1.800     albertel 4187:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4188:         my ($role,$tend,$tstart);
                   4189:         if ($context eq 'userroles') {
1.1149    raeburn  4190:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4191: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4192:         } else {
                   4193:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4194:         }
1.400     www      4195:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4196:         my $status = 'active';
1.939     raeburn  4197:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4198:             $status = 'previous';
                   4199:         } 
                   4200:         if (($tstart) && ($now<$tstart)) {
                   4201:             $status = 'future';
                   4202:         }
                   4203:         if (ref($types) eq 'ARRAY') {
                   4204:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4205:                 next;
                   4206:             } 
                   4207:         } else {
                   4208:             if ($status ne 'active') {
                   4209:                 next;
                   4210:             }
                   4211:         }
1.867     raeburn  4212:         my ($rolecode,$username,$domain,$section,$area);
                   4213:         if ($context eq 'userroles') {
1.1186    raeburn  4214:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4215:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4216:         } else {
                   4217:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4218:         }
1.832     raeburn  4219:         if (ref($roledoms) eq 'ARRAY') {
                   4220:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4221:                 next;
                   4222:             }
                   4223:         }
                   4224:         if (ref($roles) eq 'ARRAY') {
                   4225:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4226:                 if ($role =~ /^cr\//) {
                   4227:                     if (!grep(/^cr$/,@{$roles})) {
                   4228:                         next;
                   4229:                     }
1.1104    raeburn  4230:                 } elsif ($role =~ /^gr\//) {
                   4231:                     if (!grep(/^gr$/,@{$roles})) {
                   4232:                         next;
                   4233:                     }
1.922     raeburn  4234:                 } else {
                   4235:                     next;
                   4236:                 }
1.832     raeburn  4237:             }
1.867     raeburn  4238:         }
1.937     raeburn  4239:         if ($hidepriv) {
1.1219    raeburn  4240:             my @privroles = ('dc','su');
1.999     raeburn  4241:             if ($context eq 'userroles') {
1.1219    raeburn  4242:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4243:             } else {
1.1219    raeburn  4244:                 my $possdoms = [$domain];
                   4245:                 if (ref($roledoms) eq 'ARRAY') {
                   4246:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4247:                 }
1.1219    raeburn  4248:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4249:                     if (!$nothide{$username.':'.$domain}) {
                   4250:                         next;
                   4251:                     }
                   4252:                 }
1.937     raeburn  4253:             }
                   4254:         }
1.933     raeburn  4255:         if ($withsec) {
                   4256:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4257:                 $tstart.':'.$tend;
                   4258:         } else {
                   4259:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4260:         }
1.832     raeburn  4261:     }
1.373     www      4262:     return %returnhash;
1.399     www      4263: }
                   4264: 
                   4265: # ----------------------------------------------------- Frontpage Announcements
                   4266: #
                   4267: #
                   4268: 
                   4269: sub postannounce {
                   4270:     my ($server,$text)=@_;
1.844     albertel 4271:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4272:     unless ($text=~/\w/) { $text=''; }
                   4273:     return &reply('setannounce:'.&escape($text),$server);
                   4274: }
                   4275: 
                   4276: sub getannounce {
1.448     albertel 4277: 
                   4278:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4279: 	my $announcement='';
1.800     albertel 4280: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4281: 	close($fh);
1.399     www      4282: 	if ($announcement=~/\w/) { 
                   4283: 	    return 
                   4284:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4285:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4286: 	} else {
                   4287: 	    return '';
                   4288: 	}
                   4289:     } else {
                   4290: 	return '';
                   4291:     }
1.351     www      4292: }
1.353     www      4293: 
                   4294: # ---------------------------------------------------------- Course ID routines
                   4295: # Deal with domain's nohist_courseid.db files
                   4296: #
                   4297: 
                   4298: sub courseidput {
1.921     raeburn  4299:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4300:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4301:     my $outcome;
                   4302:     if ($caller eq 'timeonly') {
                   4303:         my $cids = '';
                   4304:         foreach my $item (keys(%$storehash)) {
                   4305:             $cids.=&escape($item).'&';
                   4306:         }
                   4307:         $cids=~s/\&$//;
                   4308:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4309:                           $coursehome);       
                   4310:     } else {
                   4311:         my $items = '';
                   4312:         foreach my $item (keys(%$storehash)) {
                   4313:             $items.= &escape($item).'='.
                   4314:                      &freeze_escape($$storehash{$item}).'&';
                   4315:         }
                   4316:         $items=~s/\&$//;
                   4317:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4318:                           $coursehome);
1.918     raeburn  4319:     }
                   4320:     if ($outcome eq 'unknown_cmd') {
                   4321:         my $what;
                   4322:         foreach my $cid (keys(%$storehash)) {
                   4323:             $what .= &escape($cid).'=';
1.921     raeburn  4324:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4325:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4326:             }
                   4327:             $what =~ s/\:$/&/;
                   4328:         }
                   4329:         $what =~ s/\&$//;  
                   4330:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4331:     } else {
                   4332:         return $outcome;
                   4333:     }
1.353     www      4334: }
                   4335: 
                   4336: sub courseiddump {
1.921     raeburn  4337:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4338:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4339:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4340:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4341:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4342:     my $as_hash = 1;
                   4343:     my %returnhash;
                   4344:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4345:     my %libserv = &all_library();
                   4346:     foreach my $tryserver (keys(%libserv)) {
                   4347:         if ( (  $hostidflag == 1 
                   4348: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4349: 	     || (!defined($hostidflag)) ) {
                   4350: 
1.918     raeburn  4351: 	    if (($domfilter eq '') ||
                   4352: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4353:                 my $rep;
                   4354:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4355:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4356:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4357:                                 &escape($descfilter), &escape($instcodefilter), 
                   4358:                                 &escape($ownerfilter), &escape($coursefilter),
                   4359:                                 &escape($typefilter), &escape($regexp_ok), 
                   4360:                                 $as_hash, &escape($selfenrollonly), 
                   4361:                                 &escape($catfilter), $showhidden, $caller, 
                   4362:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4363:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  4364:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4365:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 4366:                 } else {
                   4367:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4368:                              $sincefilter.':'.&escape($descfilter).':'.
                   4369:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4370:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4371:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4372:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4373:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4374:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4375:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  4376:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4377:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 4378:                 }
                   4379:                      
1.918     raeburn  4380:                 my @pairs=split(/\&/,$rep);
                   4381:                 foreach my $item (@pairs) {
                   4382:                     my ($key,$value)=split(/\=/,$item,2);
                   4383:                     $key = &unescape($key);
                   4384:                     next if ($key =~ /^error: 2 /);
                   4385:                     my $result = &thaw_unescape($value);
                   4386:                     if (ref($result) eq 'HASH') {
                   4387:                         $returnhash{$key}=$result;
                   4388:                     } else {
1.921     raeburn  4389:                         my @responses = split(/:/,$value);
                   4390:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4391:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4392:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4393:                         }
1.1008    raeburn  4394:                     }
1.353     www      4395:                 }
                   4396:             }
                   4397:         }
                   4398:     }
                   4399:     return %returnhash;
                   4400: }
                   4401: 
1.1055    raeburn  4402: sub courselastaccess {
                   4403:     my ($cdom,$cnum,$hostidref) = @_;
                   4404:     my %returnhash;
                   4405:     if ($cdom && $cnum) {
                   4406:         my $chome = &homeserver($cnum,$cdom);
                   4407:         if ($chome ne 'no_host') {
                   4408:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4409:             &extract_lastaccess(\%returnhash,$rep);
                   4410:         }
                   4411:     } else {
                   4412:         if (!$cdom) { $cdom=''; }
                   4413:         my %libserv = &all_library();
                   4414:         foreach my $tryserver (keys(%libserv)) {
                   4415:             if (ref($hostidref) eq 'ARRAY') {
                   4416:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4417:             } 
                   4418:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4419:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4420:                 &extract_lastaccess(\%returnhash,$rep);
                   4421:             }
                   4422:         }
                   4423:     }
                   4424:     return %returnhash;
                   4425: }
                   4426: 
                   4427: sub extract_lastaccess {
                   4428:     my ($returnhash,$rep) = @_;
                   4429:     if (ref($returnhash) eq 'HASH') {
                   4430:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4431:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4432:                  $rep eq '') {
                   4433:             my @pairs=split(/\&/,$rep);
                   4434:             foreach my $item (@pairs) {
                   4435:                 my ($key,$value)=split(/\=/,$item,2);
                   4436:                 $key = &unescape($key);
                   4437:                 next if ($key =~ /^error: 2 /);
                   4438:                 $returnhash->{$key} = &thaw_unescape($value);
                   4439:             }
                   4440:         }
                   4441:     }
                   4442:     return;
                   4443: }
                   4444: 
1.658     raeburn  4445: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4446: 
                   4447: sub dcmailput {
1.685     raeburn  4448:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4449:     my $status = &Apache::lonnet::critical(
1.740     www      4450:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4451:        &escape($message),$server);
1.662     raeburn  4452:     return $status;
                   4453: }
                   4454: 
1.658     raeburn  4455: sub dcmaildump {
                   4456:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4457:     my %returnhash=();
1.846     albertel 4458: 
                   4459:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4460:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4461:                                                          &escape($enddate).':';
                   4462: 	my @esc_senders=map { &escape($_)} @$senders;
                   4463: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4464: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4465:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4466:             if (($key) && ($value)) {
                   4467:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4468:             }
                   4469:         }
                   4470:     }
                   4471:     return %returnhash;
                   4472: }
1.662     raeburn  4473: # ---------------------------------------------------------- Domain roles
                   4474: 
                   4475: sub get_domain_roles {
                   4476:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4477:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4478:         $startdate = '.';
                   4479:     }
1.1018    raeburn  4480:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4481:         $enddate = '.';
                   4482:     }
1.922     raeburn  4483:     my $rolelist;
                   4484:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4485:         $rolelist = join('&',@{$roles});
1.922     raeburn  4486:     }
1.662     raeburn  4487:     my %personnel = ();
1.841     albertel 4488: 
                   4489:     my %servers = &get_servers($dom,'library');
                   4490:     foreach my $tryserver (keys(%servers)) {
                   4491: 	%{$personnel{$tryserver}}=();
                   4492: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4493: 					    &escape($startdate).':'.
                   4494: 					    &escape($enddate).':'.
                   4495: 					    &escape($rolelist), $tryserver))) {
                   4496: 	    my ($key,$value) = split(/\=/,$line,2);
                   4497: 	    if (($key) && ($value)) {
                   4498: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4499: 	    }
                   4500: 	}
1.662     raeburn  4501:     }
                   4502:     return %personnel;
                   4503: }
1.658     raeburn  4504: 
1.1057    www      4505: # ----------------------------------------------------------- Interval timing 
1.149     www      4506: 
1.1153    www      4507: {
                   4508: # Caches needed for speedup of navmaps
                   4509: # We don't want to cache this for very long at all (5 seconds at most)
                   4510: # 
                   4511: # The user for whom we cache
                   4512: my $cachedkey='';
                   4513: # The cached times for this user
                   4514: my %cachedtimes=();
                   4515: # When this was last done
1.1282    raeburn  4516: my $cachedtime='';
1.1153    www      4517: 
                   4518: sub load_all_first_access {
1.1154    raeburn  4519:     my ($uname,$udom)=@_;
1.1156    www      4520:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  4521:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  4522:         return;
                   4523:     }
                   4524:     $cachedtime=time;
                   4525:     $cachedkey=$uname.':'.$udom;
                   4526:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4527: }
                   4528: 
1.504     albertel 4529: sub get_first_access {
1.1162    raeburn  4530:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4531:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4532:     if ($argsymb) { $symb=$argsymb; }
                   4533:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4534:     if ($argmap) { $map = $argmap; }
1.926     albertel 4535:     if ($type eq 'course') {
                   4536: 	$res='course';
                   4537:     } elsif ($type eq 'map') {
1.588     albertel 4538: 	$res=&symbread($map);
                   4539:     } else {
                   4540: 	$res=$symb;
                   4541:     }
1.1153    www      4542:     &load_all_first_access($uname,$udom);
                   4543:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4544: }
                   4545: 
                   4546: sub set_first_access {
1.1162    raeburn  4547:     my ($type,$interval)=@_;
1.790     albertel 4548:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4549:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4550:     if ($type eq 'course') {
                   4551: 	$res='course';
                   4552:     } elsif ($type eq 'map') {
1.588     albertel 4553: 	$res=&symbread($map);
                   4554:     } else {
                   4555: 	$res=$symb;
                   4556:     }
1.1153    www      4557:     $cachedkey='';
1.1162    raeburn  4558:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4559:     if (!$firstaccess) {
1.1162    raeburn  4560:         my $start = time;
                   4561: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4562:                           $udom,$uname);
                   4563:         if ($putres eq 'ok') {
                   4564:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4565:                  $udom,$uname); 
                   4566:             &appenv(
                   4567:                      {
                   4568:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4569:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4570:                      }
                   4571:                   );
                   4572:         }
                   4573:         return $putres;
1.505     albertel 4574:     }
                   4575:     return 'already_set';
1.504     albertel 4576: }
1.1153    www      4577: }
1.1282    raeburn  4578: 
1.110     www      4579: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4580: 
                   4581: sub expirespread {
                   4582:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4583:     my $cid=$env{'request.course.id'}; 
1.110     www      4584:     if ($cid) {
                   4585:        my $now=time;
                   4586:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4587:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4588:                             $env{'course.'.$cid.'.num'}.
1.110     www      4589: 	        	    ':nohist_expirationdates:'.
                   4590:                             &escape($key).'='.$now,
1.620     albertel 4591:                             $env{'course.'.$cid.'.home'})
1.110     www      4592:     }
                   4593:     return 'ok';
1.14      www      4594: }
                   4595: 
1.109     www      4596: # ----------------------------------------------------- Devalidate Spreadsheets
                   4597: 
                   4598: sub devalidate {
1.325     www      4599:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4600:     my $cid=$env{'request.course.id'}; 
1.109     www      4601:     if ($cid) {
1.391     matthew  4602:         # delete the stored spreadsheets for
                   4603:         # - the student level sheet of this user in course's homespace
                   4604:         # - the assessment level sheet for this resource 
                   4605:         #   for this user in user's homespace
1.553     albertel 4606: 	# - current conditional state info
1.325     www      4607: 	my $key=$uname.':'.$udom.':';
1.109     www      4608:         my $status=
1.299     matthew  4609: 	    &del('nohist_calculatedsheets',
1.391     matthew  4610: 		 [$key.'studentcalc:'],
1.620     albertel 4611: 		 $env{'course.'.$cid.'.domain'},
                   4612: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4613: 		.' '.
                   4614: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4615: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4616:         unless ($status eq 'ok ok') {
                   4617:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4618:                     $uname.' at '.$udom.' for '.
1.109     www      4619: 		    $symb.': '.$status);
1.133     albertel 4620:         }
1.553     albertel 4621: 	&delenv('user.state.'.$cid);
1.109     www      4622:     }
                   4623: }
                   4624: 
1.265     albertel 4625: sub get_scalar {
                   4626:     my ($string,$end) = @_;
                   4627:     my $value;
                   4628:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4629: 	$value = $1;
                   4630:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4631: 	$value = $1;
                   4632:     }
                   4633:     return &unescape($value);
                   4634: }
                   4635: 
                   4636: sub array2str {
                   4637:   my (@array) = @_;
                   4638:   my $result=&arrayref2str(\@array);
                   4639:   $result=~s/^__ARRAY_REF__//;
                   4640:   $result=~s/__END_ARRAY_REF__$//;
                   4641:   return $result;
                   4642: }
                   4643: 
1.204     albertel 4644: sub arrayref2str {
                   4645:   my ($arrayref) = @_;
1.265     albertel 4646:   my $result='__ARRAY_REF__';
1.204     albertel 4647:   foreach my $elem (@$arrayref) {
1.265     albertel 4648:     if(ref($elem) eq 'ARRAY') {
                   4649:       $result.=&arrayref2str($elem).'&';
                   4650:     } elsif(ref($elem) eq 'HASH') {
                   4651:       $result.=&hashref2str($elem).'&';
                   4652:     } elsif(ref($elem)) {
                   4653:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4654:     } else {
                   4655:       $result.=&escape($elem).'&';
                   4656:     }
                   4657:   }
                   4658:   $result=~s/\&$//;
1.265     albertel 4659:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4660:   return $result;
                   4661: }
                   4662: 
1.168     albertel 4663: sub hash2str {
1.204     albertel 4664:   my (%hash) = @_;
                   4665:   my $result=&hashref2str(\%hash);
1.265     albertel 4666:   $result=~s/^__HASH_REF__//;
                   4667:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4668:   return $result;
                   4669: }
                   4670: 
                   4671: sub hashref2str {
                   4672:   my ($hashref)=@_;
1.265     albertel 4673:   my $result='__HASH_REF__';
1.800     albertel 4674:   foreach my $key (sort(keys(%$hashref))) {
                   4675:     if (ref($key) eq 'ARRAY') {
                   4676:       $result.=&arrayref2str($key).'=';
                   4677:     } elsif (ref($key) eq 'HASH') {
                   4678:       $result.=&hashref2str($key).'=';
                   4679:     } elsif (ref($key)) {
1.265     albertel 4680:       $result.='=';
1.800     albertel 4681:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4682:     } else {
1.1132    raeburn  4683: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4684:     }
                   4685: 
1.800     albertel 4686:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4687:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4688:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4689:       $result.=&hashref2str($hashref->{$key}).'&';
                   4690:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4691:        $result.='&';
1.800     albertel 4692:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4693:     } else {
1.800     albertel 4694:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4695:     }
                   4696:   }
1.168     albertel 4697:   $result=~s/\&$//;
1.265     albertel 4698:   $result .= '__END_HASH_REF__';
1.168     albertel 4699:   return $result;
                   4700: }
                   4701: 
                   4702: sub str2hash {
1.265     albertel 4703:     my ($string)=@_;
                   4704:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4705:     return %$hash;
                   4706: }
                   4707: 
                   4708: sub str2hashref {
1.168     albertel 4709:   my ($string) = @_;
1.265     albertel 4710: 
                   4711:   my %hash;
                   4712: 
                   4713:   if($string !~ /^__HASH_REF__/) {
                   4714:       if (! ($string eq '' || !defined($string))) {
                   4715: 	  $hash{'error'}='Not hash reference';
                   4716:       }
                   4717:       return (\%hash, $string);
                   4718:   }
                   4719: 
                   4720:   $string =~ s/^__HASH_REF__//;
                   4721: 
                   4722:   while($string !~ /^__END_HASH_REF__/) {
                   4723:       #key
                   4724:       my $key='';
                   4725:       if($string =~ /^__HASH_REF__/) {
                   4726:           ($key, $string)=&str2hashref($string);
                   4727:           if(defined($key->{'error'})) {
                   4728:               $hash{'error'}='Bad data';
                   4729:               return (\%hash, $string);
                   4730:           }
                   4731:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4732:           ($key, $string)=&str2arrayref($string);
                   4733:           if($key->[0] eq 'Array reference error') {
                   4734:               $hash{'error'}='Bad data';
                   4735:               return (\%hash, $string);
                   4736:           }
                   4737:       } else {
                   4738:           $string =~ s/^(.*?)=//;
1.267     albertel 4739: 	  $key=&unescape($1);
1.265     albertel 4740:       }
                   4741:       $string =~ s/^=//;
                   4742: 
                   4743:       #value
                   4744:       my $value='';
                   4745:       if($string =~ /^__HASH_REF__/) {
                   4746:           ($value, $string)=&str2hashref($string);
                   4747:           if(defined($value->{'error'})) {
                   4748:               $hash{'error'}='Bad data';
                   4749:               return (\%hash, $string);
                   4750:           }
                   4751:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4752:           ($value, $string)=&str2arrayref($string);
                   4753:           if($value->[0] eq 'Array reference error') {
                   4754:               $hash{'error'}='Bad data';
                   4755:               return (\%hash, $string);
                   4756:           }
                   4757:       } else {
                   4758: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4759:       }
                   4760:       $string =~ s/^&//;
                   4761: 
                   4762:       $hash{$key}=$value;
1.204     albertel 4763:   }
1.265     albertel 4764: 
                   4765:   $string =~ s/^__END_HASH_REF__//;
                   4766: 
                   4767:   return (\%hash, $string);
1.204     albertel 4768: }
                   4769: 
                   4770: sub str2array {
1.265     albertel 4771:     my ($string)=@_;
                   4772:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4773:     return @$array;
                   4774: }
                   4775: 
                   4776: sub str2arrayref {
1.204     albertel 4777:   my ($string) = @_;
1.265     albertel 4778:   my @array;
                   4779: 
                   4780:   if($string !~ /^__ARRAY_REF__/) {
                   4781:       if (! ($string eq '' || !defined($string))) {
                   4782: 	  $array[0]='Array reference error';
                   4783:       }
                   4784:       return (\@array, $string);
                   4785:   }
                   4786: 
                   4787:   $string =~ s/^__ARRAY_REF__//;
                   4788: 
                   4789:   while($string !~ /^__END_ARRAY_REF__/) {
                   4790:       my $value='';
                   4791:       if($string =~ /^__HASH_REF__/) {
                   4792:           ($value, $string)=&str2hashref($string);
                   4793:           if(defined($value->{'error'})) {
                   4794:               $array[0] ='Array reference error';
                   4795:               return (\@array, $string);
                   4796:           }
                   4797:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4798:           ($value, $string)=&str2arrayref($string);
                   4799:           if($value->[0] eq 'Array reference error') {
                   4800:               $array[0] ='Array reference error';
                   4801:               return (\@array, $string);
                   4802:           }
                   4803:       } else {
                   4804: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4805:       }
                   4806:       $string =~ s/^&//;
                   4807: 
                   4808:       push(@array, $value);
1.191     harris41 4809:   }
1.265     albertel 4810: 
                   4811:   $string =~ s/^__END_ARRAY_REF__//;
                   4812: 
                   4813:   return (\@array, $string);
1.168     albertel 4814: }
                   4815: 
1.167     albertel 4816: # -------------------------------------------------------------------Temp Store
                   4817: 
1.168     albertel 4818: sub tmpreset {
                   4819:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4820:   if (!$symb) {
                   4821:     $symb=&symbread();
1.620     albertel 4822:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4823:   }
                   4824:   $symb=escape($symb);
                   4825: 
1.620     albertel 4826:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4827:   $namespace=~s/\//\_/g;
                   4828:   $namespace=~s/\W//g;
                   4829: 
1.620     albertel 4830:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4831:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4832:   if ($domain eq 'public' && $stuname eq 'public') {
                   4833:       $stuname=$ENV{'REMOTE_ADDR'};
                   4834:   }
1.1117    foxr     4835:   my $path=LONCAPA::tempdir();
1.168     albertel 4836:   my %hash;
                   4837:   if (tie(%hash,'GDBM_File',
                   4838: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4839: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4840:     foreach my $key (keys(%hash)) {
1.180     albertel 4841:       if ($key=~ /:$symb/) {
1.168     albertel 4842: 	delete($hash{$key});
                   4843:       }
                   4844:     }
                   4845:   }
                   4846: }
                   4847: 
1.167     albertel 4848: sub tmpstore {
1.168     albertel 4849:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4850: 
                   4851:   if (!$symb) {
                   4852:     $symb=&symbread();
1.620     albertel 4853:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4854:   }
                   4855:   $symb=escape($symb);
                   4856: 
                   4857:   if (!$namespace) {
                   4858:     # I don't think we would ever want to store this for a course.
                   4859:     # it seems this will only be used if we don't have a course.
1.620     albertel 4860:     #$namespace=$env{'request.course.id'};
1.168     albertel 4861:     #if (!$namespace) {
1.620     albertel 4862:       $namespace=$env{'request.state'};
1.168     albertel 4863:     #}
                   4864:   }
                   4865:   $namespace=~s/\//\_/g;
                   4866:   $namespace=~s/\W//g;
1.620     albertel 4867:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4868:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4869:   if ($domain eq 'public' && $stuname eq 'public') {
                   4870:       $stuname=$ENV{'REMOTE_ADDR'};
                   4871:   }
1.168     albertel 4872:   my $now=time;
                   4873:   my %hash;
1.1117    foxr     4874:   my $path=LONCAPA::tempdir();
1.168     albertel 4875:   if (tie(%hash,'GDBM_File',
                   4876: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4877: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4878:     $hash{"version:$symb"}++;
                   4879:     my $version=$hash{"version:$symb"};
                   4880:     my $allkeys=''; 
                   4881:     foreach my $key (keys(%$storehash)) {
                   4882:       $allkeys.=$key.':';
1.591     albertel 4883:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4884:     }
                   4885:     $hash{"$version:$symb:timestamp"}=$now;
                   4886:     $allkeys.='timestamp';
                   4887:     $hash{"$version:keys:$symb"}=$allkeys;
                   4888:     if (untie(%hash)) {
                   4889:       return 'ok';
                   4890:     } else {
                   4891:       return "error:$!";
                   4892:     }
                   4893:   } else {
                   4894:     return "error:$!";
                   4895:   }
                   4896: }
1.167     albertel 4897: 
1.168     albertel 4898: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4899: 
1.168     albertel 4900: sub tmprestore {
                   4901:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4902: 
1.168     albertel 4903:   if (!$symb) {
                   4904:     $symb=&symbread();
1.620     albertel 4905:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4906:   }
                   4907:   $symb=escape($symb);
                   4908: 
1.620     albertel 4909:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4910: 
1.620     albertel 4911:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4912:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4913:   if ($domain eq 'public' && $stuname eq 'public') {
                   4914:       $stuname=$ENV{'REMOTE_ADDR'};
                   4915:   }
1.168     albertel 4916:   my %returnhash;
                   4917:   $namespace=~s/\//\_/g;
                   4918:   $namespace=~s/\W//g;
                   4919:   my %hash;
1.1117    foxr     4920:   my $path=LONCAPA::tempdir();
1.168     albertel 4921:   if (tie(%hash,'GDBM_File',
                   4922: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4923: 	  &GDBM_READER(),0640)) {
1.168     albertel 4924:     my $version=$hash{"version:$symb"};
                   4925:     $returnhash{'version'}=$version;
                   4926:     my $scope;
                   4927:     for ($scope=1;$scope<=$version;$scope++) {
                   4928:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4929:       my @keys=split(/:/,$vkeys);
                   4930:       my $key;
                   4931:       $returnhash{"$scope:keys"}=$vkeys;
                   4932:       foreach $key (@keys) {
1.591     albertel 4933: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4934: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4935:       }
                   4936:     }
1.168     albertel 4937:     if (!(untie(%hash))) {
                   4938:       return "error:$!";
                   4939:     }
                   4940:   } else {
                   4941:     return "error:$!";
                   4942:   }
                   4943:   return %returnhash;
1.167     albertel 4944: }
                   4945: 
1.9       www      4946: # ----------------------------------------------------------------------- Store
                   4947: 
                   4948: sub store {
1.1269    raeburn  4949:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      4950:     my $home='';
                   4951: 
1.168     albertel 4952:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4953: 
1.213     www      4954:     $symb=&symbclean($symb);
1.122     albertel 4955:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4956: 
1.620     albertel 4957:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4958:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4959: 
                   4960:     &devalidate($symb,$stuname,$domain);
1.109     www      4961: 
                   4962:     $symb=escape($symb);
1.187     www      4963:     if (!$namespace) { 
1.620     albertel 4964:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4965:           return ''; 
                   4966:        } 
                   4967:     }
1.620     albertel 4968:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4969: 
                   4970:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4971:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4972: 
1.12      www      4973:     my $namevalue='';
1.800     albertel 4974:     foreach my $key (keys(%$storehash)) {
                   4975:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4976:     }
1.12      www      4977:     $namevalue=~s/\&$//;
1.187     www      4978:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  4979:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      4980: }
                   4981: 
1.47      www      4982: # -------------------------------------------------------------- Critical Store
                   4983: 
                   4984: sub cstore {
1.1269    raeburn  4985:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      4986:     my $home='';
                   4987: 
1.168     albertel 4988:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4989: 
1.213     www      4990:     $symb=&symbclean($symb);
1.122     albertel 4991:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4992: 
1.620     albertel 4993:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4994:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4995: 
                   4996:     &devalidate($symb,$stuname,$domain);
1.109     www      4997: 
                   4998:     $symb=escape($symb);
1.187     www      4999:     if (!$namespace) { 
1.620     albertel 5000:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5001:           return ''; 
                   5002:        } 
                   5003:     }
1.620     albertel 5004:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5005: 
                   5006:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5007:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5008: 
1.47      www      5009:     my $namevalue='';
1.800     albertel 5010:     foreach my $key (keys(%$storehash)) {
                   5011:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5012:     }
1.47      www      5013:     $namevalue=~s/\&$//;
1.187     www      5014:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5015:     return critical
1.1269    raeburn  5016:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5017: }
                   5018: 
1.9       www      5019: # --------------------------------------------------------------------- Restore
                   5020: 
                   5021: sub restore {
1.124     www      5022:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5023:     my $home='';
                   5024: 
1.168     albertel 5025:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5026: 
1.122     albertel 5027:     if (!$symb) {
1.1224    raeburn  5028:         return if ($namespace eq 'courserequests');
                   5029:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5030:     } else {
1.1224    raeburn  5031:         unless ($namespace eq 'courserequests') {
                   5032:             $symb=&escape(&symbclean($symb));
                   5033:         }
1.122     albertel 5034:     }
1.188     www      5035:     if (!$namespace) { 
1.620     albertel 5036:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5037:           return ''; 
                   5038:        } 
                   5039:     }
1.620     albertel 5040:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5041:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5042:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5043:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5044: 
1.12      www      5045:     my %returnhash=();
1.800     albertel 5046:     foreach my $line (split(/\&/,$answer)) {
                   5047: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5048:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5049:     }
1.75      www      5050:     my $version;
                   5051:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5052:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5053:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5054:        }
1.75      www      5055:     }
1.13      www      5056:     return %returnhash;
1.34      www      5057: }
                   5058: 
                   5059: # ---------------------------------------------------------- Course Description
1.1118    foxr     5060: #
                   5061: #  
1.34      www      5062: 
                   5063: sub coursedescription {
1.731     albertel 5064:     my ($courseid,$args)=@_;
1.34      www      5065:     $courseid=~s/^\///;
1.49      www      5066:     $courseid=~s/\_/\//g;
1.34      www      5067:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5068:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5069:     my $normalid=$cdomain.'_'.$cnum;
                   5070:     # need to always cache even if we get errors otherwise we keep 
                   5071:     # trying and trying and trying to get the course description.
                   5072:     my %envhash=();
                   5073:     my %returnhash=();
1.731     albertel 5074:     
                   5075:     my $expiretime=600;
                   5076:     if ($env{'request.course.id'} eq $normalid) {
                   5077: 	$expiretime=120;
                   5078:     }
                   5079: 
                   5080:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5081:     if (!$args->{'freshen_cache'}
                   5082: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5083: 	foreach my $key (keys(%env)) {
                   5084: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5085: 	    my ($setting) = $1;
                   5086: 	    $returnhash{$setting} = $env{$key};
                   5087: 	}
                   5088: 	return %returnhash;
                   5089:     }
                   5090: 
1.1118    foxr     5091:     # get the data again
                   5092: 
1.731     albertel 5093:     if (!$args->{'one_time'}) {
                   5094: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5095:     }
1.811     albertel 5096: 
1.34      www      5097:     if ($chome ne 'no_host') {
1.302     albertel 5098:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5099:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5100: 	   my $username = $env{'user.name'}; # Defult username
                   5101: 	   if(defined $args->{'user'}) {
                   5102: 	       $username = $args->{'user'};
                   5103: 	   }
1.129     albertel 5104:            $returnhash{'home'}= $chome;
                   5105: 	   $returnhash{'domain'} = $cdomain;
                   5106: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5107:            if (!defined($returnhash{'type'})) {
                   5108:                $returnhash{'type'} = 'Course';
                   5109:            }
1.130     albertel 5110:            while (my ($name,$value) = each %returnhash) {
1.53      www      5111:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5112:            }
1.270     www      5113:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5114:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5115: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5116:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5117:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5118:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5119:        }
                   5120:     }
1.731     albertel 5121:     if (!$args->{'one_time'}) {
1.949     raeburn  5122: 	&appenv(\%envhash);
1.731     albertel 5123:     }
1.302     albertel 5124:     return %returnhash;
1.461     www      5125: }
                   5126: 
1.1080    raeburn  5127: sub update_released_required {
                   5128:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5129:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5130:         $cid = $env{'request.course.id'};
                   5131:         $cdom = $env{'course.'.$cid.'.domain'};
                   5132:         $cnum = $env{'course.'.$cid.'.num'};
                   5133:         $chome = $env{'course.'.$cid.'.home'};
                   5134:     }
                   5135:     if ($needsrelease) {
                   5136:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5137:         my $needsupdate;
                   5138:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5139:             $needsupdate = 1;
                   5140:         } else {
                   5141:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5142:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5143:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5144:                 $needsupdate = 1;
                   5145:             }
                   5146:         }
                   5147:         if ($needsupdate) {
                   5148:             my %needshash = (
                   5149:                              'internal.releaserequired' => $needsrelease,
                   5150:                             );
                   5151:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5152:             if ($putresult eq 'ok') {
                   5153:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5154:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5155:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5156:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5157:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5158:                 }
                   5159:             }
                   5160:         }
                   5161:     }
                   5162:     return;
                   5163: }
                   5164: 
1.461     www      5165: # -------------------------------------------------See if a user is privileged
                   5166: 
                   5167: sub privileged {
1.1219    raeburn  5168:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5169:     my $now = time;
1.1219    raeburn  5170:     my $roles;
                   5171:     if (ref($possroles) eq 'ARRAY') {
                   5172:         $roles = $possroles; 
                   5173:     } else {
                   5174:         $roles = ['dc','su'];
                   5175:     }
                   5176:     if (ref($possdomains) eq 'ARRAY') {
                   5177:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5178:         foreach my $dom (@{$possdomains}) {
                   5179:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5180:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5181:                 foreach my $role (@{$roles}) {
                   5182:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5183:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5184:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5185:                             return 1 unless (($end && $end < $now) ||
                   5186:                                              ($start && $start > $now));
                   5187:                         }
                   5188:                     }
                   5189:                 }
                   5190:             }
                   5191:         }
                   5192:     } else {
                   5193:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5194:         my $now = time;
1.1170    droeschl 5195: 
1.1275    musolffc 5196:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5197:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5198:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5199:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5200:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5201:             }
1.1219    raeburn  5202:         }
                   5203:     }
                   5204:     return 0;
                   5205: }
1.1170    droeschl 5206: 
1.1219    raeburn  5207: sub privileged_by_domain {
                   5208:     my ($domains,$roles) = @_;
                   5209:     my %privileged = ();
                   5210:     my $cachetime = 60*60*24;
                   5211:     my $now = time;
                   5212:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5213:         return %privileged;
                   5214:     }
                   5215:     foreach my $dom (@{$domains}) {
                   5216:         next if (ref($privileged{$dom}) eq 'HASH');
                   5217:         my $needroles;
                   5218:         foreach my $role (@{$roles}) {
                   5219:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5220:             if (defined($cached)) {
                   5221:                 if (ref($result) eq 'HASH') {
                   5222:                     $privileged{$dom}{$role} = $result;
                   5223:                 }
                   5224:             } else {
                   5225:                 $needroles = 1;
                   5226:             }
                   5227:         }
                   5228:         if ($needroles) {
                   5229:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5230:             $privileged{$dom} = {};
                   5231:             foreach my $server (keys(%dompersonnel)) {
                   5232:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5233:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5234:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5235:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5236:                         next if ($end && $end < $now);
                   5237:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5238:                             $dompersonnel{$server}{$item};
                   5239:                     }
                   5240:                 }
                   5241:             }
                   5242:             if (ref($privileged{$dom}) eq 'HASH') {
                   5243:                 foreach my $role (@{$roles}) {
                   5244:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5245:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5246:                     } else {
                   5247:                         my %hash = ();
                   5248:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5249:                     }
                   5250:                 }
                   5251:             }
                   5252:         }
                   5253:     }
                   5254:     return %privileged;
1.9       www      5255: }
1.1       albertel 5256: 
1.103     harris41 5257: # -------------------------------------------------------- Get user privileges
1.11      www      5258: 
                   5259: sub rolesinit {
1.1169    droeschl 5260:     my ($domain, $username) = @_;
                   5261:     my %userroles = ('user.login.time' => time);
                   5262:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5263: 
                   5264:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5265:     # also, blocking can be triggered by an activating timer
                   5266:     # it's saved in the user's %env.
                   5267:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5268:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5269:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5270:         %timerintchk, %timerintenv);
                   5271: 
1.1162    raeburn  5272:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5273:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5274:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5275:     }
1.1169    droeschl 5276: 
1.1162    raeburn  5277:     foreach my $key (keys(%timerinterval)) {
                   5278:         my ($cid,$rest) = split(/\0/,$key);
                   5279:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5280:     }
1.1169    droeschl 5281: 
1.11      www      5282:     my %allroles=();
1.1162    raeburn  5283:     my %allgroups=();
1.11      www      5284: 
1.1274    raeburn  5285:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5286:         my $role = $rolesdump{$area};
                   5287:         $area =~ s/\_\w\w$//;
                   5288: 
                   5289:         my ($trole, $tend, $tstart, $group_privs);
                   5290: 
                   5291:         if ($role =~ /^cr/) {
                   5292:         # Custom role, defined by a user 
                   5293:         # e.g., user.role.cr/msu/smith/mynewrole
                   5294:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5295:                 $trole = $1;
                   5296:                 ($tend, $tstart) = split('_', $2);
                   5297:             } else {
                   5298:                 $trole = $role;
                   5299:             }
                   5300:         } elsif ($role =~ m|^gr/|) {
                   5301:         # Role of member in a group, defined within a course/community
                   5302:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5303:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5304:             next if $tstart eq '-1';
                   5305:             ($trole, $group_privs) = split(/\//, $trole);
                   5306:             $group_privs = &unescape($group_privs);
                   5307:         } else {
                   5308:         # Just a normal role, defined in roles.tab
                   5309:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5310:         }
                   5311: 
                   5312:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5313:                  $username);
                   5314:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5315: 
                   5316:         # role expired or not available yet?
                   5317:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5318:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5319: 
                   5320:         next if $area eq '' or $trole eq '';
                   5321: 
                   5322:         my $spec = "$trole.$area";
                   5323:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5324: 
                   5325:         if ($trole =~ /^cr\//) {
                   5326:         # Custom role, defined by a user
                   5327:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5328:         } elsif ($trole eq 'gr') {
                   5329:         # Role of a member in a group, defined within a course/community
                   5330:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5331:             next;
                   5332:         } else {
                   5333:         # Normal role, defined in roles.tab
                   5334:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5335:         }
                   5336: 
                   5337:         my $cid = $tdomain.'_'.$trest;
                   5338:         unless ($firstaccchk{$cid}) {
                   5339:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5340:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5341:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5342:                         $coursetimerstarts{$cid}{$item}; 
                   5343:                 }
                   5344:             }
                   5345:             $firstaccchk{$cid} = 1;
                   5346:         }
                   5347:         unless ($timerintchk{$cid}) {
                   5348:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5349:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5350:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5351:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5352:                 }
1.12      www      5353:             }
1.1169    droeschl 5354:             $timerintchk{$cid} = 1;
1.191     harris41 5355:         }
1.11      www      5356:     }
1.1169    droeschl 5357: 
                   5358:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5359:         \%allroles, \%allgroups);
                   5360:     $env{'user.adv'} = $userroles{'user.adv'};
                   5361: 
1.1162    raeburn  5362:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5363: }
                   5364: 
1.567     raeburn  5365: sub set_arearole {
1.1215    raeburn  5366:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5367:     unless ($nolog) {
1.567     raeburn  5368: # log the associated role with the area
1.1215    raeburn  5369:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5370:     }
1.743     albertel 5371:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5372: }
                   5373: 
                   5374: sub custom_roleprivs {
                   5375:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5376:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5377:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5378:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5379:         my ($rdummy,$roledef)=
                   5380:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5381:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5382:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5383:             if (defined($syspriv)) {
1.1043    raeburn  5384:                 if ($trest =~ /^$match_community$/) {
                   5385:                     $syspriv =~ s/bre\&S//; 
                   5386:                 }
1.567     raeburn  5387:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5388:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5389:             }
                   5390:             if ($tdomain ne '') {
                   5391:                 if (defined($dompriv)) {
                   5392:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5393:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5394:                 }
                   5395:                 if (($trest ne '') && (defined($coursepriv))) {
                   5396:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5397:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5398:                 }
                   5399:             }
                   5400:         }
                   5401:     }
                   5402: }
                   5403: 
1.678     raeburn  5404: sub group_roleprivs {
                   5405:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5406:     my $access = 1;
                   5407:     my $now = time;
                   5408:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5409:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5410:     if ($access) {
1.811     albertel 5411:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5412:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5413:     }
                   5414: }
1.567     raeburn  5415: 
                   5416: sub standard_roleprivs {
                   5417:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5418:     if (defined($pr{$trole.':s'})) {
                   5419:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5420:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5421:     }
                   5422:     if ($tdomain ne '') {
                   5423:         if (defined($pr{$trole.':d'})) {
                   5424:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5425:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5426:         }
                   5427:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5428:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5429:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5430:         }
                   5431:     }
                   5432: }
                   5433: 
                   5434: sub set_userprivs {
1.1064    raeburn  5435:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5436:     my $author=0;
                   5437:     my $adv=0;
1.678     raeburn  5438:     my %grouproles = ();
                   5439:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5440:         my @groupkeys; 
1.1000    raeburn  5441:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5442:             push(@groupkeys,$role);
                   5443:         }
                   5444:         if (ref($groups_roles) eq 'HASH') {
                   5445:             foreach my $key (keys(%{$groups_roles})) {
                   5446:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5447:                     push(@groupkeys,$key);
                   5448:                 }
                   5449:             }
                   5450:         }
                   5451:         if (@groupkeys > 0) {
                   5452:             foreach my $role (@groupkeys) {
                   5453:                 my ($trole,$area,$sec,$extendedarea);
                   5454:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5455:                     $trole = $1;
                   5456:                     $area = $2;
                   5457:                     $sec = $3;
                   5458:                     $extendedarea = $area.$sec;
                   5459:                     if (exists($$allgroups{$area})) {
                   5460:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5461:                             my $spec = $trole.'.'.$extendedarea;
                   5462:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5463:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5464:                         }
1.678     raeburn  5465:                     }
                   5466:                 }
                   5467:             }
                   5468:         }
                   5469:     }
1.800     albertel 5470:     foreach my $group (keys(%grouproles)) {
                   5471:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5472:     }
1.800     albertel 5473:     foreach my $role (keys(%{$allroles})) {
                   5474:         my %thesepriv;
1.941     raeburn  5475:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5476:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5477:             if ($item ne '') {
                   5478:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5479:                 if ($restrictions eq '') {
                   5480:                     $thesepriv{$privilege}='F';
                   5481:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5482:                     $thesepriv{$privilege}.=$restrictions;
                   5483:                 }
                   5484:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5485:             }
                   5486:         }
                   5487:         my $thesestr='';
1.1104    raeburn  5488:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5489: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5490: 	}
                   5491:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5492:     }
                   5493:     return ($author,$adv);
                   5494: }
                   5495: 
1.994     raeburn  5496: sub role_status {
1.1104    raeburn  5497:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5498:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5499:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5500:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5501:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5502:             $$where = '/'.$two;
1.994     raeburn  5503:             $$trolecode=$$role.'.'.$$where;
                   5504:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5505:             $$tstatus='is';
1.1104    raeburn  5506:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5507:                 $$tstatus='future';
1.1034    raeburn  5508:                 if ($$tstart<$now) {
                   5509:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5510:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5511:                             my (%allroles,%allgroups,$group_privs,
                   5512:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5513:                             my %userroles = (
                   5514:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5515:                             );
1.1064    raeburn  5516:                             @rolecodes = ('cm'); 
1.1002    raeburn  5517:                             my $spec=$$role.'.'.$$where;
                   5518:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5519:                             if ($$role =~ /^cr\//) {
                   5520:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5521:                                 push(@rolecodes,'cr');
1.1002    raeburn  5522:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5523:                                 push(@rolecodes,$$role);
1.1002    raeburn  5524:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5525:                                                     $env{'user.name'});
1.1064    raeburn  5526:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5527:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5528:                                 $group_privs = &unescape($group_privs);
                   5529:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5530:                                 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  5531:                                 &get_groups_roles($tdomain,$trest,
                   5532:                                                   \%course_roles,\@rolecodes,
                   5533:                                                   \%groups_roles);
1.1002    raeburn  5534:                             } else {
1.1064    raeburn  5535:                                 push(@rolecodes,$$role);
1.1002    raeburn  5536:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5537:                             }
1.1064    raeburn  5538:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5539:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5540:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5541:                         }
                   5542:                     }
1.1034    raeburn  5543:                     $$tstatus = 'is';
1.1002    raeburn  5544:                 }
1.994     raeburn  5545:             }
                   5546:             if ($$tend) {
1.1104    raeburn  5547:                 if ($$tend<$update) {
1.994     raeburn  5548:                     $$tstatus='expired';
                   5549:                 } elsif ($$tend<$now) {
                   5550:                     $$tstatus='will_not';
                   5551:                 }
                   5552:             }
                   5553:         }
                   5554:     }
                   5555: }
                   5556: 
1.1104    raeburn  5557: sub get_groups_roles {
                   5558:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5559:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5560:                   (ref($rolecodes) eq 'ARRAY') && 
                   5561:                   (ref($groups_roles) eq 'HASH')); 
                   5562:     if (keys(%{$cdom_courseroles}) > 0) {
                   5563:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5564:         if ($cdom ne '' && $cnum ne '') {
                   5565:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5566:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5567:                     my $crsrole = $1;
                   5568:                     my $crssec = $2;
                   5569:                     if ($crsrole =~ /^cr/) {
                   5570:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5571:                             push(@{$rolecodes},'cr');
                   5572:                         }
                   5573:                     } else {
                   5574:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5575:                             push(@{$rolecodes},$crsrole);
                   5576:                         }
                   5577:                     }
                   5578:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5579:                     if ($crssec ne '') {
                   5580:                         $rolekey .= "/$crssec";
                   5581:                     }
                   5582:                     $rolekey .= './';
                   5583:                     $groups_roles->{$rolekey} = $rolecodes;
                   5584:                 }
                   5585:             }
                   5586:         }
                   5587:     }
                   5588:     return;
                   5589: }
                   5590: 
                   5591: sub delete_env_groupprivs {
                   5592:     my ($where,$courseroles,$possroles) = @_;
                   5593:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   5594:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   5595:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   5596:         %{$courseroles->{$udom}} =
                   5597:             &get_my_roles('','','userroles',['active'],
                   5598:                           $possroles,[$udom],1);
                   5599:     }
                   5600:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   5601:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   5602:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   5603:             my $area = '/'.$cdom.'/'.$cnum;
                   5604:             my $privkey = "user.priv.$crsrole.$area";
                   5605:             if ($crssec ne '') {
                   5606:                 $privkey .= '/'.$crssec;
                   5607:             }
                   5608:             $privkey .= ".$area/$group";
                   5609:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5610:         }
                   5611:     }
                   5612:     return;
                   5613: }
                   5614: 
1.994     raeburn  5615: sub check_adhoc_privs {
1.1104    raeburn  5616:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5617:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1185    raeburn  5618:     my $setprivs;
1.994     raeburn  5619:     if ($env{$cckey}) {
                   5620:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5621:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5622:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5623:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5624:             $setprivs = 1;
1.994     raeburn  5625:         }
                   5626:     } else {
1.1088    raeburn  5627:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.1185    raeburn  5628:         $setprivs = 1;
1.994     raeburn  5629:     }
1.1185    raeburn  5630:     return $setprivs;
1.994     raeburn  5631: }
                   5632: 
                   5633: sub set_adhoc_privileges {
                   5634: # role can be cc or ca
1.1088    raeburn  5635:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5636:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5637:     my $spec = $role.'.'.$area;
                   5638:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  5639:                                   $env{'user.name'},1);
1.994     raeburn  5640:     my %ccrole = ();
                   5641:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5642:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5643:     &appenv(\%userroles,[$role,'cm']);
                   5644:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5645:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5646:         &appenv( {'request.role'        => $spec,
                   5647:                   'request.role.domain' => $dcdom,
                   5648:                   'request.course.sec'  => ''
                   5649:                  }
                   5650:                );
                   5651:         my $tadv=0;
                   5652:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5653:         &appenv({'request.role.adv'    => $tadv});
                   5654:     }
1.994     raeburn  5655: }
                   5656: 
1.12      www      5657: # --------------------------------------------------------------- get interface
                   5658: 
                   5659: sub get {
1.131     albertel 5660:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5661:    my $items='';
1.800     albertel 5662:    foreach my $item (@$storearr) {
                   5663:        $items.=&escape($item).'&';
1.191     harris41 5664:    }
1.12      www      5665:    $items=~s/\&$//;
1.620     albertel 5666:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5667:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5668:    my $uhome=&homeserver($uname,$udomain);
                   5669: 
1.133     albertel 5670:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5671:    my @pairs=split(/\&/,$rep);
1.273     albertel 5672:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5673:      return @pairs;
                   5674:    }
1.15      www      5675:    my %returnhash=();
1.42      www      5676:    my $i=0;
1.800     albertel 5677:    foreach my $item (@$storearr) {
                   5678:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5679:       $i++;
1.191     harris41 5680:    }
1.15      www      5681:    return %returnhash;
1.27      www      5682: }
                   5683: 
                   5684: # --------------------------------------------------------------- del interface
                   5685: 
                   5686: sub del {
1.133     albertel 5687:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5688:    my $items='';
1.800     albertel 5689:    foreach my $item (@$storearr) {
                   5690:        $items.=&escape($item).'&';
1.191     harris41 5691:    }
1.984     neumanie 5692: 
1.27      www      5693:    $items=~s/\&$//;
1.620     albertel 5694:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5695:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5696:    my $uhome=&homeserver($uname,$udomain);
                   5697:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5698: }
                   5699: 
                   5700: # -------------------------------------------------------------- dump interface
                   5701: 
1.1180    droeschl 5702: sub unserialize {
                   5703:     my ($rep, $escapedkeys) = @_;
                   5704: 
                   5705:     return {} if $rep =~ /^error/;
                   5706: 
                   5707:     my %returnhash=();
1.1252    raeburn  5708: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 5709: 	    my ($key, $value) = split(/=/, $item, 2);
                   5710: 	    $key = unescape($key) unless $escapedkeys;
                   5711: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  5712: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 5713: 	}
                   5714:     #return %returnhash;
                   5715:     return \%returnhash;
                   5716: }        
                   5717: 
                   5718: # see Lond::dump_with_regexp
                   5719: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5720: sub dump {
1.1180    droeschl 5721:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5722:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5723:     if (!$uname) { $uname=$env{'user.name'}; }
                   5724:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5725: 
1.1266    raeburn  5726:     if ($regexp) {
                   5727:         $regexp=&escape($regexp);
                   5728:     } else {
                   5729:         $regexp='.';
                   5730:     }
1.1180    droeschl 5731:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5732:         # user is hosted on this machine
1.1266    raeburn  5733:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  5734:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 5735:         return %{unserialize($reply, $escapedkeys)};
                   5736:     }
1.1166    raeburn  5737:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5738:     my @pairs=split(/\&/,$rep);
                   5739:     my %returnhash=();
1.1098    foxr     5740:     if (!($rep =~ /^error/ )) {
                   5741: 	foreach my $item (@pairs) {
                   5742: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5743:         $key = unescape($key) unless $escapedkeys;
                   5744:         #$key = &unescape($key);
1.1098    foxr     5745: 	    next if ($key =~ /^error: 2 /);
                   5746: 	    $returnhash{$key}=&thaw_unescape($value);
                   5747: 	}
1.755     albertel 5748:     }
                   5749:     return %returnhash;
1.407     www      5750: }
                   5751: 
1.1098    foxr     5752: 
1.717     albertel 5753: # --------------------------------------------------------- dumpstore interface
                   5754: 
                   5755: sub dumpstore {
                   5756:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5757:    # same as dump but keys must be escaped. They may contain colon separated
                   5758:    # lists of values that may themself contain colons (e.g. symbs).
                   5759:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5760: }
                   5761: 
1.407     www      5762: # -------------------------------------------------------------- keys interface
                   5763: 
                   5764: sub getkeys {
                   5765:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5766:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5767:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5768:    my $uhome=&homeserver($uname,$udomain);
                   5769:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5770:    my @keyarray=();
1.800     albertel 5771:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5772:       next if ($key =~ /^error: 2 /);
1.800     albertel 5773:       push(@keyarray,&unescape($key));
1.407     www      5774:    }
                   5775:    return @keyarray;
1.318     matthew  5776: }
                   5777: 
1.319     matthew  5778: # --------------------------------------------------------------- currentdump
                   5779: sub currentdump {
1.328     matthew  5780:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5781:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5782:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5783:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5784:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5785:    my $rep;
                   5786: 
                   5787:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5788:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5789:                    $courseid)));
                   5790:    } else {
                   5791:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5792:    }
                   5793: 
1.318     matthew  5794:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5795:    #
1.318     matthew  5796:    my %returnhash=();
1.319     matthew  5797:    #
                   5798:    if ($rep eq "unknown_cmd") { 
                   5799:        # an old lond will not know currentdump
                   5800:        # Do a dump and make it look like a currentdump
1.822     albertel 5801:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5802:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5803:        my %hash = @tmp;
                   5804:        @tmp=();
1.424     matthew  5805:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5806:    } else {
                   5807:        my @pairs=split(/\&/,$rep);
1.800     albertel 5808:        foreach my $pair (@pairs) {
                   5809:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5810:            my ($symb,$param) = split(/:/,$key);
                   5811:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5812:                                                         &thaw_unescape($value);
1.319     matthew  5813:        }
1.191     harris41 5814:    }
1.12      www      5815:    return %returnhash;
1.424     matthew  5816: }
                   5817: 
                   5818: sub convert_dump_to_currentdump{
                   5819:     my %hash = %{shift()};
                   5820:     my %returnhash;
                   5821:     # Code ripped from lond, essentially.  The only difference
                   5822:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5823:     # we might run in to problems with parameter names =~ /^v\./
                   5824:     while (my ($key,$value) = each(%hash)) {
                   5825:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5826: 	$symb  = &unescape($symb);
                   5827: 	$param = &unescape($param);
1.424     matthew  5828:         next if ($v eq 'version' || $symb eq 'keys');
                   5829:         next if (exists($returnhash{$symb}) &&
                   5830:                  exists($returnhash{$symb}->{$param}) &&
                   5831:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5832:         $returnhash{$symb}->{$param}=$value;
                   5833:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5834:     }
                   5835:     #
                   5836:     # Remove all of the keys in the hashes which keep track of
                   5837:     # the version of the parameter.
                   5838:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5839:         # use a foreach because we are going to delete from the hash.
                   5840:         foreach my $key (keys(%$param_hash)) {
                   5841:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5842:         }
                   5843:     }
                   5844:     return \%returnhash;
1.12      www      5845: }
                   5846: 
1.627     albertel 5847: # ------------------------------------------------------ critical inc interface
                   5848: 
                   5849: sub cinc {
                   5850:     return &inc(@_,'critical');
                   5851: }
                   5852: 
1.449     matthew  5853: # --------------------------------------------------------------- inc interface
                   5854: 
                   5855: sub inc {
1.627     albertel 5856:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5857:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5858:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5859:     my $uhome=&homeserver($uname,$udomain);
                   5860:     my $items='';
                   5861:     if (! ref($store)) {
                   5862:         # got a single value, so use that instead
                   5863:         $items = &escape($store).'=&';
                   5864:     } elsif (ref($store) eq 'SCALAR') {
                   5865:         $items = &escape($$store).'=&';        
                   5866:     } elsif (ref($store) eq 'ARRAY') {
                   5867:         $items = join('=&',map {&escape($_);} @{$store});
                   5868:     } elsif (ref($store) eq 'HASH') {
                   5869:         while (my($key,$value) = each(%{$store})) {
                   5870:             $items.= &escape($key).'='.&escape($value).'&';
                   5871:         }
                   5872:     }
                   5873:     $items=~s/\&$//;
1.627     albertel 5874:     if ($critical) {
                   5875: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5876:     } else {
                   5877: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5878:     }
1.449     matthew  5879: }
                   5880: 
1.12      www      5881: # --------------------------------------------------------------- put interface
                   5882: 
                   5883: sub put {
1.134     albertel 5884:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5885:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5886:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5887:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5888:    my $items='';
1.800     albertel 5889:    foreach my $item (keys(%$storehash)) {
                   5890:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5891:    }
1.12      www      5892:    $items=~s/\&$//;
1.134     albertel 5893:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5894: }
                   5895: 
1.631     albertel 5896: # ------------------------------------------------------------ newput interface
                   5897: 
                   5898: sub newput {
                   5899:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5900:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5901:    if (!$uname) { $uname=$env{'user.name'}; }
                   5902:    my $uhome=&homeserver($uname,$udomain);
                   5903:    my $items='';
                   5904:    foreach my $key (keys(%$storehash)) {
                   5905:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5906:    }
                   5907:    $items=~s/\&$//;
                   5908:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5909: }
                   5910: 
                   5911: # ---------------------------------------------------------  putstore interface
                   5912: 
1.524     raeburn  5913: sub putstore {
1.1269    raeburn  5914:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 5915:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5916:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5917:    my $uhome=&homeserver($uname,$udomain);
                   5918:    my $items='';
1.715     albertel 5919:    foreach my $key (keys(%$storehash)) {
                   5920:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5921:    }
1.715     albertel 5922:    $items=~s/\&$//;
1.716     albertel 5923:    my $esc_symb=&escape($symb);
                   5924:    my $esc_v=&escape($version);
1.715     albertel 5925:    my $reply =
1.716     albertel 5926:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5927: 	      $uhome);
1.1269    raeburn  5928:    if (($tolog) && ($reply eq 'ok')) {
                   5929:        my $namevalue='';
                   5930:        foreach my $key (keys(%{$storehash})) {
                   5931:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   5932:        }
                   5933:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   5934:                      '&host='.&escape($perlvar{'lonHostID'}).
                   5935:                      '&version='.$esc_v.
                   5936:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   5937:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   5938:    }
1.715     albertel 5939:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5940:        # gfall back to way things use to be done
1.715     albertel 5941:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5942: 			    $uname);
1.524     raeburn  5943:    }
1.715     albertel 5944:    return $reply;
                   5945: }
                   5946: 
                   5947: sub old_putstore {
1.716     albertel 5948:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5949:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5950:     if (!$uname) { $uname=$env{'user.name'}; }
                   5951:     my $uhome=&homeserver($uname,$udomain);
                   5952:     my %newstorehash;
1.800     albertel 5953:     foreach my $item (keys(%$storehash)) {
                   5954: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5955: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5956:     }
                   5957:     my $items='';
                   5958:     my %allitems = ();
1.800     albertel 5959:     foreach my $item (keys(%newstorehash)) {
                   5960: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5961: 	    my $key = $1.':keys:'.$2;
                   5962: 	    $allitems{$key} .= $3.':';
                   5963: 	}
1.800     albertel 5964: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5965:     }
1.800     albertel 5966:     foreach my $item (keys(%allitems)) {
                   5967: 	$allitems{$item} =~ s/\:$//;
                   5968: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5969:     }
                   5970:     $items=~s/\&$//;
                   5971:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5972: }
                   5973: 
1.47      www      5974: # ------------------------------------------------------ critical put interface
                   5975: 
                   5976: sub cput {
1.134     albertel 5977:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5978:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5979:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5980:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5981:    my $items='';
1.800     albertel 5982:    foreach my $item (keys(%$storehash)) {
                   5983:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5984:    }
1.47      www      5985:    $items=~s/\&$//;
1.134     albertel 5986:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5987: }
                   5988: 
                   5989: # -------------------------------------------------------------- eget interface
                   5990: 
                   5991: sub eget {
1.133     albertel 5992:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5993:    my $items='';
1.800     albertel 5994:    foreach my $item (@$storearr) {
                   5995:        $items.=&escape($item).'&';
1.191     harris41 5996:    }
1.12      www      5997:    $items=~s/\&$//;
1.620     albertel 5998:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5999:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6000:    my $uhome=&homeserver($uname,$udomain);
                   6001:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6002:    my @pairs=split(/\&/,$rep);
                   6003:    my %returnhash=();
1.42      www      6004:    my $i=0;
1.800     albertel 6005:    foreach my $item (@$storearr) {
                   6006:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6007:       $i++;
1.191     harris41 6008:    }
1.12      www      6009:    return %returnhash;
                   6010: }
                   6011: 
1.667     albertel 6012: # ------------------------------------------------------------ tmpput interface
                   6013: sub tmpput {
1.802     raeburn  6014:     my ($storehash,$server,$context)=@_;
1.667     albertel 6015:     my $items='';
1.800     albertel 6016:     foreach my $item (keys(%$storehash)) {
                   6017: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6018:     }
                   6019:     $items=~s/\&$//;
1.802     raeburn  6020:     if (defined($context)) {
                   6021:         $items .= ':'.&escape($context);
                   6022:     }
1.667     albertel 6023:     return &reply("tmpput:$items",$server);
                   6024: }
                   6025: 
                   6026: # ------------------------------------------------------------ tmpget interface
                   6027: sub tmpget {
1.688     albertel 6028:     my ($token,$server)=@_;
                   6029:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6030:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6031:     my %returnhash;
                   6032:     foreach my $item (split(/\&/,$rep)) {
                   6033: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  6034:         next if ($key =~ /^error: 2 /);
1.667     albertel 6035: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6036:     }
                   6037:     return %returnhash;
                   6038: }
                   6039: 
1.1113    raeburn  6040: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6041: sub tmpdel {
                   6042:     my ($token,$server)=@_;
                   6043:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6044:     return &reply("tmpdel:$token",$server);
                   6045: }
                   6046: 
1.1198    raeburn  6047: # ------------------------------------------------------------ get_timebased_id 
                   6048: 
                   6049: sub get_timebased_id {
                   6050:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6051:         $maxtries) = @_;
                   6052:     my ($newid,$error,$dellock);
                   6053:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6054:         return ('','ok','invalid call to get suffix');
                   6055:     }
                   6056: 
                   6057: # set defaults for any optional args for which values were not supplied
                   6058:     if ($who eq '') {
                   6059:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6060:     }
                   6061:     if (!$locktries) {
                   6062:         $locktries = 3;
                   6063:     }
                   6064:     if (!$maxtries) {
                   6065:         $maxtries = 10;
                   6066:     }
                   6067:     
                   6068:     if (($cdom eq '') || ($cnum eq '')) {
                   6069:         if ($env{'request.course.id'}) {
                   6070:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6071:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6072:         }
                   6073:         if (($cdom eq '') || ($cnum eq '')) {
                   6074:             return ('','ok','call to get suffix not in course context');
                   6075:         }
                   6076:     }
                   6077: 
                   6078: # construct locking item
                   6079:     my $lockhash = {
                   6080:                       $prefix."\0".'locked_'.$keyid => $who,
                   6081:                    };
                   6082:     my $tries = 0;
                   6083: 
                   6084: # attempt to get lock on nohist_$namespace file
                   6085:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6086:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6087:         $tries ++;
                   6088:         sleep 1;
                   6089:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6090:     }
                   6091: 
                   6092: # attempt to get unique identifier, based on current timestamp
                   6093:     if ($gotlock eq 'ok') {
                   6094:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6095:         my $id = time;
                   6096:         $newid = $id;
1.1268    raeburn  6097:         if ($idtype eq 'addcode') {
                   6098:             $newid .= &sixnum_code();
                   6099:         }
1.1198    raeburn  6100:         my $idtries = 0;
                   6101:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6102:             if ($idtype eq 'concat') {
                   6103:                 $newid = $id.$idtries;
1.1268    raeburn  6104:             } elsif ($idtype eq 'addcode') {
                   6105:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6106:             } else {
                   6107:                 $newid ++;
                   6108:             }
                   6109:             $idtries ++;
                   6110:         }
                   6111:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6112:             my %new_item =  (
                   6113:                               $prefix."\0".$newid => $who,
                   6114:                             );
                   6115:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6116:                                                  $cdom,$cnum);
                   6117:             if ($putresult ne 'ok') {
                   6118:                 undef($newid);
                   6119:                 $error = 'error saving new item: '.$putresult;
                   6120:             }
                   6121:         } else {
1.1268    raeburn  6122:              undef($newid);
1.1198    raeburn  6123:              $error = ('error: no unique suffix available for the new item ');
                   6124:         }
                   6125: #  remove lock
                   6126:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6127:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6128:     } else {
                   6129:         $error = "error: could not obtain lockfile\n";
                   6130:         $dellock = 'ok';
1.1276    raeburn  6131:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6132:             $dellock = 'nolock';
                   6133:         }
1.1198    raeburn  6134:     }
                   6135:     return ($newid,$dellock,$error);
                   6136: }
                   6137: 
1.1268    raeburn  6138: sub sixnum_code {
                   6139:     my $code;
                   6140:     for (0..6) {
                   6141:         $code .= int( rand(9) );
                   6142:     }
                   6143:     return $code;
                   6144: }
                   6145: 
1.765     albertel 6146: # -------------------------------------------------- portfolio access checking
                   6147: 
                   6148: sub portfolio_access {
1.1270    raeburn  6149:     my ($requrl,$clientip) = @_;
1.765     albertel 6150:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6151:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6152:     if ($result) {
                   6153:         my %setters;
                   6154:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6155:             my ($startblock,$endblock) =
                   6156:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6157:             if ($startblock && $endblock) {
                   6158:                 return 'B';
                   6159:             }
                   6160:         } else {
                   6161:             my ($startblock,$endblock) =
                   6162:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6163:             if ($startblock && $endblock) {
                   6164:                 return 'B';
                   6165:             }
                   6166:         }
                   6167:     }
1.765     albertel 6168:     if ($result eq 'ok') {
1.766     albertel 6169:        return 'F';
1.765     albertel 6170:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6171:        return 'A';
1.765     albertel 6172:     }
1.766     albertel 6173:     return '';
1.765     albertel 6174: }
                   6175: 
                   6176: sub get_portfolio_access {
1.1270    raeburn  6177:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6178: 
                   6179:     if (!ref($access_hash)) {
                   6180: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6181: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6182: 						   $file_name);
                   6183: 	$access_hash = $access_controls{$file_name};
                   6184:     }
                   6185: 
1.1270    raeburn  6186:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6187:     my $now = time;
                   6188:     if (ref($access_hash) eq 'HASH') {
                   6189:         foreach my $key (keys(%{$access_hash})) {
                   6190:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6191:             if ($start > $now) {
                   6192:                 next;
                   6193:             }
                   6194:             if ($end && $end<$now) {
                   6195:                 next;
                   6196:             }
                   6197:             if ($scope eq 'public') {
                   6198:                 $public = $key;
                   6199:                 last;
                   6200:             } elsif ($scope eq 'guest') {
                   6201:                 $guest = $key;
                   6202:             } elsif ($scope eq 'domains') {
                   6203:                 push(@domains,$key);
                   6204:             } elsif ($scope eq 'users') {
                   6205:                 push(@users,$key);
                   6206:             } elsif ($scope eq 'course') {
                   6207:                 push(@courses,$key);
                   6208:             } elsif ($scope eq 'group') {
                   6209:                 push(@groups,$key);
1.1270    raeburn  6210:             } elsif ($scope eq 'ip') {
                   6211:                 push(@ips,$key);
1.765     albertel 6212:             }
                   6213:         }
                   6214:         if ($public) {
                   6215:             return 'ok';
1.1270    raeburn  6216:         } elsif (@ips > 0) {
                   6217:             my $allowed;
                   6218:             foreach my $ipkey (@ips) {
                   6219:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6220:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6221:                         $allowed = 1;
                   6222:                         last; 
                   6223:                     }
                   6224:                 }
                   6225:             }
                   6226:             if ($allowed) {
                   6227:                 return 'ok';
                   6228:             }
1.765     albertel 6229:         }
                   6230:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6231:             if ($guest) {
                   6232:                 return $guest;
                   6233:             }
                   6234:         } else {
                   6235:             if (@domains > 0) {
                   6236:                 foreach my $domkey (@domains) {
                   6237:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6238:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6239:                             return 'ok';
                   6240:                         }
                   6241:                     }
                   6242:                 }
                   6243:             }
                   6244:             if (@users > 0) {
                   6245:                 foreach my $userkey (@users) {
1.865     raeburn  6246:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6247:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6248:                             if (ref($item) eq 'HASH') {
                   6249:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6250:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6251:                                     return 'ok';
                   6252:                                 }
                   6253:                             }
                   6254:                         }
                   6255:                     } 
1.765     albertel 6256:                 }
                   6257:             }
                   6258:             my %roleshash;
                   6259:             my @courses_and_groups = @courses;
                   6260:             push(@courses_and_groups,@groups); 
                   6261:             if (@courses_and_groups > 0) {
                   6262:                 my (%allgroups,%allroles); 
                   6263:                 my ($start,$end,$role,$sec,$group);
                   6264:                 foreach my $envkey (%env) {
1.1060    raeburn  6265:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6266:                         my $cid = $2.'_'.$3; 
                   6267:                         if ($1 eq 'gr') {
                   6268:                             $group = $4;
                   6269:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6270:                         } else {
                   6271:                             if ($4 eq '') {
                   6272:                                 $sec = 'none';
                   6273:                             } else {
                   6274:                                 $sec = $4;
                   6275:                             }
                   6276:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6277:                         }
1.811     albertel 6278:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6279:                         my $cid = $2.'_'.$3;
                   6280:                         if ($4 eq '') {
                   6281:                             $sec = 'none';
                   6282:                         } else {
                   6283:                             $sec = $4;
                   6284:                         }
                   6285:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6286:                     }
                   6287:                 }
                   6288:                 if (keys(%allroles) == 0) {
                   6289:                     return;
                   6290:                 }
                   6291:                 foreach my $key (@courses_and_groups) {
                   6292:                     my %content = %{$$access_hash{$key}};
                   6293:                     my $cnum = $content{'number'};
                   6294:                     my $cdom = $content{'domain'};
                   6295:                     my $cid = $cdom.'_'.$cnum;
                   6296:                     if (!exists($allroles{$cid})) {
                   6297:                         next;
                   6298:                     }    
                   6299:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6300:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6301:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6302:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6303:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6304:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6305:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6306:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6307:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6308:                                         if (grep/^all$/,@sections) {
                   6309:                                             return 'ok';
                   6310:                                         } else {
                   6311:                                             if (grep/^$sec$/,@sections) {
                   6312:                                                 return 'ok';
                   6313:                                             }
                   6314:                                         }
                   6315:                                     }
                   6316:                                 }
                   6317:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6318:                                     if (grep/^none$/,@groups) {
                   6319:                                         return 'ok';
                   6320:                                     }
                   6321:                                 } else {
                   6322:                                     if (grep/^all$/,@groups) {
                   6323:                                         return 'ok';
                   6324:                                     } 
                   6325:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6326:                                         if (grep/^$group$/,@groups) {
                   6327:                                             return 'ok';
                   6328:                                         }
                   6329:                                     }
                   6330:                                 } 
                   6331:                             }
                   6332:                         }
                   6333:                     }
                   6334:                 }
                   6335:             }
                   6336:             if ($guest) {
                   6337:                 return $guest;
                   6338:             }
                   6339:         }
                   6340:     }
                   6341:     return;
                   6342: }
                   6343: 
                   6344: sub course_group_datechecker {
                   6345:     my ($dates,$now,$status) = @_;
                   6346:     my ($start,$end) = split(/\./,$dates);
                   6347:     if (!$start && !$end) {
                   6348:         return 'ok';
                   6349:     }
                   6350:     if (grep/^active$/,@{$status}) {
                   6351:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6352:             return 'ok';
                   6353:         }
                   6354:     }
                   6355:     if (grep/^previous$/,@{$status}) {
                   6356:         if ($end > $now ) {
                   6357:             return 'ok';
                   6358:         }
                   6359:     }
                   6360:     if (grep/^future$/,@{$status}) {
                   6361:         if ($start > $now) {
                   6362:             return 'ok';
                   6363:         }
                   6364:     }
                   6365:     return; 
                   6366: }
                   6367: 
                   6368: sub parse_portfolio_url {
                   6369:     my ($url) = @_;
                   6370: 
                   6371:     my ($type,$udom,$unum,$group,$file_name);
                   6372:     
1.823     albertel 6373:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6374: 	$type = 1;
                   6375:         $udom = $1;
                   6376:         $unum = $2;
                   6377:         $file_name = $3;
1.823     albertel 6378:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6379: 	$type = 2;
                   6380:         $udom = $1;
                   6381:         $unum = $2;
                   6382:         $group = $3;
                   6383:         $file_name = $3.'/'.$4;
                   6384:     }
                   6385:     if (wantarray) {
                   6386: 	return ($type,$udom,$unum,$file_name,$group);
                   6387:     }
                   6388:     return $type;
                   6389: }
                   6390: 
                   6391: sub is_portfolio_url {
                   6392:     my ($url) = @_;
                   6393:     return scalar(&parse_portfolio_url($url));
                   6394: }
                   6395: 
1.798     raeburn  6396: sub is_portfolio_file {
                   6397:     my ($file) = @_;
1.820     raeburn  6398:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6399:         return 1;
                   6400:     }
                   6401:     return;
                   6402: }
                   6403: 
1.976     raeburn  6404: sub usertools_access {
1.1084    raeburn  6405:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6406:     my ($access,%tools);
                   6407:     if ($context eq '') {
                   6408:         $context = 'tools';
                   6409:     }
                   6410:     if ($context eq 'requestcourses') {
                   6411:         %tools = (
                   6412:                       official   => 1,
                   6413:                       unofficial => 1,
1.1006    raeburn  6414:                       community  => 1,
1.1246    raeburn  6415:                       textbook   => 1,
1.985     raeburn  6416:                  );
1.1183    raeburn  6417:     } elsif ($context eq 'requestauthor') {
                   6418:         %tools = (
                   6419:                       requestauthor => 1,
                   6420:                  );
1.985     raeburn  6421:     } else {
                   6422:         %tools = (
                   6423:                       aboutme   => 1,
                   6424:                       blog      => 1,
1.1177    raeburn  6425:                       webdav    => 1,
1.985     raeburn  6426:                       portfolio => 1,
                   6427:                  );
                   6428:     }
1.976     raeburn  6429:     return if (!defined($tools{$tool}));
                   6430: 
1.1242    raeburn  6431:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6432:         $udom = $env{'user.domain'};
                   6433:         $uname = $env{'user.name'};
                   6434:     }
                   6435: 
1.978     raeburn  6436:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6437:         if ($action ne 'reload') {
1.985     raeburn  6438:             if ($context eq 'requestcourses') {
                   6439:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6440:             } elsif ($context eq 'requestauthor') {
                   6441:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6442:             } else {
                   6443:                 return $env{'environment.availabletools.'.$tool};
                   6444:             }
                   6445:         }
1.976     raeburn  6446:     }
                   6447: 
1.1183    raeburn  6448:     my ($toolstatus,$inststatus,$envkey);
                   6449:     if ($context eq 'requestauthor') {
                   6450:         $envkey = $context; 
                   6451:     } else {
                   6452:         $envkey = $context.'.'.$tool;
                   6453:     }
1.976     raeburn  6454: 
1.985     raeburn  6455:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6456:          ($action ne 'reload')) {
1.1183    raeburn  6457:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6458:         $inststatus = $env{'environment.inststatus'};
                   6459:     } else {
1.1084    raeburn  6460:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6461:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6462:             $inststatus = $userenvref->{'inststatus'};
                   6463:         } else {
1.1183    raeburn  6464:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6465:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6466:             $inststatus = $userenv{'inststatus'};
                   6467:         }
1.976     raeburn  6468:     }
                   6469: 
                   6470:     if ($toolstatus ne '') {
                   6471:         if ($toolstatus) {
                   6472:             $access = 1;
                   6473:         } else {
                   6474:             $access = 0;
                   6475:         }
                   6476:         return $access;
                   6477:     }
                   6478: 
1.1084    raeburn  6479:     my ($is_adv,%domdef);
                   6480:     if (ref($is_advref) eq 'HASH') {
                   6481:         $is_adv = $is_advref->{'is_adv'};
                   6482:     } else {
                   6483:         $is_adv = &is_advanced_user($udom,$uname);
                   6484:     }
                   6485:     if (ref($domdefref) eq 'HASH') {
                   6486:         %domdef = %{$domdefref};
                   6487:     } else {
                   6488:         %domdef = &get_domain_defaults($udom);
                   6489:     }
1.976     raeburn  6490:     if (ref($domdef{$tool}) eq 'HASH') {
                   6491:         if ($is_adv) {
                   6492:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6493:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6494:                     $access = 1;
                   6495:                 } else {
                   6496:                     $access = 0;
                   6497:                 }
                   6498:                 return $access;
                   6499:             }
                   6500:         }
                   6501:         if ($inststatus ne '') {
                   6502:             my ($hasaccess,$hasnoaccess);
                   6503:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6504:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6505:                     if ($domdef{$tool}{$affiliation}) {
                   6506:                         $hasaccess = 1;
                   6507:                     } else {
                   6508:                         $hasnoaccess = 1;
                   6509:                     }
                   6510:                 }
                   6511:             }
                   6512:             if ($hasaccess || $hasnoaccess) {
                   6513:                 if ($hasaccess) {
                   6514:                     $access = 1;
                   6515:                 } elsif ($hasnoaccess) {
                   6516:                     $access = 0; 
                   6517:                 }
                   6518:                 return $access;
                   6519:             }
                   6520:         } else {
                   6521:             if ($domdef{$tool}{'default'} ne '') {
                   6522:                 if ($domdef{$tool}{'default'}) {
                   6523:                     $access = 1;
                   6524:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6525:                     $access = 0;
                   6526:                 }
                   6527:                 return $access;
                   6528:             }
                   6529:         }
                   6530:     } else {
1.1177    raeburn  6531:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6532:             $access = 1;
                   6533:         } else {
                   6534:             $access = 0;
                   6535:         }
1.976     raeburn  6536:         return $access;
                   6537:     }
                   6538: }
                   6539: 
1.1050    raeburn  6540: sub is_course_owner {
                   6541:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6542:     if (($udom eq '') || ($uname eq '')) {
                   6543:         $udom = $env{'user.domain'};
                   6544:         $uname = $env{'user.name'};
                   6545:     }
                   6546:     unless (($udom eq '') || ($uname eq '')) {
                   6547:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6548:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6549:                 return 1;
                   6550:             } else {
                   6551:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6552:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6553:                     return 1;
                   6554:                 }
                   6555:             }
                   6556:         }
                   6557:     }
                   6558:     return;
                   6559: }
                   6560: 
1.976     raeburn  6561: sub is_advanced_user {
                   6562:     my ($udom,$uname) = @_;
1.1085    raeburn  6563:     if ($udom ne '' && $uname ne '') {
                   6564:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  6565:             if (wantarray) {
                   6566:                 return ($env{'user.adv'},$env{'user.author'});
                   6567:             } else {
                   6568:                 return $env{'user.adv'};
                   6569:             }
1.1085    raeburn  6570:         }
                   6571:     }
1.976     raeburn  6572:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   6573:     my %allroles;
1.1128    raeburn  6574:     my ($is_adv,$is_author);
1.976     raeburn  6575:     foreach my $role (keys(%roleshash)) {
                   6576:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   6577:         my $area = '/'.$tdomain.'/'.$trest;
                   6578:         if ($sec ne '') {
                   6579:             $area .= '/'.$sec;
                   6580:         }
                   6581:         if (($area ne '') && ($trole ne '')) {
                   6582:             my $spec=$trole.'.'.$area;
                   6583:             if ($trole =~ /^cr\//) {
                   6584:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6585:             } elsif ($trole ne 'gr') {
                   6586:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6587:             }
1.1128    raeburn  6588:             if ($trole eq 'au') {
                   6589:                 $is_author = 1;
                   6590:             }
1.976     raeburn  6591:         }
                   6592:     }
                   6593:     foreach my $role (keys(%allroles)) {
                   6594:         last if ($is_adv);
                   6595:         foreach my $item (split(/:/,$allroles{$role})) {
                   6596:             if ($item ne '') {
                   6597:                 my ($privilege,$restrictions)=split(/&/,$item);
                   6598:                 if ($privilege eq 'adv') {
                   6599:                     $is_adv = 1;
                   6600:                     last;
                   6601:                 }
                   6602:             }
                   6603:         }
                   6604:     }
1.1128    raeburn  6605:     if (wantarray) {
                   6606:         return ($is_adv,$is_author);
                   6607:     }
1.976     raeburn  6608:     return $is_adv;
                   6609: }
1.798     raeburn  6610: 
1.1035    raeburn  6611: sub check_can_request {
1.1036    raeburn  6612:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  6613:     my $canreq = 0;
                   6614:     my ($types,$typename) = &Apache::loncommon::course_types();
                   6615:     my @options = ('approval','validate','autolimit');
                   6616:     my $optregex = join('|',@options);
                   6617:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   6618:         foreach my $type (@{$types}) {
                   6619:             if (&usertools_access($env{'user.name'},
                   6620:                                   $env{'user.domain'},
                   6621:                                   $type,undef,'requestcourses')) {
                   6622:                 $canreq ++;
1.1036    raeburn  6623:                 if (ref($request_domains) eq 'HASH') {
                   6624:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   6625:                 }
1.1035    raeburn  6626:                 if ($dom eq $env{'user.domain'}) {
                   6627:                     $can_request->{$type} = 1;
                   6628:                 }
                   6629:             }
                   6630:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   6631:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   6632:                 if (@curr > 0) {
1.1036    raeburn  6633:                     foreach my $item (@curr) {
                   6634:                         if (ref($request_domains) eq 'HASH') {
                   6635:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   6636:                             if ($otherdom ne '') {
                   6637:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   6638:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   6639:                                         push(@{$request_domains->{$type}},$otherdom);
                   6640:                                     }
                   6641:                                 } else {
                   6642:                                     push(@{$request_domains->{$type}},$otherdom);
                   6643:                                 }
                   6644:                             }
                   6645:                         }
                   6646:                     }
                   6647:                     unless($dom eq $env{'user.domain'}) {
                   6648:                         $canreq ++;
1.1035    raeburn  6649:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   6650:                             $can_request->{$type} = 1;
                   6651:                         }
                   6652:                     }
                   6653:                 }
                   6654:             }
                   6655:         }
                   6656:     }
                   6657:     return $canreq;
                   6658: }
                   6659: 
1.341     www      6660: # ---------------------------------------------- Custom access rule evaluation
                   6661: 
                   6662: sub customaccess {
                   6663:     my ($priv,$uri)=@_;
1.807     albertel 6664:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      6665:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 6666:     $udom = &LONCAPA::clean_domain($udom);
                   6667:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      6668:     my $access=0;
1.800     albertel 6669:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 6670: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   6671: 	if ($type eq 'user') {
                   6672: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 6673: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 6674: 		if ($tdom) {
                   6675: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   6676: 		}
1.896     albertel 6677: 		if ($tuname) {
                   6678: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 6679: 		}
                   6680: 		$access=($effect eq 'allow');
                   6681: 		last;
                   6682: 	    }
                   6683: 	} else {
                   6684: 	    if ($role) {
                   6685: 		if ($role ne $urole) { next; }
                   6686: 	    }
                   6687: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   6688: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   6689: 		if ($tdom) {
                   6690: 		    if ($tdom ne $udom) { next; }
                   6691: 		}
                   6692: 		if ($tcrs) {
                   6693: 		    if ($tcrs ne $ucrs) { next; }
                   6694: 		}
                   6695: 		if ($tsec) {
                   6696: 		    if ($tsec ne $usec) { next; }
                   6697: 		}
                   6698: 		$access=($effect eq 'allow');
                   6699: 		last;
                   6700: 	    }
                   6701: 	    if ($realm eq '' && $role eq '') {
                   6702: 		$access=($effect eq 'allow');
                   6703: 	    }
1.402     bowersj2 6704: 	}
1.341     www      6705:     }
                   6706:     return $access;
                   6707: }
                   6708: 
1.103     harris41 6709: # ------------------------------------------------- Check for a user privilege
1.12      www      6710: 
                   6711: sub allowed {
1.1281    raeburn  6712:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 6713:     my $ver_orguri=$uri;
1.439     www      6714:     $uri=&deversion($uri);
1.152     www      6715:     my $orguri=$uri;
1.52      www      6716:     $uri=&declutter($uri);
1.809     raeburn  6717: 
1.810     raeburn  6718:     if ($priv eq 'evb') {
                   6719: # Evade communication block restrictions for specified role in a course
                   6720:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   6721:             return $1;
                   6722:         } else {
                   6723:             return;
                   6724:         }
                   6725:     }
                   6726: 
1.620     albertel 6727:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      6728: # Free bre access to adm and meta resources
1.775     albertel 6729:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 6730: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   6731: 	&& ($priv eq 'bre')) {
1.14      www      6732: 	return 'F';
1.159     www      6733:     }
                   6734: 
1.545     banghart 6735: # Free bre access to user's own portfolio contents
1.714     raeburn  6736:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  6737:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  6738: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  6739:         my %setters;
                   6740:         my ($startblock,$endblock) = 
                   6741:             &Apache::loncommon::blockcheck(\%setters,'port');
                   6742:         if ($startblock && $endblock) {
                   6743:             return 'B';
                   6744:         } else {
                   6745:             return 'F';
                   6746:         }
1.545     banghart 6747:     }
                   6748: 
1.762     raeburn  6749: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6750:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6751:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6752:         if (exists($env{'request.course.id'})) {
                   6753:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6754:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6755:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6756:                 my $courseprivid=$env{'request.course.id'};
                   6757:                 $courseprivid=~s/\_/\//;
                   6758:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6759:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6760:                     return $1; 
1.762     raeburn  6761:                 } else {
                   6762:                     if ($env{'request.course.sec'}) {
                   6763:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6764:                     }
                   6765:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6766:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6767:                         return $2;
                   6768:                     }
1.714     raeburn  6769:                 }
                   6770:             }
                   6771:         }
                   6772:     }
                   6773: 
1.159     www      6774: # Free bre to public access
                   6775: 
                   6776:     if ($priv eq 'bre') {
1.238     www      6777:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6778: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6779:            return 'F'; 
                   6780:         }
1.238     www      6781:         if ($copyright eq 'priv') {
                   6782:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6783: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6784: 		return '';
                   6785:             }
                   6786:         }
                   6787:         if ($copyright eq 'domain') {
                   6788:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6789: 	    unless (($env{'user.domain'} eq $1) ||
                   6790:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6791: 		return '';
                   6792:             }
1.262     matthew  6793:         }
1.620     albertel 6794:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6795:             # Library role, so allow browsing of resources in this domain.
                   6796:             return 'F';
1.238     www      6797:         }
1.341     www      6798:         if ($copyright eq 'custom') {
                   6799: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6800:         }
1.14      www      6801:     }
1.264     matthew  6802:     # Domain coordinator is trying to create a course
1.620     albertel 6803:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6804:         # uri is the requested domain in this case.
                   6805:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6806:         # a role of dc for the domain in question.
1.620     albertel 6807:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6808:     }
1.29      www      6809: 
1.52      www      6810:     my $thisallowed='';
                   6811:     my $statecond=0;
                   6812:     my $courseprivid='';
                   6813: 
1.1039    raeburn  6814:     my $ownaccess;
1.1043    raeburn  6815:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6816:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6817:         if ($uri eq '') {
                   6818:             $ownaccess = 1;
                   6819:         } else {
                   6820:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6821:                 my $udom = $env{'user.domain'};
                   6822:                 my $uname = $env{'user.name'};
                   6823:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6824:                     $ownaccess = 1;
1.1040    raeburn  6825:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6826:                     unless ($uri =~ m{\.\./}) {
                   6827:                         $ownaccess = 1;
                   6828:                     }
                   6829:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6830:                     my $now = time;
                   6831:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6832:                         my $adom = $1;
                   6833:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6834:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6835:                                 my ($start,$end) = split('.',$env{$key});
                   6836:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6837:                                     $ownaccess = 1;
                   6838:                                     last;
                   6839:                                 }
                   6840:                             }
                   6841:                         }
                   6842:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6843:                         my $adom = $1;
                   6844:                         my $aname = $2;
1.1042    raeburn  6845:                         foreach my $role ('ca','aa') { 
                   6846:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6847:                                 my ($start,$end) =
                   6848:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6849:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6850:                                     $ownaccess = 1;
                   6851:                                     last;
                   6852:                                 }
1.1039    raeburn  6853:                             }
                   6854:                         }
                   6855:                     }
                   6856:                 }
                   6857:             }
                   6858:         }
                   6859:     }
                   6860: 
1.52      www      6861: # Course
                   6862: 
1.620     albertel 6863:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6864:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6865:             $thisallowed.=$1;
                   6866:         }
1.52      www      6867:     }
1.29      www      6868: 
1.52      www      6869: # Domain
                   6870: 
1.620     albertel 6871:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6872:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6873:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6874:             $thisallowed.=$1;
                   6875:         }
1.12      www      6876:     }
1.52      www      6877: 
1.1141    raeburn  6878: # User who is not author or co-author might still be able to edit
                   6879: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6880:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6881:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6882:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6883:             $thisallowed.=$1;
                   6884:         }
                   6885:     }
                   6886: 
1.52      www      6887: # Course: uri itself is a course
1.66      www      6888:     my $courseuri=$uri;
                   6889:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6890:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6891: 
1.620     albertel 6892:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6893:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6894:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6895:             $thisallowed.=$1;
                   6896:         }
1.12      www      6897:     }
1.29      www      6898: 
1.665     albertel 6899: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6900: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6901:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6902: 	$thisallowed='';
1.671     raeburn  6903:         my ($match)=&is_on_map($uri);
                   6904:         if ($match) {
                   6905:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6906:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  6907:                 my $value = $1;
                   6908:                 if ($noblockcheck) {
                   6909:                     $thisallowed.=$value;
1.1162    raeburn  6910:                 } else {
1.1281    raeburn  6911:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6912:                     if (@blockers > 0) {
                   6913:                         $thisallowed = 'B';
                   6914:                     } else {
                   6915:                         $thisallowed.=$value;
                   6916:                     }
1.1162    raeburn  6917:                 }
1.671     raeburn  6918:             }
                   6919:         } else {
1.705     albertel 6920:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6921:             if ($refuri) {
                   6922:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6923:                     $thisallowed='F';
1.671     raeburn  6924:                 } else {
                   6925:                     $refuri=&declutter($refuri);
                   6926:                     my ($match) = &is_on_map($refuri);
                   6927:                     if ($match) {
1.1281    raeburn  6928:                         if ($noblockcheck) {
                   6929:                             $thisallowed='F';
1.1162    raeburn  6930:                         } else {
1.1281    raeburn  6931:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6932:                             if (@blockers > 0) {
                   6933:                                 $thisallowed = 'B';
                   6934:                             } else {
                   6935:                                 $thisallowed='F';
                   6936:                             }
1.1162    raeburn  6937:                         }
1.671     raeburn  6938:                     }
1.669     raeburn  6939:                 }
1.671     raeburn  6940:             }
                   6941:         }
1.314     www      6942:     }
1.492     albertel 6943: 
1.766     albertel 6944:     if ($priv eq 'bre'
                   6945: 	&& $thisallowed ne 'F' 
                   6946: 	&& $thisallowed ne '2'
                   6947: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  6948: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 6949:     }
1.1250    raeburn  6950: 
1.52      www      6951: # Full access at system, domain or course-wide level? Exit.
1.29      www      6952:     if ($thisallowed=~/F/) {
                   6953: 	return 'F';
                   6954:     }
                   6955: 
1.52      www      6956: # If this is generating or modifying users, exit with special codes
1.29      www      6957: 
1.643     www      6958:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6959: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6960: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6961: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6962: 	    unless ($auname) { return $thisallowed; }
                   6963: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6964: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6965: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6966: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6967: 	}
1.52      www      6968: 	return $thisallowed;
                   6969:     }
                   6970: #
1.103     harris41 6971: # Gathered so far: system, domain and course wide privileges
1.52      www      6972: #
                   6973: # Course: See if uri or referer is an individual resource that is part of 
                   6974: # the course
                   6975: 
1.620     albertel 6976:     if ($env{'request.course.id'}) {
1.232     www      6977: 
1.620     albertel 6978:        $courseprivid=$env{'request.course.id'};
                   6979:        if ($env{'request.course.sec'}) {
                   6980:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6981:        }
                   6982:        $courseprivid=~s/\_/\//;
                   6983:        my $checkreferer=1;
1.232     www      6984:        my ($match,$cond)=&is_on_map($uri);
                   6985:        if ($match) {
                   6986:            $statecond=$cond;
1.620     albertel 6987:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6988:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6989:                my $value = $1;
                   6990:                if ($priv eq 'bre') {
1.1281    raeburn  6991:                    if ($noblockcheck) {
                   6992:                        $thisallowed.=$value;
1.1162    raeburn  6993:                    } else {
1.1281    raeburn  6994:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6995:                        if (@blockers > 0) {
                   6996:                            $thisallowed = 'B';
                   6997:                        } else {
                   6998:                            $thisallowed.=$value;
                   6999:                        }
1.1162    raeburn  7000:                    }
                   7001:                } else {
                   7002:                    $thisallowed.=$value;
                   7003:                }
1.52      www      7004:                $checkreferer=0;
                   7005:            }
1.29      www      7006:        }
1.83      www      7007:        
1.148     www      7008:        if ($checkreferer) {
1.620     albertel 7009: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7010:             unless ($refuri) {
1.800     albertel 7011:                 foreach my $key (keys(%env)) {
                   7012: 		    if ($key=~/^httpref\..*\*/) {
                   7013: 			my $pattern=$key;
1.156     www      7014:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7015:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7016:                         $pattern=~s/\//\\\//g;
1.152     www      7017:                         if ($orguri=~/$pattern/) {
1.800     albertel 7018: 			    $refuri=$env{$key};
1.148     www      7019:                         }
                   7020:                     }
1.191     harris41 7021:                 }
1.148     www      7022:             }
1.232     www      7023: 
1.148     www      7024:          if ($refuri) { 
1.152     www      7025: 	  $refuri=&declutter($refuri);
1.232     www      7026:           my ($match,$cond)=&is_on_map($refuri);
                   7027:             if ($match) {
                   7028:               my $refstatecond=$cond;
1.620     albertel 7029:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7030:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7031:                   my $value = $1;
                   7032:                   if ($priv eq 'bre') {
1.1281    raeburn  7033:                       if ($noblockcheck) {
                   7034:                           $thisallowed.=$value;
1.1162    raeburn  7035:                       } else {
1.1281    raeburn  7036:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7037:                           if (@blockers > 0) {
                   7038:                               $thisallowed = 'B';
                   7039:                           } else {
                   7040:                               $thisallowed.=$value;
                   7041:                           }
1.1162    raeburn  7042:                       }
                   7043:                   } else {
                   7044:                       $thisallowed.=$value;
                   7045:                   }
1.53      www      7046:                   $uri=$refuri;
                   7047:                   $statecond=$refstatecond;
1.52      www      7048:               }
                   7049:           }
1.148     www      7050:         }
1.29      www      7051:        }
1.52      www      7052:    }
1.29      www      7053: 
1.52      www      7054: #
1.103     harris41 7055: # Gathered now: all privileges that could apply, and condition number
1.52      www      7056: # 
                   7057: #
                   7058: # Full or no access?
                   7059: #
1.29      www      7060: 
1.52      www      7061:     if ($thisallowed=~/F/) {
                   7062: 	return 'F';
                   7063:     }
1.29      www      7064: 
1.52      www      7065:     unless ($thisallowed) {
                   7066:         return '';
                   7067:     }
1.29      www      7068: 
1.52      www      7069: # Restrictions exist, deal with them
                   7070: #
                   7071: #   C:according to course preferences
                   7072: #   R:according to resource settings
                   7073: #   L:unless locked
                   7074: #   X:according to user session state
                   7075: #
                   7076: 
                   7077: # Possibly locked functionality, check all courses
1.54      www      7078: # Locks might take effect only after 10 minutes cache expiration for other
                   7079: # courses, and 2 minutes for current course
1.52      www      7080: 
                   7081:     my $envkey;
                   7082:     if ($thisallowed=~/L/) {
1.1000    raeburn  7083:         foreach $envkey (keys(%env)) {
1.54      www      7084:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7085:                my $courseid=$2;
                   7086:                my $roleid=$1.'.'.$2;
1.92      www      7087:                $courseid=~s/^\///;
1.54      www      7088:                my $expiretime=600;
1.620     albertel 7089:                if ($env{'request.role'} eq $roleid) {
1.54      www      7090: 		  $expiretime=120;
                   7091:                }
                   7092: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7093:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7094:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7095: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7096:                }
1.620     albertel 7097:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7098:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7099: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7100:                        &log($env{'user.domain'},$env{'user.name'},
                   7101:                             $env{'user.home'},
1.57      www      7102:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7103:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7104:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7105: 		       return '';
                   7106:                    }
                   7107:                }
1.620     albertel 7108:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7109:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7110: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7111:                        &log($env{'user.domain'},$env{'user.name'},
                   7112:                             $env{'user.home'},
1.57      www      7113:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7114:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7115:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7116: 		       return '';
                   7117:                    }
                   7118:                }
                   7119: 	   }
1.29      www      7120:        }
1.52      www      7121:     }
                   7122:    
                   7123: #
                   7124: # Rest of the restrictions depend on selected course
                   7125: #
                   7126: 
1.620     albertel 7127:     unless ($env{'request.course.id'}) {
1.766     albertel 7128: 	if ($thisallowed eq 'A') {
                   7129: 	    return 'A';
1.814     raeburn  7130:         } elsif ($thisallowed eq 'B') {
                   7131:             return 'B';
1.766     albertel 7132: 	} else {
                   7133: 	    return '1';
                   7134: 	}
1.52      www      7135:     }
1.29      www      7136: 
1.52      www      7137: #
                   7138: # Now user is definitely in a course
                   7139: #
1.53      www      7140: 
                   7141: 
                   7142: # Course preferences
                   7143: 
                   7144:    if ($thisallowed=~/C/) {
1.620     albertel 7145:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7146:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7147:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7148: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  7149: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7150: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7151: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7152: 			$env{'request.course.id'});
                   7153: 	   }
1.237     www      7154:            return '';
                   7155:        }
                   7156: 
1.620     albertel 7157:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7158: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  7159: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7160: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7161: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7162: 			$env{'request.course.id'});
                   7163: 	   }
1.54      www      7164:            return '';
                   7165:        }
1.53      www      7166:    }
                   7167: 
                   7168: # Resource preferences
                   7169: 
                   7170:    if ($thisallowed=~/R/) {
1.620     albertel 7171:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7172:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7173: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7174: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7175: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7176: 	   }
                   7177: 	   return '';
1.54      www      7178:        }
1.53      www      7179:    }
1.30      www      7180: 
1.246     www      7181: # Restricted by state or randomout?
1.30      www      7182: 
1.52      www      7183:    if ($thisallowed=~/X/) {
1.620     albertel 7184:       if ($env{'acc.randomout'}) {
1.579     albertel 7185: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7186:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7187:             return ''; 
                   7188:          }
1.247     www      7189:       }
                   7190:       if (&condval($statecond)) {
1.52      www      7191: 	 return '2';
                   7192:       } else {
                   7193:          return '';
                   7194:       }
                   7195:    }
1.30      www      7196: 
1.766     albertel 7197:     if ($thisallowed eq 'A') {
                   7198: 	return 'A';
1.814     raeburn  7199:     } elsif ($thisallowed eq 'B') {
                   7200:         return 'B';
1.766     albertel 7201:     }
1.52      www      7202:    return 'F';
1.232     www      7203: }
1.1162    raeburn  7204: 
1.1192    raeburn  7205: # ------------------------------------------- Check construction space access
                   7206: 
                   7207: sub constructaccess {
                   7208:     my ($url,$setpriv)=@_;
                   7209: 
                   7210: # We do not allow editing of previous versions of files
                   7211:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7212: 
                   7213: # Get username and domain from URL
                   7214:     my ($ownername,$ownerdomain,$ownerhome);
                   7215: 
                   7216:     ($ownerdomain,$ownername) =
                   7217:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
                   7218: 
                   7219: # The URL does not really point to any authorspace, forget it
                   7220:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7221: 
                   7222: # Now we need to see if the user has access to the authorspace of
                   7223: # $ownername at $ownerdomain
                   7224: 
                   7225:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7226: # Real author for this?
                   7227:        $ownerhome = $env{'user.home'};
                   7228:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7229:           return ($ownername,$ownerdomain,$ownerhome);
                   7230:        }
                   7231:     } else {
                   7232: # Co-author for this?
                   7233:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7234:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7235:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7236:             return ($ownername,$ownerdomain,$ownerhome);
                   7237:         }
                   7238:     }
                   7239: 
                   7240: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7241: # we might as well leave
                   7242:    unless ($setpriv) { return ''; }
                   7243: 
                   7244: # Backdoor access?
                   7245:     my $allowed=&allowed('eco',$ownerdomain);
                   7246: # Nope
                   7247:     unless ($allowed) { return ''; }
                   7248: # Looks like we may have access, but could be locked by the owner of the construction space
                   7249:     if ($allowed eq 'U') {
                   7250:         my %blocked=&get('environment',['domcoord.author'],
                   7251:                          $ownerdomain,$ownername);
                   7252: # Is blocked by owner
                   7253:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7254:     }
                   7255:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7256: # Grant temporary access
                   7257:         my $then=$env{'user.login.time'};
1.1209    raeburn  7258:         my $update=$env{'user.update.time'};
1.1192    raeburn  7259:         if (!$update) { $update = $then; }
                   7260:         my $refresh=$env{'user.refresh.time'};
                   7261:         if (!$refresh) { $refresh = $update; }
                   7262:         my $now = time;
                   7263:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7264:                            $now,'ca','constructaccess');
                   7265:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7266:         return($ownername,$ownerdomain,$ownerhome);
                   7267:     }
                   7268: # No business here
                   7269:     return '';
                   7270: }
                   7271: 
1.1282    raeburn  7272: # ----------------------------------------------------------- Content Blocking
                   7273: 
                   7274: {
                   7275: # Caches for faster Course Contents display where content blocking
                   7276: # is in operation (i.e., interval param set) for timed quiz.
                   7277: #
                   7278: # User for whom data are being temporarily cached.
                   7279: my $cacheduser='';
                   7280: # Cached blockers for this user (a hash of blocking items). 
                   7281: my %cachedblockers=();
                   7282: # When the data were last cached.
                   7283: my $cachedlast='';
                   7284: 
                   7285: sub load_all_blockers {
                   7286:     my ($uname,$udom,$blocks)=@_;
                   7287:     if (($uname ne '') && ($udom ne '')) { 
                   7288:         if (($cacheduser eq $uname.':'.$udom) &&
                   7289:             (abs($cachedlast-time)<5)) {
                   7290:             return;
                   7291:         }
                   7292:     }
                   7293:     $cachedlast=time;
                   7294:     $cacheduser=$uname.':'.$udom;
                   7295:     %cachedblockers = &get_commblock_resources($blocks);
                   7296: }
                   7297: 
1.1162    raeburn  7298: sub get_comm_blocks {
                   7299:     my ($cdom,$cnum) = @_;
                   7300:     if ($cdom eq '' || $cnum eq '') {
                   7301:         return unless ($env{'request.course.id'});
                   7302:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7303:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7304:     }
                   7305:     my %commblocks;
                   7306:     my $hashid=$cdom.'_'.$cnum;
                   7307:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7308:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7309:         %commblocks = %{$blocksref};
                   7310:     } else {
                   7311:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7312:         my $cachetime = 600;
                   7313:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7314:     }
                   7315:     return %commblocks;
                   7316: }
                   7317: 
1.1282    raeburn  7318: sub get_commblock_resources {
                   7319:     my ($blocks) = @_;
                   7320:     my %blockers = ();
                   7321:     return %blockers unless ($env{'request.course.id'});
                   7322:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7323:     my %commblocks;
                   7324:     if (ref($blocks) eq 'HASH') {
                   7325:         %commblocks = %{$blocks};
                   7326:     } else {
                   7327:         %commblocks = &get_comm_blocks();
                   7328:     }
1.1282    raeburn  7329:     return %blockers unless (keys(%commblocks) > 0); 
                   7330:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7331:     return %blockers unless (ref($navmap));
1.1162    raeburn  7332:     my $now = time;
                   7333:     foreach my $block (keys(%commblocks)) {
                   7334:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7335:             my ($start,$end) = ($1,$2);
                   7336:             if ($start <= $now && $end >= $now) {
                   7337:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7338:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7339:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  7340:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7341:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  7342:                             }
                   7343:                         }
                   7344:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  7345:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7346:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7347:                             }
                   7348:                         }
                   7349:                     }
                   7350:                 }
                   7351:             }
                   7352:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7353:             my $item = $1;
1.1163    raeburn  7354:             my @to_test;
1.1162    raeburn  7355:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7356:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  7357:                     my @interval;
                   7358:                     my $type = 'map';
                   7359:                     if ($item eq 'course') {
                   7360:                         $type = 'course';
                   7361:                         @interval=&EXT("resource.0.interval");
                   7362:                     } else {
                   7363:                         if ($item =~ /___\d+___/) {
                   7364:                             $type = 'resource';
                   7365:                             @interval=&EXT("resource.0.interval",$item);
                   7366:                             if (ref($navmap)) {                        
                   7367:                                 my $res = $navmap->getBySymb($item); 
                   7368:                                 push(@to_test,$res);
                   7369:                             }
1.1162    raeburn  7370:                         } else {
1.1282    raeburn  7371:                             my $mapsymb = &symbread($item,1);
                   7372:                             if ($mapsymb) {
                   7373:                                 if (ref($navmap)) {
                   7374:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7375:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7376:                                     foreach my $res (@to_test) {
                   7377:                                         my $symb = $res->symb();
                   7378:                                         next if ($symb eq $mapsymb);
                   7379:                                         if ($symb ne '') {
                   7380:                                             @interval=&EXT("resource.0.interval",$symb);
                   7381:                                             if ($interval[1] eq 'map') {
                   7382:                                                 last;
1.1162    raeburn  7383:                                             }
                   7384:                                         }
                   7385:                                     }
                   7386:                                 }
                   7387:                             }
                   7388:                         }
1.1282    raeburn  7389:                     }
                   7390:                     if ($interval[0] =~ /^\d+$/) {
                   7391:                         my $first_access;
                   7392:                         if ($type eq 'resource') {
                   7393:                             $first_access=&get_first_access($interval[1],$item);
                   7394:                         } elsif ($type eq 'map') {
                   7395:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7396:                         } else {
                   7397:                             $first_access=&get_first_access($interval[1]);
                   7398:                         }
                   7399:                         if ($first_access) {
                   7400:                             my $timesup = $first_access+$interval[0];
                   7401:                             if ($timesup > $now) {
                   7402:                                 my $activeblock;
                   7403:                                 foreach my $res (@to_test) {
1.1283    raeburn  7404:                                     if ($res->answerable()) {
1.1282    raeburn  7405:                                         $activeblock = 1;
                   7406:                                         last;
                   7407:                                     }
                   7408:                                 }
                   7409:                                 if ($activeblock) {
                   7410:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7411:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7412:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7413:                                          }
                   7414:                                     }
                   7415:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7416:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7417:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7418:                                         }
1.1162    raeburn  7419:                                     }
                   7420:                                 }
                   7421:                             }
                   7422:                         }
                   7423:                     }
                   7424:                 }
                   7425:             }
                   7426:         }
                   7427:     }
1.1282    raeburn  7428:     return %blockers;
1.1162    raeburn  7429: }
                   7430: 
1.1282    raeburn  7431: sub has_comm_blocking {
                   7432:     my ($priv,$symb,$uri,$blocks) = @_;
                   7433:     my @blockers;
                   7434:     return unless ($env{'request.course.id'});
                   7435:     return unless ($priv eq 'bre');
                   7436:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7437:     return if ($env{'request.state'} eq 'construct');
                   7438:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7439:     return unless (keys(%cachedblockers) > 0);
                   7440:     my (%possibles,@symbs);
                   7441:     if (!$symb) {
                   7442:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7443:     }
1.1282    raeburn  7444:     if ($symb) {
                   7445:         @symbs = ($symb);
                   7446:     } elsif (keys(%possibles)) { 
                   7447:         @symbs = keys(%possibles);
                   7448:     }
                   7449:     my $noblock;
                   7450:     foreach my $symb (@symbs) {
                   7451:         last if ($noblock);
                   7452:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7453:         foreach my $block (keys(%cachedblockers)) {
                   7454:             if ($block =~ /^firstaccess____(.+)$/) {
                   7455:                 my $item = $1;
                   7456:                 if (($item eq $map) || ($item eq $symb)) {
                   7457:                     $noblock = 1;
                   7458:                     last;
                   7459:                 }
                   7460:             }
                   7461:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7462:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7463:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7464:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7465:                             push(@blockers,$block);
                   7466:                         }
                   7467:                     }
                   7468:                 }
1.1162    raeburn  7469:             }
1.1282    raeburn  7470:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7471:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7472:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7473:                         push(@blockers,$block);
                   7474:                     }
                   7475:                 }
1.1162    raeburn  7476:             }
                   7477:         }
                   7478:     }
1.1282    raeburn  7479:     return if ($noblock);
                   7480:     return @blockers;
                   7481: }
1.1162    raeburn  7482: }
                   7483: 
1.1282    raeburn  7484: # -------------------------------- Deversion and split uri into path an filename   
                   7485: 
1.1133    foxr     7486: #
1.1282    raeburn  7487: #   Removes the version from a URI and
1.1133    foxr     7488: #   splits it in to its filename and path to the filename.
                   7489: #   Seems like File::Basename could have done this more clearly.
                   7490: #   Parameters:
                   7491: #      $uri   - input URI
                   7492: #   Returns:
                   7493: #     Two element list consisting of 
                   7494: #     $pathname  - the URI up to and excluding the trailing /
                   7495: #     $filename  - The part of the URI following the last /
                   7496: #  NOTE:
                   7497: #    Another realization of this is simply:
                   7498: #    use File::Basename;
                   7499: #    ...
                   7500: #    $uri = shift;
                   7501: #    $filename = basename($uri);
                   7502: #    $path     = dirname($uri);
                   7503: #    return ($filename, $path);
                   7504: #
                   7505: #     The implementation below is probably faster however.
                   7506: #
1.710     albertel 7507: sub split_uri_for_cond {
                   7508:     my $uri=&deversion(&declutter(shift));
                   7509:     my @uriparts=split(/\//,$uri);
                   7510:     my $filename=pop(@uriparts);
                   7511:     my $pathname=join('/',@uriparts);
                   7512:     return ($pathname,$filename);
                   7513: }
1.232     www      7514: # --------------------------------------------------- Is a resource on the map?
                   7515: 
                   7516: sub is_on_map {
1.710     albertel 7517:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7518:     #Trying to find the conditional for the file
1.620     albertel 7519:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7520: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7521:     if ($match) {
1.289     bowersj2 7522: 	return (1,$1);
                   7523:     } else {
1.434     www      7524: 	return (0,0);
1.289     bowersj2 7525:     }
1.12      www      7526: }
                   7527: 
1.427     www      7528: # --------------------------------------------------------- Get symb from alias
                   7529: 
                   7530: sub get_symb_from_alias {
                   7531:     my $symb=shift;
                   7532:     my ($map,$resid,$url)=&decode_symb($symb);
                   7533: # Already is a symb
                   7534:     if ($url) { return $symb; }
                   7535: # Must be an alias
                   7536:     my $aliassymb='';
                   7537:     my %bighash;
1.620     albertel 7538:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7539:                             &GDBM_READER(),0640)) {
                   7540:         my $rid=$bighash{'mapalias_'.$symb};
                   7541: 	if ($rid) {
                   7542: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7543: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7544: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7545: 	}
                   7546:         untie %bighash;
                   7547:     }
                   7548:     return $aliassymb;
                   7549: }
                   7550: 
1.12      www      7551: # ----------------------------------------------------------------- Define Role
                   7552: 
                   7553: sub definerole {
                   7554:   if (allowed('mcr','/')) {
                   7555:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 7556:     foreach my $role (split(':',$sysrole)) {
                   7557: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7558:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   7559:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   7560: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7561:                return "refused:s:$crole&$cqual"; 
                   7562:             }
                   7563:         }
1.191     harris41 7564:     }
1.800     albertel 7565:     foreach my $role (split(':',$domrole)) {
                   7566: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7567:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   7568:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   7569: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      7570:                return "refused:d:$crole&$cqual"; 
                   7571:             }
                   7572:         }
1.191     harris41 7573:     }
1.800     albertel 7574:     foreach my $role (split(':',$courole)) {
                   7575: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 7576:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   7577:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   7578: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      7579:                return "refused:c:$crole&$cqual"; 
                   7580:             }
                   7581:         }
1.191     harris41 7582:     }
1.620     albertel 7583:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   7584:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7585: 	        "rolesdef_$rolename=".
                   7586:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 7587:     return reply($command,$env{'user.home'});
1.12      www      7588:   } else {
                   7589:     return 'refused';
                   7590:   }
1.105     harris41 7591: }
                   7592: 
                   7593: # ---------------- Make a metadata query against the network of library servers
                   7594: 
                   7595: sub metadata_query {
1.1237    raeburn  7596:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 7597:     my %rhash;
1.845     albertel 7598:     my %libserv = &all_library();
1.244     matthew  7599:     my @server_list = (defined($server_array) ? @$server_array
                   7600:                                               : keys(%libserv) );
                   7601:     for my $server (@server_list) {
1.1237    raeburn  7602:         my $domains = ''; 
                   7603:         if (ref($domains_hash) eq 'HASH') {
                   7604:             $domains = $domains_hash->{$server}; 
                   7605:         }
1.118     harris41 7606: 	unless ($custom or $customshow) {
1.1237    raeburn  7607: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 7608: 	    $rhash{$server}=$reply;
                   7609: 	}
                   7610: 	else {
                   7611: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  7612: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 7613: 			     $server);
                   7614: 	    $rhash{$server}=$reply;
                   7615: 	}
1.112     harris41 7616:     }
1.118     harris41 7617:     return \%rhash;
1.240     www      7618: }
                   7619: 
                   7620: # ----------------------------------------- Send log queries and wait for reply
                   7621: 
                   7622: sub log_query {
                   7623:     my ($uname,$udom,$query,%filters)=@_;
                   7624:     my $uhome=&homeserver($uname,$udom);
                   7625:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 7626:     my $uhost=&hostname($uhome);
1.800     albertel 7627:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      7628:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   7629:                        $uhome);
1.479     albertel 7630:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      7631:     return get_query_reply($queryid);
                   7632: }
                   7633: 
1.818     raeburn  7634: # -------------------------- Update MySQL table for portfolio file
                   7635: 
                   7636: sub update_portfolio_table {
1.821     raeburn  7637:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  7638:     if ($group ne '') {
                   7639:         $file_name =~s /^\Q$group\E//;
                   7640:     }
1.818     raeburn  7641:     my $homeserver = &homeserver($uname,$udom);
                   7642:     my $queryid=
1.821     raeburn  7643:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   7644:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  7645:     my $reply = &get_query_reply($queryid);
                   7646:     return $reply;
                   7647: }
                   7648: 
1.899     raeburn  7649: # -------------------------- Update MySQL allusers table
                   7650: 
                   7651: sub update_allusers_table {
                   7652:     my ($uname,$udom,$names) = @_;
                   7653:     my $homeserver = &homeserver($uname,$udom);
                   7654:     my $queryid=
                   7655:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   7656:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   7657:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   7658:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   7659:                'generation='.&escape($names->{'generation'}).'%%'.
                   7660:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   7661:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  7662:     return;
1.899     raeburn  7663: }
                   7664: 
1.508     raeburn  7665: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  7666: 
                   7667: sub fetch_enrollment_query {
1.511     raeburn  7668:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  7669:     my $homeserver;
1.547     raeburn  7670:     my $maxtries = 1;
1.508     raeburn  7671:     if ($context eq 'automated') {
                   7672:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  7673:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  7674:     } else {
                   7675:         $homeserver = &homeserver($cnum,$dom);
                   7676:     }
1.838     albertel 7677:     my $host=&hostname($homeserver);
1.506     raeburn  7678:     my $cmd = '';
1.1000    raeburn  7679:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 7680:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  7681:     }
                   7682:     $cmd =~ s/%%$//;
                   7683:     $cmd = &escape($cmd);
                   7684:     my $query = 'fetchenrollment';
1.620     albertel 7685:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  7686:     unless ($queryid=~/^\Q$host\E\_/) { 
                   7687:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   7688:         return 'error: '.$queryid;
                   7689:     }
1.506     raeburn  7690:     my $reply = &get_query_reply($queryid);
1.547     raeburn  7691:     my $tries = 1;
                   7692:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7693:         $reply = &get_query_reply($queryid);
                   7694:         $tries ++;
                   7695:     }
1.526     raeburn  7696:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 7697:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  7698:     } else {
1.901     albertel 7699:         my @responses = split(/:/,$reply);
1.515     raeburn  7700:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 7701:             foreach my $line (@responses) {
                   7702:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  7703:                 $$replyref{$key} = $value;
                   7704:             }
                   7705:         } else {
1.1117    foxr     7706:             my $pathname = LONCAPA::tempdir();
1.800     albertel 7707:             foreach my $line (@responses) {
                   7708:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  7709:                 $$replyref{$key} = $value;
                   7710:                 if ($value > 0) {
1.800     albertel 7711:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   7712:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  7713:                         my $destname = $pathname.'/'.$filename;
                   7714:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  7715:                         if ($xml_classlist =~ /^error/) {
                   7716:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   7717:                         } else {
1.506     raeburn  7718:                             if ( open(FILE,">$destname") ) {
                   7719:                                 print FILE &unescape($xml_classlist);
                   7720:                                 close(FILE);
1.526     raeburn  7721:                             } else {
                   7722:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  7723:                             }
                   7724:                         }
                   7725:                     }
                   7726:                 }
                   7727:             }
                   7728:         }
                   7729:         return 'ok';
                   7730:     }
                   7731:     return 'error';
                   7732: }
                   7733: 
1.242     www      7734: sub get_query_reply {
                   7735:     my $queryid=shift;
1.1117    foxr     7736:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      7737:     my $reply='';
                   7738:     for (1..100) {
1.1289    damieng  7739: 	sleep(0.2);
1.240     www      7740:         if (-e $replyfile.'.end') {
1.448     albertel 7741: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 7742: 		$reply = join('',<$fh>);
                   7743: 		close($fh);
1.240     www      7744: 	   } else { return 'error: reply_file_error'; }
1.242     www      7745:            return &unescape($reply);
                   7746: 	}
1.240     www      7747:     }
1.242     www      7748:     return 'timeout:'.$queryid;
1.240     www      7749: }
                   7750: 
                   7751: sub courselog_query {
1.241     www      7752: #
                   7753: # possible filters:
                   7754: # url: url or symb
                   7755: # username
                   7756: # domain
                   7757: # action: view, submit, grade
                   7758: # start: timestamp
                   7759: # end: timestamp
                   7760: #
1.240     www      7761:     my (%filters)=@_;
1.620     albertel 7762:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      7763:     if ($filters{'url'}) {
                   7764: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   7765:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   7766:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   7767:     }
1.620     albertel 7768:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7769:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      7770:     return &log_query($cname,$cdom,'courselog',%filters);
                   7771: }
                   7772: 
                   7773: sub userlog_query {
1.858     raeburn  7774: #
                   7775: # possible filters:
                   7776: # action: log check role
                   7777: # start: timestamp
                   7778: # end: timestamp
                   7779: #
1.240     www      7780:     my ($uname,$udom,%filters)=@_;
                   7781:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      7782: }
                   7783: 
1.506     raeburn  7784: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   7785: 
                   7786: sub auto_run {
1.508     raeburn  7787:     my ($cnum,$cdom) = @_;
1.876     raeburn  7788:     my $response = 0;
                   7789:     my $settings;
                   7790:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   7791:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   7792:         $settings = $domconfig{'autoenroll'};
                   7793:         if ($settings->{'run'} eq '1') {
                   7794:             $response = 1;
                   7795:         }
                   7796:     } else {
1.934     raeburn  7797:         my $homeserver;
                   7798:         if (&is_course($cdom,$cnum)) {
                   7799:             $homeserver = &homeserver($cnum,$cdom);
                   7800:         } else {
                   7801:             $homeserver = &domain($cdom,'primary');
                   7802:         }
                   7803:         if ($homeserver ne 'no_host') {
                   7804:             $response = &reply('autorun:'.$cdom,$homeserver);
                   7805:         }
1.876     raeburn  7806:     }
1.506     raeburn  7807:     return $response;
                   7808: }
1.776     albertel 7809: 
1.506     raeburn  7810: sub auto_get_sections {
1.508     raeburn  7811:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  7812:     my $homeserver;
                   7813:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   7814:         $homeserver = &homeserver($cnum,$cdom);
                   7815:     }
                   7816:     if (!defined($homeserver)) { 
                   7817:         if ($cdom =~ /^$match_domain$/) {
                   7818:             $homeserver = &domain($cdom,'primary');
                   7819:         }
                   7820:     }
                   7821:     my @secs;
                   7822:     if (defined($homeserver)) {
                   7823:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   7824:         unless ($response eq 'refused') {
                   7825:             @secs = split(/:/,$response);
                   7826:         }
1.506     raeburn  7827:     }
                   7828:     return @secs;
                   7829: }
1.776     albertel 7830: 
1.506     raeburn  7831: sub auto_new_course {
1.1099    raeburn  7832:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  7833:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  7834:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  7835:     return $response;
                   7836: }
1.776     albertel 7837: 
1.506     raeburn  7838: sub auto_validate_courseID {
1.508     raeburn  7839:     my ($cnum,$cdom,$inst_course_id) = @_;
                   7840:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  7841:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  7842:     return $response;
                   7843: }
1.776     albertel 7844: 
1.1007    raeburn  7845: sub auto_validate_instcode {
1.1020    raeburn  7846:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  7847:     my ($homeserver,$response);
                   7848:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7849:         $homeserver = &homeserver($cnum,$cdom);
                   7850:     }
                   7851:     if (!defined($homeserver)) {
                   7852:         if ($cdom =~ /^$match_domain$/) {
                   7853:             $homeserver = &domain($cdom,'primary');
                   7854:         }
                   7855:     }
1.1065    raeburn  7856:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   7857:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  7858:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   7859:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  7860: }
                   7861: 
1.506     raeburn  7862: sub auto_create_password {
1.873     raeburn  7863:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   7864:     my ($homeserver,$response);
1.506     raeburn  7865:     my $create_passwd = 0;
                   7866:     my $authchk = '';
1.873     raeburn  7867:     if ($udom =~ /^$match_domain$/) {
                   7868:         $homeserver = &domain($udom,'primary');
                   7869:     }
                   7870:     if ($homeserver eq '') {
                   7871:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   7872:             $homeserver = &homeserver($cnum,$cdom);
                   7873:         }
                   7874:     }
                   7875:     if ($homeserver eq '') {
                   7876:         $authchk = 'nodomain';
1.506     raeburn  7877:     } else {
1.873     raeburn  7878:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   7879:         if ($response eq 'refused') {
                   7880:             $authchk = 'refused';
                   7881:         } else {
1.901     albertel 7882:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  7883:         }
1.506     raeburn  7884:     }
                   7885:     return ($authparam,$create_passwd,$authchk);
                   7886: }
                   7887: 
1.706     raeburn  7888: sub auto_photo_permission {
                   7889:     my ($cnum,$cdom,$students) = @_;
                   7890:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 7891:     my ($outcome,$perm_reqd,$conditions) = 
                   7892: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7893:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7894: 	return (undef,undef);
                   7895:     }
1.706     raeburn  7896:     return ($outcome,$perm_reqd,$conditions);
                   7897: }
                   7898: 
                   7899: sub auto_checkphotos {
                   7900:     my ($uname,$udom,$pid) = @_;
                   7901:     my $homeserver = &homeserver($uname,$udom);
                   7902:     my ($result,$resulttype);
                   7903:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7904: 				   &escape($uname).':'.&escape($pid),
                   7905: 				   $homeserver));
1.709     albertel 7906:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7907: 	return (undef,undef);
                   7908:     }
1.706     raeburn  7909:     if ($outcome) {
                   7910:         ($result,$resulttype) = split(/:/,$outcome);
                   7911:     } 
                   7912:     return ($result,$resulttype);
                   7913: }
                   7914: 
                   7915: sub auto_photochoice {
                   7916:     my ($cnum,$cdom) = @_;
                   7917:     my $homeserver = &homeserver($cnum,$cdom);
                   7918:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7919: 						       &escape($cdom),
                   7920: 						       $homeserver)));
1.709     albertel 7921:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7922: 	return (undef,undef);
                   7923:     }
1.706     raeburn  7924:     return ($update,$comment);
                   7925: }
                   7926: 
                   7927: sub auto_photoupdate {
                   7928:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7929:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7930:     my $host=&hostname($homeserver);
1.706     raeburn  7931:     my $cmd = '';
                   7932:     my $maxtries = 1;
1.800     albertel 7933:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7934:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7935:     }
                   7936:     $cmd =~ s/%%$//;
                   7937:     $cmd = &escape($cmd);
                   7938:     my $query = 'institutionalphotos';
                   7939:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7940:     unless ($queryid=~/^\Q$host\E\_/) {
                   7941:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7942:         return 'error: '.$queryid;
                   7943:     }
                   7944:     my $reply = &get_query_reply($queryid);
                   7945:     my $tries = 1;
                   7946:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7947:         $reply = &get_query_reply($queryid);
                   7948:         $tries ++;
                   7949:     }
                   7950:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7951:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7952:     } else {
                   7953:         my @responses = split(/:/,$reply);
                   7954:         my $outcome = shift(@responses); 
                   7955:         foreach my $item (@responses) {
                   7956:             my ($key,$value) = split(/=/,$item);
                   7957:             $$photo{$key} = $value;
                   7958:         }
                   7959:         return $outcome;
                   7960:     }
                   7961:     return 'error';
                   7962: }
                   7963: 
1.521     raeburn  7964: sub auto_instcode_format {
1.793     albertel 7965:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7966: 	$cat_order) = @_;
1.521     raeburn  7967:     my $courses = '';
1.772     raeburn  7968:     my @homeservers;
1.521     raeburn  7969:     if ($caller eq 'global') {
1.841     albertel 7970: 	my %servers = &get_servers($codedom,'library');
                   7971: 	foreach my $tryserver (keys(%servers)) {
                   7972: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7973: 		push(@homeservers,$tryserver);
                   7974: 	    }
1.584     raeburn  7975:         }
1.1022    raeburn  7976:     } elsif ($caller eq 'requests') {
                   7977:         if ($codedom =~ /^$match_domain$/) {
                   7978:             my $chome = &domain($codedom,'primary');
                   7979:             unless ($chome eq 'no_host') {
                   7980:                 push(@homeservers,$chome);
                   7981:             }
                   7982:         }
1.521     raeburn  7983:     } else {
1.772     raeburn  7984:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7985:     }
1.793     albertel 7986:     foreach my $code (keys(%{$instcodes})) {
                   7987:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7988:     }
                   7989:     chop($courses);
1.772     raeburn  7990:     my $ok_response = 0;
                   7991:     my $response;
                   7992:     while (@homeservers > 0 && $ok_response == 0) {
                   7993:         my $server = shift(@homeservers); 
                   7994:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7995:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7996:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7997: 		split(/:/,$response);
1.772     raeburn  7998:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7999:             push(@{$codetitles},&str2array($codetitles_str));
                   8000:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8001:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8002:             $ok_response = 1;
                   8003:         }
                   8004:     }
                   8005:     if ($ok_response) {
1.521     raeburn  8006:         return 'ok';
1.772     raeburn  8007:     } else {
                   8008:         return $response;
1.521     raeburn  8009:     }
                   8010: }
                   8011: 
1.792     raeburn  8012: sub auto_instcode_defaults {
                   8013:     my ($domain,$returnhash,$code_order) = @_;
                   8014:     my @homeservers;
1.841     albertel 8015: 
                   8016:     my %servers = &get_servers($domain,'library');
                   8017:     foreach my $tryserver (keys(%servers)) {
                   8018: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8019: 	    push(@homeservers,$tryserver);
                   8020: 	}
1.792     raeburn  8021:     }
1.841     albertel 8022: 
1.792     raeburn  8023:     my $response;
1.841     albertel 8024:     foreach my $server (@homeservers) {
1.792     raeburn  8025:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8026:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8027: 	
                   8028: 	foreach my $pair (split(/\&/,$response)) {
                   8029: 	    my ($name,$value)=split(/\=/,$pair);
                   8030: 	    if ($name eq 'code_order') {
                   8031: 		@{$code_order} = split(/\&/,&unescape($value));
                   8032: 	    } else {
                   8033: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8034: 	    }
                   8035: 	}
                   8036: 	return 'ok';
1.792     raeburn  8037:     }
1.841     albertel 8038: 
                   8039:     return $response;
1.1003    raeburn  8040: }
                   8041: 
                   8042: sub auto_possible_instcodes {
1.1007    raeburn  8043:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8044:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8045:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8046:         return;
                   8047:     }
1.1003    raeburn  8048:     my (@homeservers,$uhome);
                   8049:     if (defined(&domain($domain,'primary'))) {
                   8050:         $uhome=&domain($domain,'primary');
                   8051:         push(@homeservers,&domain($domain,'primary'));
                   8052:     } else {
                   8053:         my %servers = &get_servers($domain,'library');
                   8054:         foreach my $tryserver (keys(%servers)) {
                   8055:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8056:                 push(@homeservers,$tryserver);
                   8057:             }
                   8058:         }
                   8059:     }
                   8060:     my $response;
                   8061:     foreach my $server (@homeservers) {
                   8062:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8063:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8064:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8065:             split(':',$response);
                   8066:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8067:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8068:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8069:             my ($name,$value)=split('=',$item);
                   8070:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8071:         }
                   8072:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8073:             my ($name,$value)=split('=',$item);
                   8074:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8075:         }
                   8076:         return 'ok';
                   8077:     }
                   8078:     return $response;
                   8079: }
1.792     raeburn  8080: 
1.1010    raeburn  8081: sub auto_courserequest_checks {
                   8082:     my ($dom) = @_;
1.1020    raeburn  8083:     my ($homeserver,%validations);
                   8084:     if ($dom =~ /^$match_domain$/) {
                   8085:         $homeserver = &domain($dom,'primary');
                   8086:     }
                   8087:     unless ($homeserver eq 'no_host') {
                   8088:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8089:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8090:             my @items = split(/&/,$response);
                   8091:             foreach my $item (@items) {
                   8092:                 my ($key,$value) = split('=',$item);
                   8093:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8094:             }
                   8095:         }
                   8096:     }
1.1010    raeburn  8097:     return %validations; 
                   8098: }
                   8099: 
1.1020    raeburn  8100: sub auto_courserequest_validation {
1.1255    raeburn  8101:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8102:     my ($homeserver,$response);
                   8103:     if ($dom =~ /^$match_domain$/) {
                   8104:         $homeserver = &domain($dom,'primary');
                   8105:     }
1.1255    raeburn  8106:     unless ($homeserver eq 'no_host') {
                   8107:         my $customdata;
                   8108:         if (ref($custominfo) eq 'HASH') {
                   8109:             $customdata = &freeze_escape($custominfo);
                   8110:         }
1.1020    raeburn  8111:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8112:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8113:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8114:                                     $customdata,$homeserver));
1.1020    raeburn  8115:     }
                   8116:     return $response;
                   8117: }
                   8118: 
1.777     albertel 8119: sub auto_validate_class_sec {
1.918     raeburn  8120:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8121:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8122:     my $ownerlist;
                   8123:     if (ref($owners) eq 'ARRAY') {
                   8124:         $ownerlist = join(',',@{$owners});
                   8125:     } else {
                   8126:         $ownerlist = $owners;
                   8127:     }
1.773     raeburn  8128:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8129:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8130:     return $response;
                   8131: }
                   8132: 
1.1248    raeburn  8133: sub auto_crsreq_update {
                   8134:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8135:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8136:     my ($homeserver,%crsreqresponse);
                   8137:     if ($cdom =~ /^$match_domain$/) {
                   8138:         $homeserver = &domain($cdom,'primary');
                   8139:     }
                   8140:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8141:         my $info;
                   8142:         if (ref($inbound) eq 'HASH') {
                   8143:             $info = &freeze_escape($inbound);
                   8144:         }
                   8145:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8146:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8147:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8148:                             &escape($title).':'.&escape($code).':'.
                   8149:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8150:                             $homeserver);
1.1248    raeburn  8151:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8152:             my @items = split(/&/,$response);
                   8153:             foreach my $item (@items) {
                   8154:                 my ($key,$value) = split('=',$item);
                   8155:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8156:             }
                   8157:         }
                   8158:     }
                   8159:     return \%crsreqresponse;
                   8160: }
                   8161: 
1.1287    raeburn  8162: sub check_instcode_cloning {
                   8163:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8164:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8165:         return;
                   8166:     }
                   8167:     my $canclone;
                   8168:     if (@{$code_order} > 0) {
                   8169:         my $instcoderegexp ='^';
                   8170:         my @clonecodes = split(/\&/,$cloner);
                   8171:         foreach my $item (@{$code_order}) {
                   8172:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8173:                 foreach my $pair (@clonecodes) {
                   8174:                     my ($key,$val) = split(/\=/,$pair,2);
                   8175:                     $val = &unescape($val);
                   8176:                     if ($key eq $item) {
                   8177:                         $instcoderegexp .= '('.$val.')';
                   8178:                         last;
                   8179:                     }
                   8180:                 }
                   8181:             } else {
                   8182:                 $instcoderegexp .= $codedefaults->{$item};
                   8183:             }
                   8184:         }
                   8185:         $instcoderegexp .= '$';
                   8186:         my (@from,@to);
                   8187:         eval {
                   8188:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8189:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8190:         };
                   8191:         if ((@from > 0) && (@to > 0)) {
                   8192:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8193:             if (!@diffs) {
                   8194:                 $canclone = 1;
                   8195:             }
                   8196:         }
                   8197:     }
                   8198:     return $canclone;
                   8199: }
                   8200: 
                   8201: sub default_instcode_cloning {
                   8202:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8203:     my (%codedefaults,@code_order,$canclone);
                   8204:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8205:         %codedefaults = %{$codedefaultsref};
                   8206:         @code_order = @{$codeorderref};
                   8207:     } elsif ($clonedom) {
                   8208:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8209:     }
                   8210:     if (($domdefclone) && (@code_order)) {
                   8211:         my @clonecodes = split(/\+/,$domdefclone);
                   8212:         my $instcoderegexp ='^';
                   8213:         foreach my $item (@code_order) {
                   8214:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8215:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8216:             } else {
                   8217:                 $instcoderegexp .= $codedefaults{$item};
                   8218:             }
                   8219:         }
                   8220:         $instcoderegexp .= '$';
                   8221:         my (@from,@to);
                   8222:         eval {
                   8223:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8224:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8225:         };
                   8226:         if ((@from > 0) && (@to > 0)) {
                   8227:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8228:             if (!@diffs) {
                   8229:                 $canclone = 1;
                   8230:             }
                   8231:         }
                   8232:     }
                   8233:     return $canclone;
                   8234: }
                   8235: 
1.679     raeburn  8236: # ------------------------------------------------------- Course Group routines
                   8237: 
                   8238: sub get_coursegroups {
1.809     raeburn  8239:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8240:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8241: }
                   8242: 
1.679     raeburn  8243: sub modify_coursegroup {
                   8244:     my ($cdom,$cnum,$groupsettings) = @_;
                   8245:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8246: }
                   8247: 
1.809     raeburn  8248: sub toggle_coursegroup_status {
                   8249:     my ($cdom,$cnum,$group,$action) = @_;
                   8250:     my ($from_namespace,$to_namespace);
                   8251:     if ($action eq 'delete') {
                   8252:         $from_namespace = 'coursegroups';
                   8253:         $to_namespace = 'deleted_groups';
                   8254:     } else {
                   8255:         $from_namespace = 'deleted_groups';
                   8256:         $to_namespace = 'coursegroups';
                   8257:     }
                   8258:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8259:     if (my $tmp = &error(%curr_group)) {
                   8260:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8261:         return ('read error',$tmp);
                   8262:     } else {
                   8263:         my %savedsettings = %curr_group; 
1.809     raeburn  8264:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8265:         my $deloutcome;
                   8266:         if ($result eq 'ok') {
1.809     raeburn  8267:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8268:         } else {
                   8269:             return ('write error',$result);
                   8270:         }
                   8271:         if ($deloutcome eq 'ok') {
                   8272:             return 'ok';
                   8273:         } else {
                   8274:             return ('delete error',$deloutcome);
                   8275:         }
                   8276:     }
                   8277: }
                   8278: 
1.679     raeburn  8279: sub modify_group_roles {
1.957     raeburn  8280:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8281:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8282:     my $role = 'gr/'.&escape($userprivs);
                   8283:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8284:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8285:     if ($result eq 'ok') {
                   8286:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8287:     }
1.679     raeburn  8288:     return $result;
                   8289: }
                   8290: 
                   8291: sub modify_coursegroup_membership {
                   8292:     my ($cdom,$cnum,$membership) = @_;
                   8293:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8294:     return $result;
                   8295: }
                   8296: 
1.682     raeburn  8297: sub get_active_groups {
                   8298:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8299:     my $now = time;
                   8300:     my %groups = ();
                   8301:     foreach my $key (keys(%env)) {
1.811     albertel 8302:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8303:             my ($start,$end) = split(/\./,$env{$key});
                   8304:             if (($end!=0) && ($end<$now)) { next; }
                   8305:             if (($start!=0) && ($start>$now)) { next; }
                   8306:             if ($1 eq $cdom && $2 eq $cnum) {
                   8307:                 $groups{$3} = $env{$key} ;
                   8308:             }
                   8309:         }
                   8310:     }
                   8311:     return %groups;
                   8312: }
                   8313: 
1.683     raeburn  8314: sub get_group_membership {
                   8315:     my ($cdom,$cnum,$group) = @_;
                   8316:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8317: }
                   8318: 
                   8319: sub get_users_groups {
                   8320:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8321:     my @usersgroups;
1.683     raeburn  8322:     my $cachetime=1800;
                   8323: 
                   8324:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8325:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8326:     if (defined($cached)) {
1.734     albertel 8327:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8328:     } else {  
                   8329:         $grouplist = '';
1.816     raeburn  8330:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8331:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8332:         my $access_end = $env{'course.'.$courseid.
                   8333:                               '.default_enrollment_end_date'};
                   8334:         my $now = time;
                   8335:         foreach my $key (keys(%roleshash)) {
                   8336:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8337:                 my $group = $1;
                   8338:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8339:                     my $start = $2;
                   8340:                     my $end = $1;
                   8341:                     if ($start == -1) { next; } # deleted from group
                   8342:                     if (($start!=0) && ($start>$now)) { next; }
                   8343:                     if (($end!=0) && ($end<$now)) {
                   8344:                         if ($access_end && $access_end < $now) {
                   8345:                             if ($access_end - $end < 86400) {
                   8346:                                 push(@usersgroups,$group);
1.733     raeburn  8347:                             }
                   8348:                         }
1.817     raeburn  8349:                         next;
1.733     raeburn  8350:                     }
1.817     raeburn  8351:                     push(@usersgroups,$group);
1.683     raeburn  8352:                 }
                   8353:             }
                   8354:         }
1.817     raeburn  8355:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8356:         $grouplist = join(':',@usersgroups);
                   8357:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8358:     }
1.733     raeburn  8359:     return @usersgroups;
1.683     raeburn  8360: }
                   8361: 
                   8362: sub devalidate_getgroups_cache {
                   8363:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8364:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8365: 
1.683     raeburn  8366:     my $hashid="$udom:$uname:$courseid";
                   8367:     &devalidate_cache_new('getgroups',$hashid);
                   8368: }
                   8369: 
1.12      www      8370: # ------------------------------------------------------------------ Plain Text
                   8371: 
                   8372: sub plaintext {
1.988     raeburn  8373:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8374:     if ($short =~ m{^cr/}) {
1.758     albertel 8375: 	return (split('/',$short))[-1];
                   8376:     }
1.742     raeburn  8377:     if (!defined($cid)) {
                   8378:         $cid = $env{'request.course.id'};
                   8379:     }
                   8380:     my %rolenames = (
1.1008    raeburn  8381:                       Course    => 'std',
                   8382:                       Community => 'alt1',
1.742     raeburn  8383:                     );
1.1037    raeburn  8384:     if ($cid ne '') {
                   8385:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8386:             unless ($forcedefault) {
                   8387:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8388:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8389:                 return &Apache::lonlocal::mt($roletext);
                   8390:             }
                   8391:         }
                   8392:     }
                   8393:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8394:         (defined($rolenames{$type})) && 
                   8395:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8396:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8397:     } elsif ($cid ne '') {
                   8398:         my $crstype = $env{'course.'.$cid.'.type'};
                   8399:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8400:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8401:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8402:         }
1.742     raeburn  8403:     }
1.1037    raeburn  8404:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8405: }
                   8406: 
                   8407: # ----------------------------------------------------------------- Assign Role
                   8408: 
                   8409: sub assignrole {
1.957     raeburn  8410:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8411:         $context)=@_;
1.21      www      8412:     my $mrole;
                   8413:     if ($role =~ /^cr\//) {
1.393     www      8414:         my $cwosec=$url;
1.811     albertel 8415:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8416: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8417:            my $refused = 1;
                   8418:            if ($context eq 'requestcourses') {
                   8419:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8420:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8421:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8422:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8423:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8424:                            if ($crsenv{'internal.courseowner'} eq
                   8425:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8426:                                $refused = '';
                   8427:                            }
                   8428:                        }
                   8429:                    }
                   8430:                }
                   8431:            }
                   8432:            if ($refused) {
                   8433:                &logthis('Refused custom assignrole: '.
                   8434:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8435:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8436:                return 'refused';
                   8437:            }
1.104     www      8438:         }
1.21      www      8439:         $mrole='cr';
1.678     raeburn  8440:     } elsif ($role =~ /^gr\//) {
                   8441:         my $cwogrp=$url;
1.811     albertel 8442:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8443:         unless (&allowed('mdg',$cwogrp)) {
                   8444:             &logthis('Refused group assignrole: '.
                   8445:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8446:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8447:             return 'refused';
                   8448:         }
                   8449:         $mrole='gr';
1.21      www      8450:     } else {
1.82      www      8451:         my $cwosec=$url;
1.811     albertel 8452:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8453:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8454:             my $refused;
                   8455:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8456:                 if (!(&allowed('c'.$role,$url))) {
                   8457:                     $refused = 1;
                   8458:                 }
                   8459:             } else {
                   8460:                 $refused = 1;
                   8461:             }
1.947     raeburn  8462:             if ($refused) {
1.1045    raeburn  8463:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8464:                 if (!$selfenroll && $context eq 'course') {
                   8465:                     my %crsenv;
                   8466:                     if ($role eq 'cc' || $role eq 'co') {
                   8467:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8468:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8469:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8470:                                 if ($crsenv{'internal.courseowner'} eq 
                   8471:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8472:                                     $refused = '';
                   8473:                                 }
                   8474:                             }
                   8475:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8476:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8477:                                 if ($crsenv{'internal.courseowner'} eq 
                   8478:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8479:                                     $refused = '';
                   8480:                                 }
                   8481:                             }
                   8482:                         }
                   8483:                     }
                   8484:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8485:                     $refused = '';
1.1017    raeburn  8486:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8487:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8488:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8489:                         my $wrongcc;
                   8490:                         if ($cnum =~ /^$match_community$/) {
                   8491:                             $wrongcc = 1 if ($role eq 'cc');
                   8492:                         } else {
                   8493:                             $wrongcc = 1 if ($role eq 'co');
                   8494:                         }
                   8495:                         unless ($wrongcc) {
                   8496:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8497:                             if ($crsenv{'internal.courseowner'} eq 
                   8498:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8499:                                 $refused = '';
                   8500:                             }
1.1017    raeburn  8501:                         }
                   8502:                     }
1.1183    raeburn  8503:                 } elsif ($context eq 'requestauthor') {
                   8504:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8505:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8506:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8507:                             $refused = '';
                   8508:                         } else {
                   8509:                             my %domdefaults = &get_domain_defaults($udom);
                   8510:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   8511:                                 my $checkbystatus;
                   8512:                                 if ($env{'user.adv'}) { 
                   8513:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   8514:                                     if ($disposition eq 'automatic') {
                   8515:                                         $refused = '';
                   8516:                                     } elsif ($disposition eq '') {
                   8517:                                         $checkbystatus = 1;
                   8518:                                     } 
                   8519:                                 } else {
                   8520:                                     $checkbystatus = 1;
                   8521:                                 }
                   8522:                                 if ($checkbystatus) {
                   8523:                                     if ($env{'environment.inststatus'}) {
                   8524:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   8525:                                         foreach my $type (@inststatuses) {
                   8526:                                             if (($type ne '') &&
                   8527:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   8528:                                                 $refused = '';
                   8529:                                             }
                   8530:                                         }
                   8531:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   8532:                                         $refused = '';
                   8533:                                     }
                   8534:                                 }
                   8535:                             }
                   8536:                         }
                   8537:                     }
1.1017    raeburn  8538:                 }
                   8539:                 if ($refused) {
1.947     raeburn  8540:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   8541:                              ' '.$role.' '.$end.' '.$start.' by '.
                   8542: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   8543:                     return 'refused';
                   8544:                 }
1.932     raeburn  8545:             }
1.1131    raeburn  8546:         } elsif ($role eq 'au') {
                   8547:             if ($url ne '/'.$udom.'/') {
                   8548:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   8549:                          ' to assign author role for '.$uname.':'.$udom.
                   8550:                          ' in domain: '.$url.' refused (wrong domain).');
                   8551:                 return 'refused';
                   8552:             }
1.104     www      8553:         }
1.21      www      8554:         $mrole=$role;
                   8555:     }
1.620     albertel 8556:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      8557:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      8558:     if ($end) { $command.='_'.$end; }
1.21      www      8559:     if ($start) {
                   8560: 	if ($end) { 
1.81      www      8561:            $command.='_'.$start; 
1.21      www      8562:         } else {
1.81      www      8563:            $command.='_0_'.$start;
1.21      www      8564:         }
                   8565:     }
1.739     raeburn  8566:     my $origstart = $start;
                   8567:     my $origend = $end;
1.957     raeburn  8568:     my $delflag;
1.357     www      8569: # actually delete
                   8570:     if ($deleteflag) {
1.373     www      8571: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      8572: # modify command to delete the role
1.620     albertel 8573:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      8574:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 8575: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      8576: # set start and finish to negative values for userrolelog
                   8577:            $start=-1;
                   8578:            $end=-1;
1.957     raeburn  8579:            $delflag = 1;
1.357     www      8580:         }
                   8581:     }
                   8582: # send command
1.349     www      8583:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      8584: # log new user role if status is ok
1.349     www      8585:     if ($answer eq 'ok') {
1.663     raeburn  8586: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  8587:         if (($role eq 'cc') || ($role eq 'in') ||
                   8588:             ($role eq 'ep') || ($role eq 'ad') ||
                   8589:             ($role eq 'ta') || ($role eq 'st') ||
                   8590:             ($role=~/^cr/) || ($role eq 'gr') ||
                   8591:             ($role eq 'co')) {
1.1200    raeburn  8592: # for course roles, perform group memberships changes triggered by role change.
                   8593:             unless ($role =~ /^gr/) {
                   8594:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   8595:                                                  $origstart,$selfenroll,$context);
                   8596:             }
1.1184    raeburn  8597:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8598:                            $selfenroll,$context);
                   8599:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
                   8600:                  ($role eq 'au') || ($role eq 'dc')) {
                   8601:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8602:                            $context);
                   8603:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   8604:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   8605:                              $context); 
                   8606:         }
1.1053    raeburn  8607:         if ($role eq 'cc') {
                   8608:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   8609:         }
1.349     www      8610:     }
                   8611:     return $answer;
1.169     harris41 8612: }
                   8613: 
1.1053    raeburn  8614: sub autoupdate_coowners {
                   8615:     my ($url,$end,$start,$uname,$udom) = @_;
                   8616:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   8617:     if (($cdom ne '') && ($cnum ne '')) {
                   8618:         my $now = time;
                   8619:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   8620:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   8621:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   8622:             my $instcode = $coursehash{'internal.coursecode'};
                   8623:             if ($instcode ne '') {
1.1056    raeburn  8624:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   8625:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  8626:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  8627:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   8628:                         if ($result eq 'valid') {
                   8629:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  8630:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8631:                                     push(@newcoowners,$coowner);
                   8632:                                 }
                   8633:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   8634:                                     push(@newcoowners,$uname.':'.$udom);
                   8635:                                 }
                   8636:                                 @newcoowners = sort(@newcoowners);
                   8637:                             } else {
                   8638:                                 push(@newcoowners,$uname.':'.$udom);
                   8639:                             }
                   8640:                         } else {
                   8641:                             if ($coursehash{'internal.co-owners'}) {
                   8642:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   8643:                                     unless ($coowner eq $uname.':'.$udom) {
                   8644:                                         push(@newcoowners,$coowner);
                   8645:                                     }
                   8646:                                 }
                   8647:                                 unless (@newcoowners > 0) {
                   8648:                                     $delcoowners = 1;
                   8649:                                     $coowners = '';
                   8650:                                 }
                   8651:                             }
                   8652:                         }
                   8653:                         if (@newcoowners || $delcoowners) {
                   8654:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   8655:                                             $delcoowners,@newcoowners);
                   8656:                         }
                   8657:                     }
                   8658:                 }
                   8659:             }
                   8660:         }
                   8661:     }
                   8662: }
                   8663: 
                   8664: sub store_coowners {
                   8665:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   8666:     my $cid = $cdom.'_'.$cnum;
                   8667:     my ($coowners,$delresult,$putresult);
                   8668:     if (@newcoowners) {
                   8669:         $coowners = join(',',@newcoowners);
                   8670:         my %coownershash = (
                   8671:                             'internal.co-owners' => $coowners,
                   8672:                            );
                   8673:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   8674:         if ($putresult eq 'ok') {
                   8675:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   8676:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   8677:             }
                   8678:         }
                   8679:     }
                   8680:     if ($delcoowners) {
                   8681:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   8682:         if ($delresult eq 'ok') {
                   8683:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   8684:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   8685:             }
                   8686:         }
                   8687:     }
                   8688:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   8689:         my %crsinfo =
                   8690:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   8691:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   8692:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   8693:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   8694:         }
                   8695:     }
                   8696: }
                   8697: 
1.169     harris41 8698: # -------------------------------------------------- Modify user authentication
1.197     www      8699: # Overrides without validation
                   8700: 
1.169     harris41 8701: sub modifyuserauth {
                   8702:     my ($udom,$uname,$umode,$upass)=@_;
                   8703:     my $uhome=&homeserver($uname,$udom);
1.197     www      8704:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   8705:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 8706:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8707:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 8708:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   8709: 		     &escape($upass),$uhome);
1.620     albertel 8710:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      8711:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   8712:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   8713:     &log($udom,,$uname,$uhome,
1.620     albertel 8714:         'Authentication changed by '.$env{'user.domain'}.', '.
                   8715:                                      $env{'user.name'}.', '.$umode.
1.197     www      8716:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 8717:     unless ($reply eq 'ok') {
1.197     www      8718:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 8719: 	return 'error: '.$reply;
                   8720:     }   
1.170     harris41 8721:     return 'ok';
1.80      www      8722: }
                   8723: 
1.81      www      8724: # --------------------------------------------------------------- Modify a user
1.80      www      8725: 
1.81      www      8726: sub modifyuser {
1.206     matthew  8727:     my ($udom,    $uname, $uid,
                   8728:         $umode,   $upass, $first,
                   8729:         $middle,  $last,  $gene,
1.1058    raeburn  8730:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 8731:     $udom= &LONCAPA::clean_domain($udom);
                   8732:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  8733:     my $showcandelete = 'none';
                   8734:     if (ref($candelete) eq 'ARRAY') {
                   8735:         if (@{$candelete} > 0) {
                   8736:             $showcandelete = join(', ',@{$candelete});
                   8737:         }
                   8738:     }
1.81      www      8739:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      8740:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  8741: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  8742:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   8743:                                      ' desiredhome not specified'). 
1.620     albertel 8744:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   8745:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 8746:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  8747:     my $newuser;
                   8748:     if ($uhome eq 'no_host') {
                   8749:         $newuser = 1;
                   8750:     }
1.80      www      8751: # ----------------------------------------------------------------- Create User
1.406     albertel 8752:     if (($uhome eq 'no_host') && 
                   8753: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      8754:         my $unhome='';
1.844     albertel 8755:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  8756:             $unhome = $desiredhome;
1.620     albertel 8757: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   8758: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  8759:         } else { # load balancing routine for determining $unhome
1.81      www      8760:             my $loadm=10000000;
1.841     albertel 8761: 	    my %servers = &get_servers($udom,'library');
                   8762: 	    foreach my $tryserver (keys(%servers)) {
                   8763: 		my $answer=reply('load',$tryserver);
                   8764: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   8765: 		    $loadm=$answer;
                   8766: 		    $unhome=$tryserver;
                   8767: 		}
1.80      www      8768: 	    }
                   8769:         }
                   8770:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  8771: 	    return 'error: unable to find a home server for '.$uname.
                   8772:                    ' in domain '.$udom;
1.80      www      8773:         }
                   8774:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   8775:                          &escape($upass),$unhome);
                   8776: 	unless ($reply eq 'ok') {
                   8777:             return 'error: '.$reply;
                   8778:         }   
1.230     stredwic 8779:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      8780:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  8781: 	    return 'error: unable verify users home machine.';
1.80      www      8782:         }
1.209     matthew  8783:     }   # End of creation of new user
1.80      www      8784: # ---------------------------------------------------------------------- Add ID
                   8785:     if ($uid) {
                   8786:        $uid=~tr/A-Z/a-z/;
                   8787:        my %uidhash=&idrget($udom,$uname);
1.196     www      8788:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   8789:          && (!$forceid)) {
1.80      www      8790: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  8791: 	      return 'error: user id "'.$uid.'" does not match '.
                   8792:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      8793:           }
                   8794:        } else {
                   8795: 	  &idput($udom,($uname => $uid));
                   8796:        }
                   8797:     }
                   8798: # -------------------------------------------------------------- Add names, etc
1.313     matthew  8799:     my @tmp=&get('environment',
1.899     raeburn  8800: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  8801:                     'permanentemail','inststatus'],
1.134     albertel 8802: 		   $udom,$uname);
1.1075    raeburn  8803:     my (%names,%oldnames);
1.313     matthew  8804:     if ($tmp[0] =~ m/^error:.*/) { 
                   8805:         %names=(); 
                   8806:     } else {
                   8807:         %names = @tmp;
1.1075    raeburn  8808:         %oldnames = %names;
1.313     matthew  8809:     }
1.388     www      8810: #
1.1058    raeburn  8811: # If name, email and/or uid are blank (e.g., because an uploaded file
                   8812: # of users did not contain them), do not overwrite existing values
                   8813: # unless field is in $candelete array ref.  
                   8814: #
                   8815: 
                   8816:     my @fields = ('firstname','middlename','lastname','generation',
                   8817:                   'permanentemail','id');
                   8818:     my %newvalues;
                   8819:     if (ref($candelete) eq 'ARRAY') {
                   8820:         foreach my $field (@fields) {
                   8821:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   8822:                 if ($field eq 'firstname') {
                   8823:                     $names{$field} = $first;
                   8824:                 } elsif ($field eq 'middlename') {
                   8825:                     $names{$field} = $middle;
                   8826:                 } elsif ($field eq 'lastname') {
                   8827:                     $names{$field} = $last;
                   8828:                 } elsif ($field eq 'generation') { 
                   8829:                     $names{$field} = $gene;
                   8830:                 } elsif ($field eq 'permanentemail') {
                   8831:                     $names{$field} = $email;
                   8832:                 } elsif ($field eq 'id') {
                   8833:                     $names{$field}  = $uid;
                   8834:                 }
                   8835:             }
                   8836:         }
                   8837:     }
1.388     www      8838:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  8839:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      8840:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  8841:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      8842:     if ($email) {
                   8843:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  8844:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      8845:     }
1.899     raeburn  8846:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  8847:     if (defined($inststatus)) {
                   8848:         $names{'inststatus'} = '';
                   8849:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   8850:         if (ref($usertypes) eq 'HASH') {
                   8851:             my @okstatuses; 
                   8852:             foreach my $item (split(/:/,$inststatus)) {
                   8853:                 if (defined($usertypes->{$item})) {
                   8854:                     push(@okstatuses,$item);  
                   8855:                 }
                   8856:             }
                   8857:             if (@okstatuses) {
                   8858:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   8859:             }
                   8860:         }
                   8861:     }
1.1075    raeburn  8862:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  8863:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  8864:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  8865:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   8866:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   8867:     } else {
                   8868:         $logmsg .= ' during self creation';
                   8869:     }
1.1075    raeburn  8870:     my $changed;
                   8871:     if ($newuser) {
                   8872:         $changed = 1;
                   8873:     } else {
                   8874:         foreach my $field (@fields) {
                   8875:             if ($names{$field} ne $oldnames{$field}) {
                   8876:                 $changed = 1;
                   8877:                 last;
                   8878:             }
                   8879:         }
                   8880:     }
                   8881:     unless ($changed) {
                   8882:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   8883:         &logthis($logmsg);
                   8884:         return 'ok';
                   8885:     }
                   8886:     my $reply = &put('environment', \%names, $udom,$uname);
                   8887:     if ($reply ne 'ok') { 
                   8888:         return 'error: '.$reply;
                   8889:     }
1.1087    raeburn  8890:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   8891:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   8892:     }
1.1075    raeburn  8893:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   8894:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   8895:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  8896:     &logthis($logmsg);
1.134     albertel 8897:     return 'ok';
1.80      www      8898: }
                   8899: 
1.81      www      8900: # -------------------------------------------------------------- Modify student
1.80      www      8901: 
1.81      www      8902: sub modifystudent {
                   8903:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  8904:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1216    raeburn  8905:         $selfenroll,$context,$inststatus,$credits)=@_;
1.455     albertel 8906:     if (!$cid) {
1.620     albertel 8907: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8908: 	    return 'not_in_class';
                   8909: 	}
1.80      www      8910:     }
                   8911: # --------------------------------------------------------------- Make the user
1.81      www      8912:     my $reply=&modifyuser
1.209     matthew  8913: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  8914:          $desiredhome,$email,$inststatus);
1.80      www      8915:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  8916:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  8917:     # student's environment
1.297     matthew  8918:     $uid = undef if (!$forceid);
1.455     albertel 8919:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  8920:                                         $gene,$usec,$end,$start,$type,$locktype,
                   8921:                                         $cid,$selfenroll,$context,$credits);
1.297     matthew  8922:     return $reply;
                   8923: }
                   8924: 
                   8925: sub modify_student_enrollment {
1.1216    raeburn  8926:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
                   8927:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
1.455     albertel 8928:     my ($cdom,$cnum,$chome);
                   8929:     if (!$cid) {
1.620     albertel 8930: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 8931: 	    return 'not_in_class';
                   8932: 	}
1.620     albertel 8933: 	$cdom=$env{'course.'.$cid.'.domain'};
                   8934: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 8935:     } else {
                   8936: 	($cdom,$cnum)=split(/_/,$cid);
                   8937:     }
1.620     albertel 8938:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 8939:     if (!$chome) {
1.457     raeburn  8940: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  8941:     }
1.455     albertel 8942:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  8943:     # Make sure the user exists
1.81      www      8944:     my $uhome=&homeserver($uname,$udom);
                   8945:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8946: 	return 'error: no such user';
                   8947:     }
1.297     matthew  8948:     # Get student data if we were not given enough information
                   8949:     if (!defined($first)  || $first  eq '' || 
                   8950:         !defined($last)   || $last   eq '' || 
                   8951:         !defined($uid)    || $uid    eq '' || 
                   8952:         !defined($middle) || $middle eq '' || 
                   8953:         !defined($gene)   || $gene   eq '') {
1.294     matthew  8954:         # They did not supply us with enough data to enroll the student, so
                   8955:         # we need to pick up more information.
1.297     matthew  8956:         my %tmp = &get('environment',
1.294     matthew  8957:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  8958:                        ,$udom,$uname);
                   8959: 
1.800     albertel 8960:         #foreach my $key (keys(%tmp)) {
                   8961:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 8962:         #}
1.294     matthew  8963:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   8964:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   8965:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  8966:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  8967:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   8968:     }
1.556     albertel 8969:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  8970:     my $user = "$uname:$udom";
                   8971:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 8972:     my $reply=cput('classlist',
1.1148    raeburn  8973: 		   {$user => 
1.1216    raeburn  8974: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
1.487     albertel 8975: 		   $cdom,$cnum);
1.1148    raeburn  8976:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   8977:         &devalidate_getsection_cache($udom,$uname,$cid);
                   8978:     } else { 
1.81      www      8979: 	return 'error: '.$reply;
                   8980:     }
1.297     matthew  8981:     # Add student role to user
1.83      www      8982:     my $uurl='/'.$cid;
1.81      www      8983:     $uurl=~s/\_/\//g;
                   8984:     if ($usec) {
                   8985: 	$uurl.='/'.$usec;
                   8986:     }
1.1148    raeburn  8987:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   8988:                              $selfenroll,$context);
                   8989:     if ($result ne 'ok') {
                   8990:         if ($old_entry{$user} ne '') {
                   8991:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   8992:         } else {
                   8993:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   8994:         }
                   8995:     }
                   8996:     return $result; 
1.21      www      8997: }
                   8998: 
1.556     albertel 8999: sub format_name {
                   9000:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9001:     my $name;
                   9002:     if ($first ne 'lastname') {
                   9003: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9004:     } else {
                   9005: 	if ($lastname=~/\S/) {
                   9006: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9007: 	    $name=~s/\s+,/,/;
                   9008: 	} else {
                   9009: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9010: 	}
                   9011:     }
                   9012:     $name=~s/^\s+//;
                   9013:     $name=~s/\s+$//;
                   9014:     $name=~s/\s+/ /g;
                   9015:     return $name;
                   9016: }
                   9017: 
1.84      www      9018: # ------------------------------------------------- Write to course preferences
                   9019: 
                   9020: sub writecoursepref {
                   9021:     my ($courseid,%prefs)=@_;
                   9022:     $courseid=~s/^\///;
                   9023:     $courseid=~s/\_/\//g;
                   9024:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9025:     my $chome=homeserver($cnum,$cdomain);
                   9026:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9027: 	return 'error: no such course';
                   9028:     }
                   9029:     my $cstring='';
1.800     albertel 9030:     foreach my $pref (keys(%prefs)) {
                   9031: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9032:     }
1.84      www      9033:     $cstring=~s/\&$//;
                   9034:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9035: }
                   9036: 
                   9037: # ---------------------------------------------------------- Make/modify course
                   9038: 
                   9039: sub createcourse {
1.741     raeburn  9040:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9041:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9042:     $url=&declutter($url);
                   9043:     my $cid='';
1.1028    raeburn  9044:     if ($context eq 'requestcourses') {
                   9045:         my $can_create = 0;
                   9046:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9047:         if ($udom eq $ownerdom) {
                   9048:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9049:                                   $context)) {
                   9050:                 $can_create = 1;
                   9051:             }
                   9052:         } else {
                   9053:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9054:                                            $category);
                   9055:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9056:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9057:                 if (@curr > 0) {
                   9058:                     my @options = qw(approval validate autolimit);
                   9059:                     my $optregex = join('|',@options);
                   9060:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9061:                         $can_create = 1;
                   9062:                     }
                   9063:                 }
                   9064:             }
                   9065:         }
                   9066:         if ($can_create) {
                   9067:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9068:                 unless (&allowed('ccc',$udom)) {
                   9069:                     return 'refused'; 
                   9070:                 }
1.1017    raeburn  9071:             }
                   9072:         } else {
                   9073:             return 'refused';
                   9074:         }
1.1028    raeburn  9075:     } elsif (!&allowed('ccc',$udom)) {
                   9076:         return 'refused';
1.84      www      9077:     }
1.1011    raeburn  9078: # --------------------------------------------------------------- Get Unique ID
                   9079:     my $uname;
                   9080:     if ($cnum =~ /^$match_courseid$/) {
                   9081:         my $chome=&homeserver($cnum,$udom,'true');
                   9082:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9083:             $uname = $cnum;
                   9084:         } else {
1.1038    raeburn  9085:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9086:         }
                   9087:     } else {
1.1038    raeburn  9088:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9089:     }
                   9090:     return $uname if ($uname =~ /^error/);
                   9091: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9092:     if (!defined($course_server)) {
                   9093:         if (defined(&domain($udom,'primary'))) {
                   9094:             $course_server = &domain($udom,'primary');
                   9095:         } else {
                   9096:             $course_server = $env{'user.home'}; 
                   9097:         }
                   9098:     }
                   9099:     my %host_servers =
                   9100:         &Apache::lonnet::get_servers($udom,'library');
                   9101:     unless ($host_servers{$course_server}) {
                   9102:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9103:     }
1.84      www      9104: # ------------------------------------------------------------- Make the course
                   9105:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9106:                       $course_server);
1.84      www      9107:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9108:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9109:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9110: 	return 'error: no such course';
                   9111:     }
1.271     www      9112: # ----------------------------------------------------------------- Course made
1.516     raeburn  9113: # log existence
1.1029    raeburn  9114:     my $now = time;
1.918     raeburn  9115:     my $newcourse = {
                   9116:                     $udom.'_'.$uname => {
1.921     raeburn  9117:                                      description => $description,
                   9118:                                      inst_code   => $inst_code,
                   9119:                                      owner       => $course_owner,
                   9120:                                      type        => $crstype,
1.1029    raeburn  9121:                                      creator     => $env{'user.name'}.':'.
                   9122:                                                     $env{'user.domain'},
                   9123:                                      created     => $now,
                   9124:                                      context     => $context,
1.918     raeburn  9125:                                                 },
                   9126:                     };
1.921     raeburn  9127:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9128: # set toplevel url
1.271     www      9129:     my $topurl=$url;
                   9130:     unless ($nonstandard) {
                   9131: # ------------------------------------------ For standard courses, make top url
                   9132:         my $mapurl=&clutter($url);
1.278     www      9133:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9134:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9135: <map>
                   9136: <resource id="1" type="start"></resource>
                   9137: <resource id="2" src="$mapurl"></resource>
                   9138: <resource id="3" type="finish"></resource>
                   9139: <link index="1" from="1" to="2"></link>
                   9140: <link index="2" from="2" to="3"></link>
                   9141: </map>
                   9142: ENDINITMAP
                   9143:         $topurl=&declutter(
1.638     albertel 9144:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9145:                           );
                   9146:     }
                   9147: # ----------------------------------------------------------- Write preferences
1.84      www      9148:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9149:                      ('description'              => $description,
                   9150:                       'url'                      => $topurl,
                   9151:                       'internal.creator'         => $env{'user.name'}.':'.
                   9152:                                                     $env{'user.domain'},
                   9153:                       'internal.created'         => $now,
                   9154:                       'internal.creationcontext' => $context)
                   9155:                     );
1.84      www      9156:     return '/'.$udom.'/'.$uname;
                   9157: }
                   9158: 
1.1011    raeburn  9159: # ------------------------------------------------------------------- Create ID
                   9160: sub generate_coursenum {
1.1038    raeburn  9161:     my ($udom,$crstype) = @_;
1.1011    raeburn  9162:     my $domdesc = &domain($udom);
                   9163:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9164:     my $first;
                   9165:     if ($crstype eq 'Community') {
                   9166:         $first = '0';
                   9167:     } else {
                   9168:         $first = int(1+rand(9)); 
                   9169:     } 
                   9170:     my $uname=$first.
1.1011    raeburn  9171:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9172:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9173:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9174: # ----------------------------------------------- Make sure that does not exist
                   9175:     my $uhome=&homeserver($uname,$udom,'true');
                   9176:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9177:         if ($crstype eq 'Community') {
                   9178:             $first = '0';
                   9179:         } else {
                   9180:             $first = int(1+rand(9));
                   9181:         }
                   9182:         $uname=$first.
1.1011    raeburn  9183:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9184:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9185:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9186:         $uhome=&homeserver($uname,$udom,'true');
                   9187:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9188:             return 'error: unable to generate unique course-ID';
                   9189:         }
                   9190:     }
                   9191:     return $uname;
                   9192: }
                   9193: 
1.813     albertel 9194: sub is_course {
1.1167    droeschl 9195:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9196:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9197: 
                   9198:     return unless $cdom and $cnum;
                   9199: 
                   9200:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9201:         '.');
                   9202: 
1.1219    raeburn  9203:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9204:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9205: }
                   9206: 
1.1015    raeburn  9207: sub store_userdata {
                   9208:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9209:     my $result;
1.1016    raeburn  9210:     if ($datakey ne '') {
1.1013    raeburn  9211:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9212:             if ($udom eq '' || $uname eq '') {
                   9213:                 $udom = $env{'user.domain'};
                   9214:                 $uname = $env{'user.name'};
                   9215:             }
                   9216:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9217:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9218:                 $result = 'error: no_host';
                   9219:             } else {
                   9220:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9221:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9222: 
                   9223:                 my $namevalue='';
                   9224:                 foreach my $key (keys(%{$storehash})) {
                   9225:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9226:                 }
                   9227:                 $namevalue=~s/\&$//;
1.1224    raeburn  9228:                 unless ($namespace eq 'courserequests') {
                   9229:                     $datakey = &escape($datakey);
                   9230:                 }
1.1105    raeburn  9231:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9232:                                   $namevalue,$uhome);
1.1013    raeburn  9233:             }
                   9234:         } else {
                   9235:             $result = 'error: data to store was not a hash reference'; 
                   9236:         }
                   9237:     } else {
                   9238:         $result= 'error: invalid requestkey'; 
                   9239:     }
                   9240:     return $result;
                   9241: }
                   9242: 
1.21      www      9243: # ---------------------------------------------------------- Assign Custom Role
                   9244: 
                   9245: sub assigncustomrole {
1.957     raeburn  9246:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9247:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9248:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9249: }
                   9250: 
                   9251: # ----------------------------------------------------------------- Revoke Role
                   9252: 
                   9253: sub revokerole {
1.957     raeburn  9254:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9255:     my $now=time;
1.965     raeburn  9256:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9257: }
                   9258: 
                   9259: # ---------------------------------------------------------- Revoke Custom Role
                   9260: 
                   9261: sub revokecustomrole {
1.957     raeburn  9262:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9263:     my $now=time;
1.357     www      9264:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9265:            $deleteflag,$selfenroll,$context);
1.17      www      9266: }
                   9267: 
1.533     banghart 9268: # ------------------------------------------------------------ Disk usage
1.535     albertel 9269: sub diskusage {
1.955     raeburn  9270:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9271:     $directorypath =~ s/\/$//;
                   9272:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9273:                        .&escape($getpropath).':'.&escape($uname).':'
                   9274:                        .&escape($udom),homeserver($uname,$udom));
                   9275:     if ($listing eq 'unknown_cmd') {
                   9276:         if ($getpropath) {
                   9277:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9278:         }
                   9279:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9280:     }
1.514     albertel 9281:     return $listing;
1.512     banghart 9282: }
                   9283: 
1.566     banghart 9284: sub is_locked {
1.1096    raeburn  9285:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9286:     my @check;
                   9287:     my $is_locked;
1.1093    raeburn  9288:     push (@check,$file_name);
1.613     albertel 9289:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9290: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9291:     my ($tmp)=keys(%locked);
                   9292:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9293:     
1.566     banghart 9294:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9295:         $is_locked = 'false';
                   9296:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9297:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9298:                $is_locked = 'true';
1.1096    raeburn  9299:                if (ref($which) eq 'ARRAY') {
                   9300:                    push(@{$which},$entry);
                   9301:                } else {
                   9302:                    last;
                   9303:                }
1.745     raeburn  9304:            }
                   9305:        }
1.566     banghart 9306:     } else {
                   9307:         $is_locked = 'false';
                   9308:     }
1.1093    raeburn  9309:     return $is_locked;
1.566     banghart 9310: }
                   9311: 
1.759     albertel 9312: sub declutter_portfile {
                   9313:     my ($file) = @_;
1.833     albertel 9314:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9315:     return $file;
                   9316: }
                   9317: 
1.559     banghart 9318: # ------------------------------------------------------------- Mark as Read Only
                   9319: 
                   9320: sub mark_as_readonly {
                   9321:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9322:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9323:     my ($tmp)=keys(%current_permissions);
                   9324:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9325:     foreach my $file (@{$files}) {
1.759     albertel 9326: 	$file = &declutter_portfile($file);
1.561     banghart 9327:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9328:     }
1.613     albertel 9329:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9330:     return;
                   9331: }
                   9332: 
1.572     banghart 9333: # ------------------------------------------------------------Save Selected Files
                   9334: 
                   9335: sub save_selected_files {
                   9336:     my ($user, $path, @files) = @_;
                   9337:     my $filename = $user."savedfiles";
1.573     banghart 9338:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9339:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9340:     foreach my $file (@files) {
1.620     albertel 9341:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9342:     }
                   9343:     foreach my $file (@other_files) {
1.574     banghart 9344:         print (OUT $file."\n");
1.572     banghart 9345:     }
1.574     banghart 9346:     close (OUT);
1.572     banghart 9347:     return 'ok';
                   9348: }
                   9349: 
1.574     banghart 9350: sub clear_selected_files {
                   9351:     my ($user) = @_;
                   9352:     my $filename = $user."savedfiles";
1.1117    foxr     9353:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9354:     print (OUT undef);
                   9355:     close (OUT);
                   9356:     return ("ok");    
                   9357: }
                   9358: 
1.572     banghart 9359: sub files_in_path {
                   9360:     my ($user, $path) = @_;
                   9361:     my $filename = $user."savedfiles";
                   9362:     my %return_files;
1.1117    foxr     9363:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9364:     while (my $line_in = <IN>) {
1.574     banghart 9365:         chomp ($line_in);
                   9366:         my @paths_and_file = split (m!/!, $line_in);
                   9367:         my $file_part = pop (@paths_and_file);
                   9368:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9369:         $path_part.='/';
                   9370:         my $path_and_file = $path_part.$file_part;
                   9371:         if ($path_part eq $path) {
                   9372:             $return_files{$file_part}= 'selected';
                   9373:         }
                   9374:     }
1.574     banghart 9375:     close (IN);
                   9376:     return (\%return_files);
1.572     banghart 9377: }
                   9378: 
                   9379: # called in portfolio select mode, to show files selected NOT in current directory
                   9380: sub files_not_in_path {
                   9381:     my ($user, $path) = @_;
                   9382:     my $filename = $user."savedfiles";
                   9383:     my @return_files;
                   9384:     my $path_part;
1.1117    foxr     9385:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9386:     while (my $line = <IN>) {
1.572     banghart 9387:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9388:         my @paths_and_file = split(m|/|, $line);
                   9389:         my $file_part = pop(@paths_and_file);
                   9390:         chomp($file_part);
                   9391:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9392:         $path_part .= '/';
                   9393:         my $path_and_file = $path_part.$file_part;
                   9394:         if ($path_part ne $path) {
1.800     albertel 9395:             push(@return_files, ($path_and_file));
1.572     banghart 9396:         }
                   9397:     }
1.800     albertel 9398:     close(OUT);
1.574     banghart 9399:     return (@return_files);
1.572     banghart 9400: }
                   9401: 
1.1273    raeburn  9402: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   9403:  
                   9404: sub portfiles_versioning {
                   9405:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   9406:     my $portfolio_root = '/userfiles/portfolio';
                   9407:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   9408:     foreach my $file (@{$portfiles}) {
                   9409:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   9410:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   9411:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   9412:         my $getpropath = 1;
                   9413:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   9414:                                              $stu_name,$getpropath);
                   9415:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   9416:         my $new_answer = 
                   9417:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   9418:         if ($new_answer ne 'problem getting file') {
                   9419:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   9420:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   9421:                               [$symb,$env{'request.course.id'},'graded']);
                   9422:         }
                   9423:     }
                   9424: }
                   9425: 
                   9426: sub get_next_version {
                   9427:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   9428:     my $version;
                   9429:     if (ref($dir_list) eq 'ARRAY') {
                   9430:         foreach my $row (@{$dir_list}) {
                   9431:             my ($file) = split(/\&/,$row,2);
                   9432:             my ($file_name,$file_version,$file_ext) =
                   9433:                 &file_name_version_ext($file);
                   9434:             if (($file_name eq $answer_name) &&
                   9435:                 ($file_ext eq $answer_ext)) {
                   9436:                      # gets here if filename and extension match,
                   9437:                      # regardless of version
                   9438:                 if ($file_version ne '') {
                   9439:                     # a versioned file is found  so save it for later
                   9440:                     if ($file_version > $version) {
                   9441:                         $version = $file_version;
                   9442:                     }
                   9443:                 }
                   9444:             }
                   9445:         }
                   9446:     }
                   9447:     $version ++;
                   9448:     return($version);
                   9449: }
                   9450: 
                   9451: sub version_selected_portfile {
                   9452:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   9453:     my ($answer_name,$answer_ver,$answer_ext) =
                   9454:         &file_name_version_ext($file_name);
                   9455:     my $new_answer;
                   9456:     $env{'form.copy'} =
                   9457:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   9458:     if($env{'form.copy'} eq '-1') {
                   9459:         $new_answer = 'problem getting file';
                   9460:     } else {
                   9461:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   9462:         my $copy_result = 
                   9463:             &finishuserfileupload($stu_name,$domain,'copy',
                   9464:                                   '/portfolio'.$directory.$new_answer);
                   9465:     }
                   9466:     undef($env{'form.copy'});
                   9467:     return ($new_answer);
                   9468: }
                   9469: 
                   9470: sub file_name_version_ext {
                   9471:     my ($file)=@_;
                   9472:     my @file_parts = split(/\./, $file);
                   9473:     my ($name,$version,$ext);
                   9474:     if (@file_parts > 1) {
                   9475:         $ext=pop(@file_parts);
                   9476:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   9477:             $version=pop(@file_parts);
                   9478:         }
                   9479:         $name=join('.',@file_parts);
                   9480:     } else {
                   9481:         $name=join('.',@file_parts);
                   9482:     }
                   9483:     return($name,$version,$ext);
                   9484: }
                   9485: 
1.745     raeburn  9486: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9487: 
1.745     raeburn  9488: sub get_portfile_permissions {
                   9489:     my ($domain,$user) = @_;
1.613     albertel 9490:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9491:     my ($tmp)=keys(%current_permissions);
                   9492:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9493:     return \%current_permissions;
                   9494: }
                   9495: 
                   9496: #---------------------------------------------Get portfolio file access controls
                   9497: 
1.749     raeburn  9498: sub get_access_controls {
1.745     raeburn  9499:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9500:     my %access;
                   9501:     my $real_file = $file;
                   9502:     $file =~ s/\.meta$//;
1.745     raeburn  9503:     if (defined($file)) {
1.749     raeburn  9504:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9505:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9506:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9507:             }
                   9508:         }
1.745     raeburn  9509:     } else {
1.749     raeburn  9510:         foreach my $key (keys(%{$current_permissions})) {
                   9511:             if ($key =~ /\0accesscontrol$/) {
                   9512:                 if (defined($group)) {
                   9513:                     if ($key !~ m-^\Q$group\E/-) {
                   9514:                         next;
                   9515:                     }
                   9516:                 }
                   9517:                 my ($fullpath) = split(/\0/,$key);
                   9518:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   9519:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   9520:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   9521:                     }
                   9522:                 }
                   9523:             }
                   9524:         }
                   9525:     }
                   9526:     return %access;
                   9527: }
                   9528: 
                   9529: sub modify_access_controls {
                   9530:     my ($file_name,$changes,$domain,$user)=@_;
                   9531:     my ($outcome,$deloutcome);
                   9532:     my %store_permissions;
                   9533:     my %new_values;
                   9534:     my %new_control;
                   9535:     my %translation;
                   9536:     my @deletions = ();
                   9537:     my $now = time;
                   9538:     if (exists($$changes{'activate'})) {
                   9539:         if (ref($$changes{'activate'}) eq 'HASH') {
                   9540:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   9541:             my $numnew = scalar(@newitems);
                   9542:             for (my $i=0; $i<$numnew; $i++) {
                   9543:                 my $newkey = $newitems[$i];
                   9544:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  9545:                 if ($newkey =~ /^\d+:/) { 
                   9546:                     $newkey =~ s/^(\d+)/$newid/;
                   9547:                     $translation{$1} = $newid;
                   9548:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   9549:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   9550:                     $translation{$1} = $newid;
                   9551:                 }
1.749     raeburn  9552:                 $new_values{$file_name."\0".$newkey} = 
                   9553:                                           $$changes{'activate'}{$newitems[$i]};
                   9554:                 $new_control{$newkey} = $now;
                   9555:             }
                   9556:         }
                   9557:     }
                   9558:     my %todelete;
                   9559:     my %changed_items;
                   9560:     foreach my $action ('delete','update') {
                   9561:         if (exists($$changes{$action})) {
                   9562:             if (ref($$changes{$action}) eq 'HASH') {
                   9563:                 foreach my $key (keys(%{$$changes{$action}})) {
                   9564:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   9565:                     if ($action eq 'delete') { 
                   9566:                         $todelete{$itemnum} = 1;
                   9567:                     } else {
                   9568:                         $changed_items{$itemnum} = $key;
                   9569:                     }
                   9570:                 }
1.745     raeburn  9571:             }
                   9572:         }
1.749     raeburn  9573:     }
                   9574:     # get lock on access controls for file.
                   9575:     my $lockhash = {
                   9576:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   9577:                                                        ':'.$env{'user.domain'},
                   9578:                    }; 
                   9579:     my $tries = 0;
                   9580:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9581:    
1.1288    damieng  9582:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  9583:         $tries ++;
1.1289    damieng  9584:         sleep(0.1);
1.749     raeburn  9585:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   9586:     }
                   9587:     if ($gotlock eq 'ok') {
                   9588:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   9589:         my ($tmp)=keys(%curr_permissions);
                   9590:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   9591:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   9592:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   9593:             if (ref($curr_controls) eq 'HASH') {
                   9594:                 foreach my $control_item (keys(%{$curr_controls})) {
                   9595:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   9596:                     if (defined($todelete{$itemnum})) {
                   9597:                         push(@deletions,$file_name."\0".$control_item);
                   9598:                     } else {
                   9599:                         if (defined($changed_items{$itemnum})) {
                   9600:                             $new_control{$changed_items{$itemnum}} = $now;
                   9601:                             push(@deletions,$file_name."\0".$control_item);
                   9602:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   9603:                         } else {
                   9604:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   9605:                         }
                   9606:                     }
1.745     raeburn  9607:                 }
                   9608:             }
                   9609:         }
1.970     raeburn  9610:         my ($group);
                   9611:         if (&is_course($domain,$user)) {
                   9612:             ($group,my $file) = split(/\//,$file_name,2);
                   9613:         }
1.749     raeburn  9614:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   9615:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   9616:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   9617:         #  remove lock
                   9618:         my @del_lock = ($file_name."\0".'locked_access_records');
                   9619:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  9620:         my $sqlresult =
1.970     raeburn  9621:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  9622:                                     $group);
1.749     raeburn  9623:     } else {
                   9624:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  9625:     }
1.749     raeburn  9626:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  9627: }
                   9628: 
1.827     raeburn  9629: sub make_public_indefinitely {
1.1271    raeburn  9630:     my (@requrl) = @_;
                   9631:     return &automated_portfile_access('public',\@requrl);
                   9632: }
                   9633: 
                   9634: sub automated_portfile_access {
                   9635:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  9636:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   9637:         return 'invalid';
                   9638:     }
1.1271    raeburn  9639:     my %urls;
                   9640:     if (ref($addsref) eq 'ARRAY') {
                   9641:         foreach my $requrl (@{$addsref}) {
                   9642:             if (&is_portfolio_url($requrl)) {
                   9643:                 unless (exists($urls{$requrl})) {
                   9644:                     $urls{$requrl} = 'add';
                   9645:                 }
                   9646:             }
                   9647:         }
                   9648:     }
                   9649:     if (ref($delsref) eq 'ARRAY') {
                   9650:         foreach my $requrl (@{$delsref}) { 
                   9651:             if (&is_portfolio_url($requrl)) {
                   9652:                 unless (exists($urls{$requrl})) {
                   9653:                     $urls{$requrl} = 'delete'; 
                   9654:                 }
                   9655:             }
                   9656:         }
                   9657:     }
                   9658:     unless (keys(%urls)) {
                   9659:         return 'invalid';
                   9660:     }
                   9661:     my $ip;
                   9662:     if ($accesstype eq 'ip') {
                   9663:         if (ref($info) eq 'HASH') {
                   9664:             if ($info->{'ip'} ne '') {
                   9665:                 $ip = $info->{'ip'};
                   9666:             }
                   9667:         }
                   9668:         if ($ip eq '') {
                   9669:             return 'invalid';
                   9670:         }
                   9671:     }
                   9672:     my $errors;
1.827     raeburn  9673:     my $now = time;
1.1271    raeburn  9674:     my %current_perms;
                   9675:     foreach my $requrl (sort(keys(%urls))) {
                   9676:         my $action;
                   9677:         if ($urls{$requrl} eq 'add') {
                   9678:             $action = 'activate';
                   9679:         } else {
                   9680:             $action = 'none';
                   9681:         }
                   9682:         my $aclnum = 0;
1.827     raeburn  9683:         my (undef,$udom,$unum,$file_name,$group) =
                   9684:             &parse_portfolio_url($requrl);
1.1271    raeburn  9685:         unless (exists($current_perms{$unum.':'.$udom})) {
                   9686:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   9687:         }
                   9688:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  9689:                                                    $group,$file_name);
                   9690:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   9691:             my ($num,$scope,$end,$start) = 
                   9692:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  9693:             if ($scope eq $accesstype) {
                   9694:                 if (($start <= $now) && ($end == 0)) {
                   9695:                     if ($accesstype eq 'ip') {
                   9696:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   9697:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   9698:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   9699:                                     if ($urls{$requrl} eq 'add') {
                   9700:                                         $action = 'none';
                   9701:                                         last;
                   9702:                                     } else {
                   9703:                                         $action = 'delete';
                   9704:                                         $aclnum = $num;
                   9705:                                         last;
                   9706:                                     }
                   9707:                                 }
                   9708:                             }
                   9709:                         }
                   9710:                     } elsif ($accesstype eq 'public') {
                   9711:                         if ($urls{$requrl} eq 'add') {
                   9712:                             $action = 'none';
                   9713:                             last;
                   9714:                         } else {
                   9715:                             $action = 'delete';
                   9716:                             $aclnum = $num;
                   9717:                             last;
                   9718:                         }
                   9719:                     }
                   9720:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  9721:                     $action = 'update';
                   9722:                     $aclnum = $num;
1.1271    raeburn  9723:                     last;
1.827     raeburn  9724:                 }
                   9725:             }
                   9726:         }
                   9727:         if ($action eq 'none') {
1.1271    raeburn  9728:             next;
1.827     raeburn  9729:         } else {
                   9730:             my %changes;
                   9731:             my $newend = 0;
                   9732:             my $newstart = $now;
1.1271    raeburn  9733:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  9734:             $changes{$action}{$newkey} = {
1.1271    raeburn  9735:                 type => $accesstype,
1.827     raeburn  9736:                 time => {
                   9737:                     start => $newstart,
                   9738:                     end   => $newend,
                   9739:                 },
                   9740:             };
1.1271    raeburn  9741:             if ($accesstype eq 'ip') {
                   9742:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   9743:             }
1.827     raeburn  9744:             my ($outcome,$deloutcome,$new_values,$translation) =
                   9745:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  9746:             unless ($outcome eq 'ok') {
                   9747:                 $errors .= $outcome.' ';
                   9748:             }
1.827     raeburn  9749:         }
1.1271    raeburn  9750:     }
                   9751:     if ($errors) {
                   9752:         $errors =~ s/\s$//;
                   9753:         return $errors;
1.827     raeburn  9754:     } else {
1.1271    raeburn  9755:         return 'ok';
1.827     raeburn  9756:     }
                   9757: }
                   9758: 
1.745     raeburn  9759: #------------------------------------------------------Get Marked as Read Only
                   9760: 
                   9761: sub get_marked_as_readonly {
                   9762:     my ($domain,$user,$what,$group) = @_;
                   9763:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 9764:     my @readonly_files;
1.629     banghart 9765:     my $cmp1=$what;
                   9766:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  9767:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9768:         if (defined($group)) {
                   9769:             if ($file_name !~ m-^\Q$group\E/-) {
                   9770:                 next;
                   9771:             }
                   9772:         }
1.561     banghart 9773:         if (ref($value) eq "ARRAY"){
                   9774:             foreach my $stored_what (@{$value}) {
1.629     banghart 9775:                 my $cmp2=$stored_what;
1.759     albertel 9776:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  9777:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  9778:                 }
1.629     banghart 9779:                 if ($cmp1 eq $cmp2) {
1.561     banghart 9780:                     push(@readonly_files, $file_name);
1.745     raeburn  9781:                     last;
1.563     banghart 9782:                 } elsif (!defined($what)) {
                   9783:                     push(@readonly_files, $file_name);
1.745     raeburn  9784:                     last;
1.561     banghart 9785:                 }
                   9786:             }
1.745     raeburn  9787:         }
1.561     banghart 9788:     }
                   9789:     return @readonly_files;
                   9790: }
1.577     banghart 9791: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 9792: 
1.577     banghart 9793: sub get_marked_as_readonly_hash {
1.745     raeburn  9794:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 9795:     my %readonly_files;
1.745     raeburn  9796:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   9797:         if (defined($group)) {
                   9798:             if ($file_name !~ m-^\Q$group\E/-) {
                   9799:                 next;
                   9800:             }
                   9801:         }
1.577     banghart 9802:         if (ref($value) eq "ARRAY"){
                   9803:             foreach my $stored_what (@{$value}) {
1.745     raeburn  9804:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 9805:                     foreach my $lock_descriptor(@{$stored_what}) {
                   9806:                         if ($lock_descriptor eq 'graded') {
                   9807:                             $readonly_files{$file_name} = 'graded';
                   9808:                         } elsif ($lock_descriptor eq 'handback') {
                   9809:                             $readonly_files{$file_name} = 'handback';
                   9810:                         } else {
                   9811:                             if (!exists($readonly_files{$file_name})) {
                   9812:                                 $readonly_files{$file_name} = 'locked';
                   9813:                             }
                   9814:                         }
1.745     raeburn  9815:                     }
1.750     banghart 9816:                 } 
1.577     banghart 9817:             }
                   9818:         } 
                   9819:     }
                   9820:     return %readonly_files;
                   9821: }
1.559     banghart 9822: # ------------------------------------------------------------ Unmark as Read Only
                   9823: 
                   9824: sub unmark_as_readonly {
1.629     banghart 9825:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   9826:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  9827:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 9828:     $file_name = &declutter_portfile($file_name);
1.634     albertel 9829:     my $symb_crs = $what;
                   9830:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  9831:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 9832:     my ($tmp)=keys(%current_permissions);
                   9833:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9834:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 9835:     foreach my $file (@readonly_files) {
1.759     albertel 9836: 	my $clean_file = &declutter_portfile($file);
                   9837: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 9838: 	my $current_locks = $current_permissions{$file};
1.563     banghart 9839:         my @new_locks;
                   9840:         my @del_keys;
                   9841:         if (ref($current_locks) eq "ARRAY"){
                   9842:             foreach my $locker (@{$current_locks}) {
1.632     albertel 9843:                 my $compare=$locker;
1.749     raeburn  9844:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  9845:                     $compare=join('',@{$locker});
1.746     raeburn  9846:                     if ($compare ne $symb_crs) {
                   9847:                         push(@new_locks, $locker);
                   9848:                     }
1.563     banghart 9849:                 }
                   9850:             }
1.650     albertel 9851:             if (scalar(@new_locks) > 0) {
1.563     banghart 9852:                 $current_permissions{$file} = \@new_locks;
                   9853:             } else {
                   9854:                 push(@del_keys, $file);
1.613     albertel 9855:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 9856:                 delete($current_permissions{$file});
1.563     banghart 9857:             }
                   9858:         }
1.561     banghart 9859:     }
1.613     albertel 9860:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9861:     return;
                   9862: }
1.512     banghart 9863: 
1.17      www      9864: # ------------------------------------------------------------ Directory lister
                   9865: 
                   9866: sub dirlist {
1.955     raeburn  9867:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      9868:     $uri=~s/^\///;
                   9869:     $uri=~s/\/$//;
1.253     stredwic 9870:     my ($udom, $uname);
1.955     raeburn  9871:     if ($getuserdir) {
1.253     stredwic 9872:         $udom = $userdomain;
                   9873:         $uname = $username;
1.955     raeburn  9874:     } else {
                   9875:         (undef,$udom,$uname)=split(/\//,$uri);
                   9876:         if(defined($userdomain)) {
                   9877:             $udom = $userdomain;
                   9878:         }
                   9879:         if(defined($username)) {
                   9880:             $uname = $username;
                   9881:         }
1.253     stredwic 9882:     }
1.955     raeburn  9883:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 9884: 
1.955     raeburn  9885:     $dirRoot = $perlvar{'lonDocRoot'};
                   9886:     if (defined($getpropath)) {
                   9887:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 9888:         $dirRoot =~ s/\/$//;
1.955     raeburn  9889:     } elsif (defined($getuserdir)) {
                   9890:         my $subdir=$uname.'__';
                   9891:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   9892:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   9893:                    ."/$udom/$subdir/$uname";
                   9894:     } elsif (defined($alternateRoot)) {
                   9895:         $dirRoot = $alternateRoot;
1.751     banghart 9896:     }
1.253     stredwic 9897: 
                   9898:     if($udom) {
                   9899:         if($uname) {
1.1135    raeburn  9900:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  9901:             if ($uhome eq 'no_host') {
                   9902:                 return ([],'no_host');
                   9903:             }
1.955     raeburn  9904:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  9905:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  9906:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  9907:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9908:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  9909:             } else {
                   9910:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9911:             }
1.605     matthew  9912:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  9913:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  9914:                 @listing_results = split(/:/,$listing);
                   9915:             } else {
                   9916:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9917:             }
1.1135    raeburn  9918:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  9919:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9920:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9921:                 return ([],$listing);
                   9922:             } else {
                   9923:                 return (\@listing_results);
1.1135    raeburn  9924:             }
1.955     raeburn  9925:         } elsif(!$alternateRoot) {
1.1136    raeburn  9926:             my (%allusers,%listerror);
1.841     albertel 9927: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  9928:  	    foreach my $tryserver (keys(%servers)) {
                   9929:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   9930:                                   &escape($udom),$tryserver);
                   9931:                 if ($listing eq 'unknown_cmd') {
                   9932: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9933: 				      $udom, $tryserver);
                   9934:                 } else {
                   9935:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   9936:                 }
1.841     albertel 9937: 		if ($listing eq 'unknown_cmd') {
                   9938: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   9939: 				      $udom, $tryserver);
                   9940: 		    @listing_results = split(/:/,$listing);
                   9941: 		} else {
                   9942: 		    @listing_results =
                   9943: 			map { &unescape($_); } split(/:/,$listing);
                   9944: 		}
1.1136    raeburn  9945:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   9946:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   9947:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   9948:                     $listerror{$tryserver} = $listing;
                   9949:                 } else {
1.841     albertel 9950: 		    foreach my $line (@listing_results) {
                   9951: 			my ($entry) = split(/&/,$line,2);
                   9952: 			$allusers{$entry} = 1;
                   9953: 		    }
                   9954: 		}
1.253     stredwic 9955:             }
1.1136    raeburn  9956:             my @alluserslist=();
1.800     albertel 9957:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  9958:                 push(@alluserslist,$user.'&user');
1.253     stredwic 9959:             }
1.1136    raeburn  9960:             return (\@alluserslist);
1.253     stredwic 9961:         } else {
1.1136    raeburn  9962:             return ([],'missing username');
1.253     stredwic 9963:         }
1.955     raeburn  9964:     } elsif(!defined($getpropath)) {
1.1136    raeburn  9965:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   9966:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   9967:         return (\@all_domains);
1.955     raeburn  9968:     } else {
1.1136    raeburn  9969:         return ([],'missing domain');
1.275     stredwic 9970:     }
                   9971: }
                   9972: 
                   9973: # --------------------------------------------- GetFileTimestamp
                   9974: # This function utilizes dirlist and returns the date stamp for
                   9975: # when it was last modified.  It will also return an error of -1
                   9976: # if an error occurs
                   9977: 
                   9978: sub GetFileTimestamp {
1.955     raeburn  9979:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 9980:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   9981:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  9982:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   9983:                                     undef,$getuserdir);
                   9984:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   9985:         return -1;
                   9986:     }
                   9987:     if (ref($fileref) eq 'ARRAY') {
                   9988:         my @stats = split('&',$fileref->[0]);
1.375     matthew  9989:         # @stats contains first the filename, then the stat output
                   9990:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 9991:     } else {
                   9992:         return -1;
1.253     stredwic 9993:     }
1.26      www      9994: }
                   9995: 
1.712     albertel 9996: sub stat_file {
                   9997:     my ($uri) = @_;
1.787     albertel 9998:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 9999: 
1.955     raeburn  10000:     my ($udom,$uname,$file);
1.712     albertel 10001:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10002: 	($udom,$uname,$file) =
1.811     albertel 10003: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10004: 	$file = 'userfiles/'.$file;
                   10005:     }
                   10006:     if ($uri =~ m-^/res/-) {
                   10007: 	($udom,$uname) = 
1.807     albertel 10008: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10009: 	$file = $uri;
                   10010:     }
                   10011: 
                   10012:     if (!$udom || !$uname || !$file) {
                   10013: 	# unable to handle the uri
                   10014: 	return ();
                   10015:     }
1.956     raeburn  10016:     my $getpropath;
                   10017:     if ($file =~ /^userfiles\//) {
                   10018:         $getpropath = 1;
                   10019:     }
1.1136    raeburn  10020:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10021:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10022:         return ();
                   10023:     } else {
                   10024:         if (ref($listref) eq 'ARRAY') {
                   10025:             my @stats = split('&',$listref->[0]);
                   10026: 	    shift(@stats); #filename is first
                   10027: 	    return @stats;
                   10028:         }
1.712     albertel 10029:     }
                   10030:     return ();
                   10031: }
                   10032: 
1.26      www      10033: # -------------------------------------------------------- Value of a Condition
                   10034: 
1.713     albertel 10035: # gets the value of a specific preevaluated condition
                   10036: #    stored in the string  $env{user.state.<cid>}
                   10037: # or looks up a condition reference in the bighash and if if hasn't
                   10038: # already been evaluated recurses into docondval to get the value of
                   10039: # the condition, then memoizing it to 
                   10040: #   $env{user.state.<cid>.<condition>}
1.40      www      10041: sub directcondval {
                   10042:     my $number=shift;
1.620     albertel 10043:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10044: 	&Apache::lonuserstate::evalstate();
                   10045:     }
1.713     albertel 10046:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10047: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10048:     } elsif ($number =~ /^_/) {
                   10049: 	my $sub_condition;
                   10050: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10051: 		&GDBM_READER(),0640)) {
                   10052: 	    $sub_condition=$bighash{'conditions'.$number};
                   10053: 	    untie(%bighash);
                   10054: 	}
                   10055: 	my $value = &docondval($sub_condition);
1.949     raeburn  10056: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10057: 	return $value;
                   10058:     }
1.620     albertel 10059:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10060:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10061:     } else {
                   10062:        return 2;
                   10063:     }
                   10064: }
                   10065: 
1.713     albertel 10066: # get the collection of conditions for this resource
1.26      www      10067: sub condval {
                   10068:     my $condidx=shift;
1.54      www      10069:     my $allpathcond='';
1.713     albertel 10070:     foreach my $cond (split(/\|/,$condidx)) {
                   10071: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10072: 	    $allpathcond.=
                   10073: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10074: 	}
1.191     harris41 10075:     }
1.54      www      10076:     $allpathcond=~s/\|$//;
1.713     albertel 10077:     return &docondval($allpathcond);
                   10078: }
                   10079: 
                   10080: #evaluates an expression of conditions
                   10081: sub docondval {
                   10082:     my ($allpathcond) = @_;
                   10083:     my $result=0;
                   10084:     if ($env{'request.course.id'}
                   10085: 	&& defined($allpathcond)) {
                   10086: 	my $operand='|';
                   10087: 	my @stack;
                   10088: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10089: 	    if ($chunk eq '(') {
                   10090: 		push @stack,($operand,$result);
                   10091: 	    } elsif ($chunk eq ')') {
                   10092: 		my $before=pop @stack;
                   10093: 		if (pop @stack eq '&') {
                   10094: 		    $result=$result>$before?$before:$result;
                   10095: 		} else {
                   10096: 		    $result=$result>$before?$result:$before;
                   10097: 		}
                   10098: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10099: 		$operand=$chunk;
                   10100: 	    } else {
                   10101: 		my $new=directcondval($chunk);
                   10102: 		if ($operand eq '&') {
                   10103: 		    $result=$result>$new?$new:$result;
                   10104: 		} else {
                   10105: 		    $result=$result>$new?$result:$new;
                   10106: 		}
                   10107: 	    }
                   10108: 	}
1.26      www      10109:     }
                   10110:     return $result;
1.421     albertel 10111: }
                   10112: 
                   10113: # ---------------------------------------------------- Devalidate courseresdata
                   10114: 
                   10115: sub devalidatecourseresdata {
                   10116:     my ($coursenum,$coursedomain)=@_;
                   10117:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10118:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10119: }
                   10120: 
1.763     www      10121: 
1.200     www      10122: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10123: #
                   10124: #  Parameters:
                   10125: #      $coursenum    - Number of the course.
                   10126: #      $coursedomain - Domain at which the course was created.
                   10127: #  Returns:
                   10128: #     A hash of the course parameters along (I think) with timestamps
                   10129: #     and version info.
1.877     foxr     10130: 
1.624     albertel 10131: sub get_courseresdata {
                   10132:     my ($coursenum,$coursedomain)=@_;
1.200     www      10133:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10134:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10135:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10136:     my %dumpreply;
1.417     albertel 10137:     unless (defined($cached)) {
1.624     albertel 10138: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10139: 	$result=\%dumpreply;
1.251     albertel 10140: 	my ($tmp) = keys(%dumpreply);
                   10141: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10142: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10143: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10144: 	    return $tmp;
1.416     albertel 10145: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10146: 	    $result=undef;
1.599     albertel 10147: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10148: 	}
                   10149:     }
1.624     albertel 10150:     return $result;
                   10151: }
                   10152: 
1.633     albertel 10153: sub devalidateuserresdata {
                   10154:     my ($uname,$udom)=@_;
                   10155:     my $hashid="$udom:$uname";
                   10156:     &devalidate_cache_new('userres',$hashid);
                   10157: }
                   10158: 
1.624     albertel 10159: sub get_userresdata {
                   10160:     my ($uname,$udom)=@_;
                   10161:     #most student don\'t have any data set, check if there is some data
                   10162:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10163: 
                   10164:     my $hashid="$udom:$uname";
                   10165:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10166:     if (!defined($cached)) {
                   10167: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10168: 	$result=\%resourcedata;
                   10169: 	&do_cache_new('userres',$hashid,$result,600);
                   10170:     }
                   10171:     my ($tmp)=keys(%$result);
                   10172:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10173: 	return $result;
                   10174:     }
                   10175:     #error 2 occurs when the .db doesn't exist
                   10176:     if ($tmp!~/error: 2 /) {
1.672     albertel 10177: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 10178: 		 " Trying to get resource data for ".
                   10179: 		 $uname." at ".$udom.": ".
                   10180: 		 $tmp."</font>");
                   10181:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10182: 	#&EXT_cache_set($udom,$uname);
                   10183: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10184: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10185:     }
                   10186:     return $tmp;
                   10187: }
1.879     foxr     10188: #----------------------------------------------- resdata - return resource data
                   10189: #  Purpose:
                   10190: #    Return resource data for either users or for a course.
                   10191: #  Parameters:
                   10192: #     $name      - Course/user name.
                   10193: #     $domain    - Name of the domain the user/course is registered on.
                   10194: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   10195: #     @which     - Array of names of resources desired.
                   10196: #  Returns:
                   10197: #     The value of the first reasource in @which that is found in the
                   10198: #     resource hash.
                   10199: #  Exceptional Conditions:
                   10200: #     If the $type passed in is not valid (not the string 'course' or 
                   10201: #     'user', an undefined  reference is returned.
                   10202: #     If none of the resources are found, an undef is returned
1.624     albertel 10203: sub resdata {
                   10204:     my ($name,$domain,$type,@which)=@_;
                   10205:     my $result;
                   10206:     if ($type eq 'course') {
                   10207: 	$result=&get_courseresdata($name,$domain);
                   10208:     } elsif ($type eq 'user') {
                   10209: 	$result=&get_userresdata($name,$domain);
                   10210:     }
                   10211:     if (!ref($result)) { return $result; }    
1.251     albertel 10212:     foreach my $item (@which) {
1.927     albertel 10213: 	if (defined($result->{$item->[0]})) {
                   10214: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10215: 	}
1.250     albertel 10216:     }
1.291     albertel 10217:     return undef;
1.200     www      10218: }
                   10219: 
1.1236    raeburn  10220: sub get_numsuppfiles {
                   10221:     my ($cnum,$cdom,$ignorecache)=@_;
                   10222:     my $hashid=$cnum.':'.$cdom;
                   10223:     my ($suppcount,$cached);
                   10224:     unless ($ignorecache) {
                   10225:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10226:     }
                   10227:     unless (defined($cached)) {
                   10228:         my $chome=&homeserver($cnum,$cdom);
                   10229:         unless ($chome eq 'no_host') {
                   10230:             ($suppcount,my $errors) = (0,0);
                   10231:             my $suppmap = 'supplemental.sequence';
                   10232:             ($suppcount,$errors) = 
                   10233:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10234:         }
                   10235:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10236:     }
                   10237:     return $suppcount;
                   10238: }
                   10239: 
1.379     matthew  10240: #
                   10241: # EXT resource caching routines
                   10242: #
                   10243: 
                   10244: sub clear_EXT_cache_status {
1.383     albertel 10245:     &delenv('cache.EXT.');
1.379     matthew  10246: }
                   10247: 
                   10248: sub EXT_cache_status {
                   10249:     my ($target_domain,$target_user) = @_;
1.383     albertel 10250:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10251:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10252:         # We know already the user has no data
                   10253:         return 1;
                   10254:     } else {
                   10255:         return 0;
                   10256:     }
                   10257: }
                   10258: 
                   10259: sub EXT_cache_set {
                   10260:     my ($target_domain,$target_user) = @_;
1.383     albertel 10261:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10262:     #&appenv({$cachename => time});
1.379     matthew  10263: }
                   10264: 
1.28      www      10265: # --------------------------------------------------------- Value of a Variable
1.58      www      10266: sub EXT {
1.715     albertel 10267: 
1.1228    raeburn  10268:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10269:     unless ($varname) { return ''; }
1.218     albertel 10270:     #get real user name/domain, courseid and symb
                   10271:     my $courseid;
1.359     albertel 10272:     my $publicuser;
1.427     www      10273:     if ($symbparm) {
                   10274: 	$symbparm=&get_symb_from_alias($symbparm);
                   10275:     }
1.218     albertel 10276:     if (!($uname && $udom)) {
1.790     albertel 10277:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10278:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10279:     } else {
1.620     albertel 10280: 	$courseid=$env{'request.course.id'};
1.218     albertel 10281:     }
1.48      www      10282:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10283:     my $rest;
1.320     albertel 10284:     if (defined($therest[0])) {
1.48      www      10285:        $rest=join('.',@therest);
                   10286:     } else {
                   10287:        $rest='';
                   10288:     }
1.320     albertel 10289: 
1.57      www      10290:     my $qualifierrest=$qualifier;
                   10291:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10292:     my $spacequalifierrest=$space;
                   10293:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10294:     if ($realm eq 'user') {
1.48      www      10295: # --------------------------------------------------------------- user.resource
                   10296: 	if ($space eq 'resource') {
1.651     albertel 10297: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10298: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10299: 		 &&
1.744     albertel 10300: 		 ($symbparm eq &symbread()) ) {	
                   10301: 		# if we are in the middle of processing the resource the
                   10302: 		# get the value we are planning on committing
                   10303:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10304:                     return $Apache::lonhomework::results{$qualifierrest};
                   10305:                 } else {
                   10306:                     return $Apache::lonhomework::history{$qualifierrest};
                   10307:                 }
1.335     albertel 10308: 	    } else {
1.359     albertel 10309: 		my %restored;
1.620     albertel 10310: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10311: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10312: 		} else {
                   10313: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10314: 		}
1.335     albertel 10315: 		return $restored{$qualifierrest};
                   10316: 	    }
1.48      www      10317: # ----------------------------------------------------------------- user.access
                   10318:         } elsif ($space eq 'access') {
1.218     albertel 10319: 	    # FIXME - not supporting calls for a specific user
1.48      www      10320:             return &allowed($qualifier,$rest);
                   10321: # ------------------------------------------ user.preferences, user.environment
                   10322:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10323: 	    if (($uname eq $env{'user.name'}) &&
                   10324: 		($udom eq $env{'user.domain'})) {
                   10325: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10326: 	    } else {
1.359     albertel 10327: 		my %returnhash;
                   10328: 		if (!$publicuser) {
                   10329: 		    %returnhash=&userenvironment($udom,$uname,
                   10330: 						 $qualifierrest);
                   10331: 		}
1.218     albertel 10332: 		return $returnhash{$qualifierrest};
                   10333: 	    }
1.48      www      10334: # ----------------------------------------------------------------- user.course
                   10335:         } elsif ($space eq 'course') {
1.218     albertel 10336: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10337:             return $env{join('.',('request.course',$qualifier))};
1.48      www      10338: # ------------------------------------------------------------------- user.role
                   10339:         } elsif ($space eq 'role') {
1.218     albertel 10340: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 10341:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      10342:             if ($qualifier eq 'value') {
                   10343: 		return $role;
                   10344:             } elsif ($qualifier eq 'extent') {
                   10345:                 return $where;
                   10346:             }
                   10347: # ----------------------------------------------------------------- user.domain
                   10348:         } elsif ($space eq 'domain') {
1.218     albertel 10349:             return $udom;
1.48      www      10350: # ------------------------------------------------------------------- user.name
                   10351:         } elsif ($space eq 'name') {
1.218     albertel 10352:             return $uname;
1.48      www      10353: # ---------------------------------------------------- Any other user namespace
1.29      www      10354:         } else {
1.359     albertel 10355: 	    my %reply;
                   10356: 	    if (!$publicuser) {
                   10357: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   10358: 	    }
                   10359: 	    return $reply{$qualifierrest};
1.48      www      10360:         }
1.236     www      10361:     } elsif ($realm eq 'query') {
                   10362: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 10363:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   10364: 						[$spacequalifierrest]);
1.620     albertel 10365: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      10366:    } elsif ($realm eq 'request') {
1.48      www      10367: # ------------------------------------------------------------- request.browser
                   10368:         if ($space eq 'browser') {
1.1145    bisitz   10369:             return $env{'browser.'.$qualifier};
1.57      www      10370: # ------------------------------------------------------------ request.filename
                   10371:         } else {
1.620     albertel 10372:             return $env{'request.'.$spacequalifierrest};
1.29      www      10373:         }
1.28      www      10374:     } elsif ($realm eq 'course') {
1.48      www      10375: # ---------------------------------------------------------- course.description
1.620     albertel 10376:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      10377:     } elsif ($realm eq 'resource') {
1.165     www      10378: 
1.620     albertel 10379: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 10380: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   10381: 	}
1.693     albertel 10382: 
1.1232    raeburn  10383:         if ($qualifier eq '') {
                   10384: 	    if ($space eq 'title') {
                   10385: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   10386: 	        return &gettitle($symbparm);
                   10387: 	    }
1.693     albertel 10388: 	
1.1232    raeburn  10389: 	    if ($space eq 'map') {
                   10390: 	        my ($map) = &decode_symb($symbparm);
                   10391: 	        return &symbread($map);
                   10392: 	    }
                   10393:             if ($space eq 'maptitle') {
                   10394:                 my ($map) = &decode_symb($symbparm);
                   10395:                 return &gettitle($map);
                   10396:             }
                   10397: 	    if ($space eq 'filename') {
                   10398: 	        if ($symbparm) {
                   10399: 		    return &clutter((&decode_symb($symbparm))[2]);
                   10400: 	        }
                   10401: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 10402: 	    }
1.1232    raeburn  10403: 
1.1233    raeburn  10404:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   10405:                 if ($space eq 'visibleparts') {
                   10406:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   10407:                     my $item;
                   10408:                     if (ref($navmap)) {
                   10409:                         my $res = $navmap->getBySymb($symbparm);
                   10410:                         my $parts = $res->parts();
                   10411:                         if (ref($parts) eq 'ARRAY') {
                   10412:                             $item = join(',',@{$parts});
                   10413:                         }
                   10414:                         undef($navmap);
1.1232    raeburn  10415:                     }
1.1233    raeburn  10416:                     return $item;
1.1232    raeburn  10417:                 }
                   10418:             }
                   10419:         }
1.693     albertel 10420: 
                   10421: 	my ($section, $group, @groups);
1.593     albertel 10422: 	my ($courselevelm,$courselevel);
1.1228    raeburn  10423:         if (($courseid eq '') && ($cid)) {
                   10424:             $courseid = $cid;
                   10425:         }
                   10426: 	if (($symbparm && $courseid) && 
                   10427: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      10428: 
1.218     albertel 10429: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      10430: 
1.60      www      10431: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 10432: 	    my $symbp=$symbparm;
1.735     albertel 10433: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 10434: 
                   10435: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   10436: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   10437: 
1.620     albertel 10438: 	    if (($env{'user.name'} eq $uname) &&
                   10439: 		($env{'user.domain'} eq $udom)) {
                   10440: 		$section=$env{'request.course.sec'};
1.733     raeburn  10441:                 @groups = split(/:/,$env{'request.course.groups'});  
                   10442:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 10443: 	    } else {
1.539     albertel 10444: 		if (! defined($usection)) {
1.551     albertel 10445: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 10446: 		} else {
                   10447: 		    $section = $usection;
                   10448: 		}
1.733     raeburn  10449:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 10450: 	    }
                   10451: 
                   10452: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   10453: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   10454: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   10455: 
1.593     albertel 10456: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 10457: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 10458: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      10459: 
1.60      www      10460: # ----------------------------------------------------------- first, check user
1.624     albertel 10461: 
                   10462: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 10463: 				       ([$courselevelr,'resource'],
                   10464: 					[$courselevelm,'map'     ],
                   10465: 					[$courselevel, 'course'  ]));
1.931     albertel 10466: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      10467: 
1.594     albertel 10468: # ------------------------------------------------ second, check some of course
1.684     raeburn  10469:             my $coursereply;
1.691     raeburn  10470:             if (@groups > 0) {
                   10471:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   10472:                                        $mapparm,$spacequalifierrest);
1.927     albertel 10473:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  10474:             }
1.96      www      10475: 
1.684     raeburn  10476: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 10477: 				  $env{'course.'.$courseid.'.domain'},
                   10478: 				  'course',
                   10479: 				  ([$seclevelr,   'resource'],
                   10480: 				   [$seclevelm,   'map'     ],
                   10481: 				   [$seclevel,    'course'  ],
                   10482: 				   [$courselevelr,'resource']));
                   10483: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      10484: 
1.60      www      10485: # ------------------------------------------------------ third, check map parms
1.218     albertel 10486: 	    my %parmhash=();
                   10487: 	    my $thisparm='';
                   10488: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 10489: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 10490: 		    &GDBM_READER(),0640)) {
1.218     albertel 10491: 		$thisparm=$parmhash{$symbparm};
                   10492: 		untie(%parmhash);
                   10493: 	    }
1.927     albertel 10494: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 10495: 	}
1.594     albertel 10496: # ------------------------------------------ fourth, look in resource metadata
1.71      www      10497: 
1.218     albertel 10498: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 10499: 	my $filename;
                   10500: 	if (!$symbparm) { $symbparm=&symbread(); }
                   10501: 	if ($symbparm) {
1.409     www      10502: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 10503: 	} else {
1.620     albertel 10504: 	    $filename=$env{'request.filename'};
1.282     albertel 10505: 	}
                   10506: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 10507: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 10508: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 10509: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      10510: 
1.927     albertel 10511: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 10512: 	if ($symbparm && defined($courseid) && 
1.620     albertel 10513: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 10514: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   10515: 				     $env{'course.'.$courseid.'.domain'},
                   10516: 				     'course',
1.927     albertel 10517: 				     ([$courselevelm,'map'   ],
                   10518: 				      [$courselevel, 'course']));
                   10519: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 10520: 	}
1.145     www      10521: # ------------------------------------------------------------------ Cascade up
1.218     albertel 10522: 	unless ($space eq '0') {
1.336     albertel 10523: 	    my @parts=split(/_/,$space);
                   10524: 	    my $id=pop(@parts);
                   10525: 	    my $part=join('_',@parts);
                   10526: 	    if ($part eq '') { $part='0'; }
1.927     albertel 10527: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 10528: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  10529: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 10530: 	}
1.395     albertel 10531: 	if ($recurse) { return undef; }
                   10532: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 10533: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      10534: # ---------------------------------------------------- Any other user namespace
                   10535:     } elsif ($realm eq 'environment') {
                   10536: # ----------------------------------------------------------------- environment
1.620     albertel 10537: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   10538: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 10539: 	} else {
1.770     albertel 10540: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   10541: 		return '';
                   10542: 	    }
1.219     albertel 10543: 	    my %returnhash=&userenvironment($udom,$uname,
                   10544: 					    $spacequalifierrest);
                   10545: 	    return $returnhash{$spacequalifierrest};
                   10546: 	}
1.28      www      10547:     } elsif ($realm eq 'system') {
1.48      www      10548: # ----------------------------------------------------------------- system.time
                   10549: 	if ($space eq 'time') {
                   10550: 	    return time;
                   10551:         }
1.696     albertel 10552:     } elsif ($realm eq 'server') {
                   10553: # ----------------------------------------------------------------- system.time
                   10554: 	if ($space eq 'name') {
                   10555: 	    return $ENV{'SERVER_NAME'};
                   10556:         }
1.28      www      10557:     }
1.48      www      10558:     return '';
1.61      www      10559: }
                   10560: 
1.927     albertel 10561: sub get_reply {
                   10562:     my ($reply_value) = @_;
1.940     raeburn  10563:     if (ref($reply_value) eq 'ARRAY') {
                   10564:         if (wantarray) {
                   10565: 	    return @$reply_value;
                   10566:         }
                   10567:         return $reply_value->[0];
                   10568:     } else {
                   10569:         return $reply_value;
1.927     albertel 10570:     }
                   10571: }
                   10572: 
1.691     raeburn  10573: sub check_group_parms {
                   10574:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   10575:     my @groupitems = ();
                   10576:     my $resultitem;
1.927     albertel 10577:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  10578:     foreach my $group (@{$groups}) {
                   10579:         foreach my $level (@levels) {
1.927     albertel 10580:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   10581:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  10582:         }
                   10583:     }
                   10584:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   10585:                             $env{'course.'.$courseid.'.domain'},
                   10586:                                      'course',@groupitems);
                   10587:     return $coursereply;
                   10588: }
                   10589: 
                   10590: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  10591:     my ($courseid,@groups) = @_;
                   10592:     @groups = sort(@groups);
1.691     raeburn  10593:     return @groups;
                   10594: }
                   10595: 
1.395     albertel 10596: sub packages_tab_default {
                   10597:     my ($uri,$varname)=@_;
                   10598:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 10599: 
                   10600:     my (@extension,@specifics,$do_default);
                   10601:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 10602: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 10603: 	if ($pack_type eq 'default') {
                   10604: 	    $do_default=1;
                   10605: 	} elsif ($pack_type eq 'extension') {
                   10606: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 10607: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 10608: 	    # only look at packages defaults for packages that this id is
1.738     albertel 10609: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   10610: 	}
                   10611:     }
                   10612:     # first look for a package that matches the requested part id
                   10613:     foreach my $package (@specifics) {
                   10614: 	my (undef,$pack_type,$pack_part)=@{$package};
                   10615: 	next if ($pack_part ne $part);
                   10616: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10617: 	    return $packagetab{"$pack_type&$name&default"};
                   10618: 	}
                   10619:     }
                   10620:     # look for any possible matching non extension_ package
                   10621:     foreach my $package (@specifics) {
                   10622: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 10623: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10624: 	    return $packagetab{"$pack_type&$name&default"};
                   10625: 	}
1.585     albertel 10626: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 10627: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   10628: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 10629: 	}
                   10630:     }
1.738     albertel 10631:     # look for any posible extension_ match
                   10632:     foreach my $package (@extension) {
                   10633: 	my ($package,$pack_type)=@{$package};
                   10634: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   10635: 	    return $packagetab{"$pack_type&$name&default"};
                   10636: 	}
                   10637: 	if (defined($packagetab{$package."&$name&default"})) {
                   10638: 	    return $packagetab{$package."&$name&default"};
                   10639: 	}
                   10640:     }
                   10641:     # look for a global default setting
                   10642:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   10643: 	return $packagetab{"default&$name&default"};
                   10644:     }
1.395     albertel 10645:     return undef;
                   10646: }
                   10647: 
1.334     albertel 10648: sub add_prefix_and_part {
                   10649:     my ($prefix,$part)=@_;
                   10650:     my $keyroot;
                   10651:     if (defined($prefix) && $prefix !~ /^__/) {
                   10652: 	# prefix that has a part already
                   10653: 	$keyroot=$prefix;
                   10654:     } elsif (defined($prefix)) {
                   10655: 	# prefix that is missing a part
                   10656: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   10657:     } else {
                   10658: 	# no prefix at all
                   10659: 	if (defined($part)) { $keyroot='_'.$part; }
                   10660:     }
                   10661:     return $keyroot;
                   10662: }
                   10663: 
1.71      www      10664: # ---------------------------------------------------------------- Get metadata
                   10665: 
1.599     albertel 10666: my %metaentry;
1.1070    www      10667: my %importedpartids;
1.71      www      10668: sub metadata {
1.176     www      10669:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      10670:     $uri=&declutter($uri);
1.288     albertel 10671:     # if it is a non metadata possible uri return quickly
1.529     albertel 10672:     if (($uri eq '') || 
                   10673: 	(($uri =~ m|^/*adm/|) && 
1.1217    raeburn  10674: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  10675:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 10676: 	return undef;
                   10677:     }
1.1261    raeburn  10678:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 10679: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 10680: 	return undef;
1.288     albertel 10681:     }
1.73      www      10682:     my $filename=$uri;
                   10683:     $uri=~s/\.meta$//;
1.172     www      10684: #
                   10685: # Is the metadata already cached?
1.177     www      10686: # Look at timestamp of caching
1.172     www      10687: # Everything is cached by the main uri, libraries are never directly cached
                   10688: #
1.428     albertel 10689:     if (!defined($liburi)) {
1.599     albertel 10690: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 10691: 	if (defined($cached)) { return $result->{':'.$what}; }
                   10692:     }
                   10693:     {
1.1069    www      10694: # Imported parts would go here
1.1070    www      10695:         my %importedids=();
                   10696:         my @origfileimportpartids=();
1.1069    www      10697:         my $importedparts=0;
1.172     www      10698: #
                   10699: # Is this a recursive call for a library?
                   10700: #
1.599     albertel 10701: #	if (! exists($metacache{$uri})) {
                   10702: #	    $metacache{$uri}={};
                   10703: #	}
1.924     albertel 10704: 	my $cachetime = 60*60;
1.171     www      10705:         if ($liburi) {
                   10706: 	    $liburi=&declutter($liburi);
                   10707:             $filename=$liburi;
1.401     bowersj2 10708:         } else {
1.599     albertel 10709: 	    &devalidate_cache_new('meta',$uri);
                   10710: 	    undef(%metaentry);
1.401     bowersj2 10711: 	}
1.140     www      10712:         my %metathesekeys=();
1.73      www      10713:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 10714: 	my $metastring;
1.1140    www      10715: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 10716: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 10717: 	    $metastring = 
1.929     albertel 10718: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 10719: 					  ('grade_target' => 'meta'));
                   10720: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  10721: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   10722:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 10723: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 10724: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 10725: 	    $metastring=&getfile($file);
1.489     albertel 10726: 	}
1.208     albertel 10727:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      10728:         my $token;
1.140     www      10729:         undef %metathesekeys;
1.71      www      10730:         while ($token=$parser->get_token) {
1.339     albertel 10731: 	    if ($token->[0] eq 'S') {
                   10732: 		if (defined($token->[2]->{'package'})) {
1.172     www      10733: #
                   10734: # This is a package - get package info
                   10735: #
1.339     albertel 10736: 		    my $package=$token->[2]->{'package'};
                   10737: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10738: 		    if (defined($token->[2]->{'id'})) { 
                   10739: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   10740: 		    }
1.599     albertel 10741: 		    if ($metaentry{':packages'}) {
                   10742: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 10743: 		    } else {
1.599     albertel 10744: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 10745: 		    }
1.736     albertel 10746: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 10747: 			my $part=$keyroot;
                   10748: 			$part=~s/^\_//;
1.736     albertel 10749: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   10750: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   10751: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 10752: 			    # ignore package.tab specified default values
                   10753:                             # here &package_tab_default() will fetch those
                   10754: 			    if ($subp eq 'default') { next; }
1.736     albertel 10755: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 10756: 			    my $unikey;
                   10757: 			    if ($pack =~ /_0$/) {
                   10758: 				$unikey='parameter_0_'.$name;
                   10759: 				$part=0;
                   10760: 			    } else {
                   10761: 				$unikey='parameter'.$keyroot.'_'.$name;
                   10762: 			    }
1.339     albertel 10763: 			    if ($subp eq 'display') {
                   10764: 				$value.=' [Part: '.$part.']';
                   10765: 			    }
1.599     albertel 10766: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 10767: 			    $metathesekeys{$unikey}=1;
1.599     albertel 10768: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10769: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 10770: 			    }
1.599     albertel 10771: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   10772: 				$metaentry{':'.$unikey}=
                   10773: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 10774: 			    }
1.339     albertel 10775: 			}
                   10776: 		    }
                   10777: 		} else {
1.172     www      10778: #
                   10779: # This is not a package - some other kind of start tag
1.339     albertel 10780: #
                   10781: 		    my $entry=$token->[1];
1.1068    www      10782: 		    my $unikey='';
1.175     www      10783: 
1.339     albertel 10784: 		    if ($entry eq 'import') {
1.175     www      10785: #
                   10786: # Importing a library here
1.339     albertel 10787: #
1.1067    www      10788:                         my $location=$parser->get_text('/import');
                   10789:                         my $dir=$filename;
                   10790:                         $dir=~s|[^/]*$||;
                   10791:                         $location=&filelocation($dir,$location);
1.1069    www      10792:                        
1.1068    www      10793:                         my $importmode=$token->[2]->{'importmode'};
                   10794:                         if ($importmode eq 'problem') {
1.1069    www      10795: # Import as problem/response
1.1068    www      10796:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10797:                         } elsif ($importmode eq 'part') {
                   10798: # Import as part(s)
1.1069    www      10799:                            $importedparts=1;
                   10800: # We need to get the original file and the imported file to get the part order correct
                   10801: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   10802: # Load and inspect original file
1.1070    www      10803:                            if ($#origfileimportpartids<0) {
                   10804:                               undef(%importedpartids);
                   10805:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   10806:                               my $origfile=&getfile($origfilelocation);
                   10807:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10808:                            }
                   10809: 
1.1069    www      10810: # Load and inspect imported file
                   10811:                            my $impfile=&getfile($location);
                   10812:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   10813:                            if ($#impfilepartids>=0) {
                   10814: # This problem had parts
1.1070    www      10815:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      10816:                            } else {
                   10817: # Importing by turning a single problem into a problem part
                   10818: # It gets the import-tags ID as part-ID
                   10819:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      10820:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      10821:                            }
1.1068    www      10822:                         } else {
                   10823: # Normal import
                   10824:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10825:                            if (defined($token->[2]->{'id'})) {
                   10826:                               $unikey.='_'.$token->[2]->{'id'};
                   10827:                            }
1.1067    www      10828:                         }
                   10829: 
1.339     albertel 10830: 			if ($depthcount<20) {
1.736     albertel 10831: 			    my $metadata = 
                   10832: 				&metadata($uri,'keys', $location,$unikey,
                   10833: 					  $depthcount+1);
                   10834: 			    foreach my $meta (split(',',$metadata)) {
                   10835: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   10836: 				$metathesekeys{$meta}=1;
1.339     albertel 10837: 			    }
1.1068    www      10838: 			
                   10839:                         }
1.1067    www      10840: 		    } else {
                   10841: #
                   10842: # Not importing, some other kind of non-package, non-library start tag
                   10843: # 
                   10844:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   10845:                         if (defined($token->[2]->{'id'})) {
                   10846:                             $unikey.='_'.$token->[2]->{'id'};
                   10847:                         }
1.339     albertel 10848: 			if (defined($token->[2]->{'name'})) { 
                   10849: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   10850: 			}
                   10851: 			$metathesekeys{$unikey}=1;
1.736     albertel 10852: 			foreach my $param (@{$token->[3]}) {
                   10853: 			    $metaentry{':'.$unikey.'.'.$param} =
                   10854: 				$token->[2]->{$param};
1.339     albertel 10855: 			}
                   10856: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 10857: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 10858: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   10859: 		 # only ws inside the tag, and not in default, so use default
                   10860: 		 # as value
1.599     albertel 10861: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 10862: 			} elsif ( $internaltext =~ /\S/ ) {
                   10863: 		  # something interesting inside the tag
                   10864: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 10865: 			} else {
1.908     albertel 10866: 		  # no interesting values, don't set a default
1.339     albertel 10867: 			}
1.172     www      10868: # end of not-a-package not-a-library import
1.339     albertel 10869: 		    }
1.172     www      10870: # end of not-a-package start tag
1.339     albertel 10871: 		}
1.172     www      10872: # the next is the end of "start tag"
1.339     albertel 10873: 	    }
                   10874: 	}
1.483     albertel 10875: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 10876: 	$extension = lc($extension);
                   10877: 	if ($extension eq 'htm') { $extension='html'; }
                   10878: 
1.737     albertel 10879: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 10880: 	    #no specific packages #how's our extension
                   10881: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 10882: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 10883: 					 \%metathesekeys);
                   10884: 	}
1.883     albertel 10885: 
                   10886: 	if (!exists($metaentry{':packages'})
                   10887: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 10888: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 10889: 		#no specific packages well let's get default then
                   10890: 		if ($key!~/^default&/) { next; }
1.488     albertel 10891: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 10892: 					     \%metathesekeys);
                   10893: 	    }
                   10894: 	}
1.338     www      10895: # are there custom rights to evaluate
1.599     albertel 10896: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 10897: 
1.338     www      10898:     #
                   10899:     # Importing a rights file here
1.339     albertel 10900:     #
                   10901: 	    unless ($depthcount) {
1.599     albertel 10902: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 10903: 		my $dir=$filename;
                   10904: 		$dir=~s|[^/]*$||;
                   10905: 		$location=&filelocation($dir,$location);
1.736     albertel 10906: 		my $rights_metadata =
                   10907: 		    &metadata($uri,'keys',$location,'_rights',
                   10908: 			      $depthcount+1);
                   10909: 		foreach my $rights (split(',',$rights_metadata)) {
                   10910: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   10911: 		    $metathesekeys{$rights}=1;
1.339     albertel 10912: 		}
                   10913: 	    }
                   10914: 	}
1.737     albertel 10915: 	# uniqifiy package listing
                   10916: 	my %seen;
                   10917: 	my @uniq_packages =
                   10918: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   10919: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   10920: 
1.1070    www      10921:         if ($importedparts) {
                   10922: # We had imported parts and need to rebuild partorder
                   10923:            $metaentry{':partorder'}='';
                   10924:            $metathesekeys{'partorder'}=1;
                   10925:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   10926:                if ($origfileimportpartids[$index] eq 'part') {
                   10927: # original part, part of the problem
                   10928:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   10929:                } else {
                   10930: # we have imported parts at this position
                   10931:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   10932:                }
                   10933:            }
                   10934:            $metaentry{':partorder'}=~s/^\,//;
                   10935:         }
                   10936: 
1.737     albertel 10937: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 10938: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  10939: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 10940: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      10941: # this is the end of "was not already recently cached
1.71      www      10942:     }
1.599     albertel 10943:     return $metaentry{':'.$what};
1.261     albertel 10944: }
                   10945: 
1.488     albertel 10946: sub metadata_create_package_def {
1.483     albertel 10947:     my ($uri,$key,$package,$metathesekeys)=@_;
                   10948:     my ($pack,$name,$subp)=split(/\&/,$key);
                   10949:     if ($subp eq 'default') { next; }
                   10950:     
1.599     albertel 10951:     if (defined($metaentry{':packages'})) {
                   10952: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 10953:     } else {
1.599     albertel 10954: 	$metaentry{':packages'}=$package;
1.483     albertel 10955:     }
                   10956:     my $value=$packagetab{$key};
                   10957:     my $unikey;
                   10958:     $unikey='parameter_0_'.$name;
1.599     albertel 10959:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 10960:     $$metathesekeys{$unikey}=1;
1.599     albertel 10961:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   10962: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 10963:     }
1.599     albertel 10964:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   10965: 	$metaentry{':'.$unikey}=
                   10966: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 10967:     }
                   10968: }
                   10969: 
1.261     albertel 10970: sub metadata_generate_part0 {
                   10971:     my ($metadata,$metacache,$uri) = @_;
                   10972:     my %allnames;
1.737     albertel 10973:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 10974: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 10975: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   10976: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 10977: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 10978: 	    $allnames{$name}=$part;
                   10979: 	  }
                   10980: 	}
                   10981:     }
                   10982:     foreach my $name (keys(%allnames)) {
                   10983:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 10984:       my $key=":parameter_0_$name";
1.261     albertel 10985:       $$metacache{"$key.part"}='0';
                   10986:       $$metacache{"$key.name"}=$name;
1.428     albertel 10987:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 10988: 					   $allnames{$name}.'_'.$name.
                   10989: 					   '.type'};
1.428     albertel 10990:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 10991: 			     '.display'};
1.644     www      10992:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 10993:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 10994:       $$metacache{"$key.display"}=$olddis;
                   10995:     }
1.71      www      10996: }
                   10997: 
1.764     albertel 10998: # ------------------------------------------------------ Devalidate title cache
                   10999: 
                   11000: sub devalidate_title_cache {
                   11001:     my ($url)=@_;
                   11002:     if (!$env{'request.course.id'}) { return; }
                   11003:     my $symb=&symbread($url);
                   11004:     if (!$symb) { return; }
                   11005:     my $key=$env{'request.course.id'}."\0".$symb;
                   11006:     &devalidate_cache_new('title',$key);
                   11007: }
                   11008: 
1.1014    droeschl 11009: # ------------------------------------------------- Get the title of a course
                   11010: 
                   11011: sub current_course_title {
                   11012:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11013: }
1.301     www      11014: # ------------------------------------------------- Get the title of a resource
                   11015: 
                   11016: sub gettitle {
                   11017:     my $urlsymb=shift;
                   11018:     my $symb=&symbread($urlsymb);
1.534     albertel 11019:     if ($symb) {
1.620     albertel 11020: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11021: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11022: 	if (defined($cached)) { 
                   11023: 	    return $result;
                   11024: 	}
1.534     albertel 11025: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11026: 	my $title='';
1.907     albertel 11027: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11028: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11029: 	} else {
                   11030: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11031: 		    &GDBM_READER(),0640)) {
                   11032: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11033: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11034: 		untie(%bighash);
                   11035: 	    }
1.534     albertel 11036: 	}
                   11037: 	$title=~s/\&colon\;/\:/gs;
                   11038: 	if ($title) {
1.1159    www      11039: # Remember both $symb and $title for dynamic metadata
                   11040:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11041:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11042: # Cache this title and then return it
1.599     albertel 11043: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11044: 	}
                   11045: 	$urlsymb=$url;
                   11046:     }
                   11047:     my $title=&metadata($urlsymb,'title');
                   11048:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11049:     return $title;
1.301     www      11050: }
1.613     albertel 11051: 
1.614     albertel 11052: sub get_slot {
                   11053:     my ($which,$cnum,$cdom)=@_;
                   11054:     if (!$cnum || !$cdom) {
1.790     albertel 11055: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11056: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11057: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11058:     }
1.703     albertel 11059:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11060:     my %slotinfo;
                   11061:     if (exists($remembered{$key})) {
                   11062: 	$slotinfo{$which} = $remembered{$key};
                   11063:     } else {
                   11064: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11065: 	&Apache::lonhomework::showhash(%slotinfo);
                   11066: 	my ($tmp)=keys(%slotinfo);
                   11067: 	if ($tmp=~/^error:/) { return (); }
                   11068: 	$remembered{$key} = $slotinfo{$which};
                   11069:     }
1.616     albertel 11070:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11071: 	return %{$slotinfo{$which}};
                   11072:     }
                   11073:     return $slotinfo{$which};
1.614     albertel 11074: }
1.1150    raeburn  11075: 
                   11076: sub get_reservable_slots {
                   11077:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11078:     my $now = time;
                   11079:     my $reservable_info;
                   11080:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11081:     if (exists($remembered{$key})) {
                   11082:         $reservable_info = $remembered{$key};
                   11083:     } else {
                   11084:         my %resv;
                   11085:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11086:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11087:         $reservable_info = \%resv;
                   11088:         $remembered{$key} = $reservable_info;
                   11089:     }
                   11090:     return $reservable_info;
                   11091: }
                   11092: 
                   11093: sub get_course_slots {
                   11094:     my ($cnum,$cdom) = @_;
                   11095:     my $hashid=$cnum.':'.$cdom;
                   11096:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11097:     if (defined($cached)) {
                   11098:         if (ref($result) eq 'HASH') {
                   11099:             return %{$result};
                   11100:         }
                   11101:     } else {
                   11102:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11103:         my ($tmp) = keys(%slots);
                   11104:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  11105:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11106:             return %slots;
                   11107:         }
                   11108:     }
                   11109:     return;
                   11110: }
                   11111: 
                   11112: sub devalidate_slots_cache {
                   11113:     my ($cnum,$cdom)=@_;
                   11114:     my $hashid=$cnum.':'.$cdom;
                   11115:     &devalidate_cache_new('allslots',$hashid);
                   11116: }
                   11117: 
1.1181    raeburn  11118: sub get_coursechange {
                   11119:     my ($cdom,$cnum) = @_;
                   11120:     if ($cdom eq '' || $cnum eq '') {
                   11121:         return unless ($env{'request.course.id'});
                   11122:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11123:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11124:     }
                   11125:     my $hashid=$cdom.'_'.$cnum;
                   11126:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11127:     if ((defined($cached)) && ($change ne '')) {
                   11128:         return $change;
                   11129:     } else {
                   11130:         my %crshash;
                   11131:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11132:         if ($crshash{'internal.contentchange'} eq '') {
                   11133:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11134:             if ($change eq '') {
                   11135:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11136:                 $change = $crshash{'internal.created'};
                   11137:             }
                   11138:         } else {
                   11139:             $change = $crshash{'internal.contentchange'};
                   11140:         }
                   11141:         my $cachetime = 600;
                   11142:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11143:     }
                   11144:     return $change;
                   11145: }
                   11146: 
                   11147: sub devalidate_coursechange_cache {
                   11148:     my ($cnum,$cdom)=@_;
                   11149:     my $hashid=$cnum.':'.$cdom;
                   11150:     &devalidate_cache_new('crschange',$hashid);
                   11151: }
                   11152: 
1.31      www      11153: # ------------------------------------------------- Update symbolic store links
                   11154: 
                   11155: sub symblist {
                   11156:     my ($mapname,%newhash)=@_;
1.438     www      11157:     $mapname=&deversion(&declutter($mapname));
1.31      www      11158:     my %hash;
1.620     albertel 11159:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11160:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11161:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11162: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11163: 		next if ($url eq 'last_known'
                   11164: 			 && $env{'form.no_update_last_known'});
                   11165: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11166: 						    $newhash{$url}->[1],
                   11167: 						    $newhash{$url}->[0]);
1.191     harris41 11168:             }
1.31      www      11169:             if (untie(%hash)) {
                   11170: 		return 'ok';
                   11171:             }
                   11172:         }
                   11173:     }
                   11174:     return 'error';
1.212     www      11175: }
                   11176: 
                   11177: # --------------------------------------------------------------- Verify a symb
                   11178: 
                   11179: sub symbverify {
1.1190    raeburn  11180:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11181:     my $thisfn=$thisurl;
1.439     www      11182:     $thisfn=&declutter($thisfn);
1.215     www      11183: # direct jump to resource in page or to a sequence - will construct own symbs
                   11184:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11185: # check URL part
1.409     www      11186:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11187: 
1.431     www      11188:     unless ($url eq $thisfn) { return 0; }
1.213     www      11189: 
1.216     www      11190:     $symb=&symbclean($symb);
1.510     www      11191:     $thisurl=&deversion($thisurl);
1.439     www      11192:     $thisfn=&deversion($thisfn);
1.213     www      11193: 
                   11194:     my %bighash;
                   11195:     my $okay=0;
1.431     www      11196: 
1.620     albertel 11197:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11198:                             &GDBM_READER(),0640)) {
1.1204    raeburn  11199:         my $noclutter;
1.1032    raeburn  11200:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11201:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  11202:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11203:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11204:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11205:                 $noclutter = 1;
                   11206:             }
                   11207:         }
                   11208:         my $ids;
                   11209:         if ($noclutter) {
                   11210:             $ids=$bighash{'ids_'.$thisurl};
                   11211:         } else {
                   11212:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11213:         }
1.1102    raeburn  11214:         unless ($ids) {
                   11215:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   11216:             $ids=$bighash{$idkey};
1.216     www      11217:         }
                   11218:         if ($ids) {
                   11219: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  11220:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  11221:                 $symb =~ s/\?.+$//;
1.1202    raeburn  11222:             }
1.800     albertel 11223: 	    foreach my $id (split(/\,/,$ids)) {
                   11224: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11225:                if (
                   11226:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  11227:    eq $symb) {
                   11228:                    if (ref($encstate)) {
                   11229:                        $$encstate = $bighash{'encrypted_'.$id};
                   11230:                    }
1.620     albertel 11231: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  11232: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   11233:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  11234: 		       $okay=1;
1.1202    raeburn  11235:                        last;
1.582     albertel 11236: 		   }
                   11237: 	       }
1.216     www      11238: 	   }
                   11239:         }
1.213     www      11240: 	untie(%bighash);
                   11241:     }
                   11242:     return $okay;
1.31      www      11243: }
                   11244: 
1.210     www      11245: # --------------------------------------------------------------- Clean-up symb
                   11246: 
                   11247: sub symbclean {
                   11248:     my $symb=shift;
1.568     albertel 11249:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11250: # remove version from map
                   11251:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11252: 
1.210     www      11253: # remove version from URL
                   11254:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11255: 
1.507     www      11256: # remove wrapper
                   11257: 
1.510     www      11258:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11259:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11260:     return $symb;
1.409     www      11261: }
                   11262: 
                   11263: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11264: 
                   11265: sub encode_symb {
                   11266:     my ($map,$resid,$url)=@_;
                   11267:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11268: }
1.409     www      11269: 
                   11270: sub decode_symb {
1.568     albertel 11271:     my $symb=shift;
                   11272:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11273:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11274:     return (&fixversion($map),$resid,&fixversion($url));
                   11275: }
                   11276: 
                   11277: sub fixversion {
                   11278:     my $fn=shift;
1.609     banghart 11279:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11280:     my %bighash;
                   11281:     my $uri=&clutter($fn);
1.620     albertel 11282:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11283: # is this cached?
1.599     albertel 11284:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11285:     if (defined($cached)) { return $result; }
                   11286: # unfortunately not cached, or expired
1.620     albertel 11287:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11288: 	    &GDBM_READER(),0640)) {
                   11289:  	if ($bighash{'version_'.$uri}) {
                   11290:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11291:  	    unless (($version eq 'mostrecent') || 
                   11292: 		    ($version==&getversion($uri))) {
1.440     www      11293:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   11294:  	    }
                   11295:  	}
                   11296:  	untie %bighash;
1.413     www      11297:     }
1.599     albertel 11298:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      11299: }
                   11300: 
                   11301: sub deversion {
                   11302:     my $url=shift;
                   11303:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   11304:     return $url;
1.210     www      11305: }
                   11306: 
1.31      www      11307: # ------------------------------------------------------ Return symb list entry
                   11308: 
                   11309: sub symbread {
1.1282    raeburn  11310:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  11311:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  11312:     if (defined($env{$cache_str})) {
                   11313:         if ($ignorecachednull) {
                   11314:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   11315:         } else {
                   11316:             return $env{$cache_str};
                   11317:         }
                   11318:     }
1.242     www      11319: # no filename provided? try from environment
1.1265    raeburn  11320:     unless ($thisfn) {
1.620     albertel 11321:         if ($env{'request.symb'}) {
                   11322: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 11323: 	}
1.620     albertel 11324: 	$thisfn=$env{'request.filename'};
1.44      www      11325:     }
1.569     albertel 11326:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      11327: # is that filename actually a symb? Verify, clean, and return
                   11328:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 11329: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 11330: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 11331: 	}
1.242     www      11332:     }
1.44      www      11333:     $thisfn=declutter($thisfn);
1.31      www      11334:     my %hash;
1.37      www      11335:     my %bighash;
                   11336:     my $syval='';
1.620     albertel 11337:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  11338:         my $targetfn = $thisfn;
1.609     banghart 11339:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  11340:             $targetfn = 'adm/wrapper/'.$thisfn;
                   11341:         }
1.687     albertel 11342: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   11343: 	    $targetfn=$1;
                   11344: 	}
1.620     albertel 11345:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11346:                       &GDBM_READER(),0640)) {
1.481     raeburn  11347: 	    $syval=$hash{$targetfn};
1.37      www      11348:             untie(%hash);
                   11349:         }
                   11350: # ---------------------------------------------------------- There was an entry
                   11351:         if ($syval) {
1.601     albertel 11352: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 11353: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  11354: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11355: 		    #return $env{$cache_str}='';
1.601     albertel 11356: 		#}    
                   11357: 		#$syval.=$1;
                   11358: 	    #}
1.37      www      11359:         } else {
                   11360: # ------------------------------------------------------- Was not in symb table
1.620     albertel 11361:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11362:                             &GDBM_READER(),0640)) {
1.37      www      11363: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      11364:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      11365:               unless ($ids) { 
                   11366:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      11367:               }
                   11368:               unless ($ids) {
                   11369: # alias?
                   11370: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      11371:               }
1.37      www      11372:               if ($ids) {
                   11373: # ------------------------------------------------------------------- Has ID(s)
                   11374:                  my @possibilities=split(/\,/,$ids);
1.39      www      11375:                  if ($#possibilities==0) {
                   11376: # ----------------------------------------------- There is only one possibility
1.37      www      11377: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 11378: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11379: 						    $resid,$thisfn);
1.1282    raeburn  11380:                      if (ref($possibles) eq 'HASH') {
                   11381:                          $possibles->{$syval} = 1;    
                   11382:                      }
                   11383:                      if ($checkforblock) {
                   11384:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   11385:                          if (@blockers) {
                   11386:                              $syval = '';
                   11387:                              return;
                   11388:                          }
                   11389:                      }
                   11390:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      11391: # ------------------------------------------ There is more than one possibility
                   11392:                      my $realpossible=0;
1.800     albertel 11393:                      foreach my $id (@possibilities) {
                   11394: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  11395:                          my $canaccess;
                   11396:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   11397:                              $canaccess = 1;
                   11398:                          } else { 
                   11399:                              $canaccess = &allowed('bre',$file);
                   11400:                          }
                   11401:                          if ($canaccess) {
                   11402:          		     my ($mapid,$resid)=split(/\./,$id);
                   11403:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   11404:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   11405: 						             $resid,$thisfn);
                   11406:                                  if (ref($possibles) eq 'HASH') {
                   11407:                                      $possibles->{$syval} = 1;
                   11408:                                  }
                   11409:                                  if ($checkforblock) {
                   11410:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   11411:                                      unless (@blockers > 0) {
                   11412:                                          $syval = $poss_syval;
                   11413:                                          $realpossible++;
                   11414:                                      }
                   11415:                                  } else {
                   11416:                                      $syval = $poss_syval;
                   11417:                                      $realpossible++;
                   11418:                                  }
                   11419:                              }
1.39      www      11420: 			 }
1.191     harris41 11421:                      }
1.39      www      11422: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      11423:                  } else {
                   11424:                      $syval='';
1.37      www      11425:                  }
                   11426: 	      }
1.1282    raeburn  11427:               untie(%bighash);
1.481     raeburn  11428:            }
1.31      www      11429:         }
1.62      www      11430:         if ($syval) {
1.620     albertel 11431: 	    return $env{$cache_str}=$syval;
1.62      www      11432:         }
1.31      www      11433:     }
1.949     raeburn  11434:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 11435:     return $env{$cache_str}='';
1.31      www      11436: }
                   11437: 
                   11438: # ---------------------------------------------------------- Return random seed
                   11439: 
1.32      www      11440: sub numval {
                   11441:     my $txt=shift;
                   11442:     $txt=~tr/A-J/0-9/;
                   11443:     $txt=~tr/a-j/0-9/;
                   11444:     $txt=~tr/K-T/0-9/;
                   11445:     $txt=~tr/k-t/0-9/;
                   11446:     $txt=~tr/U-Z/0-5/;
                   11447:     $txt=~tr/u-z/0-5/;
                   11448:     $txt=~s/\D//g;
1.564     albertel 11449:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      11450:     return int($txt);
1.368     albertel 11451: }
                   11452: 
1.484     albertel 11453: sub numval2 {
                   11454:     my $txt=shift;
                   11455:     $txt=~tr/A-J/0-9/;
                   11456:     $txt=~tr/a-j/0-9/;
                   11457:     $txt=~tr/K-T/0-9/;
                   11458:     $txt=~tr/k-t/0-9/;
                   11459:     $txt=~tr/U-Z/0-5/;
                   11460:     $txt=~tr/u-z/0-5/;
                   11461:     $txt=~s/\D//g;
                   11462:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11463:     my $total;
                   11464:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 11465:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 11466:     return int($total);
                   11467: }
                   11468: 
1.575     albertel 11469: sub numval3 {
                   11470:     use integer;
                   11471:     my $txt=shift;
                   11472:     $txt=~tr/A-J/0-9/;
                   11473:     $txt=~tr/a-j/0-9/;
                   11474:     $txt=~tr/K-T/0-9/;
                   11475:     $txt=~tr/k-t/0-9/;
                   11476:     $txt=~tr/U-Z/0-5/;
                   11477:     $txt=~tr/u-z/0-5/;
                   11478:     $txt=~s/\D//g;
                   11479:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   11480:     my $total;
                   11481:     foreach my $val (@txts) { $total+=$val; }
                   11482:     if ($_64bit) { $total=(($total<<32)>>32); }
                   11483:     return $total;
                   11484: }
                   11485: 
1.675     albertel 11486: sub digest {
                   11487:     my ($data)=@_;
                   11488:     my $digest=&Digest::MD5::md5($data);
                   11489:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   11490:     my ($e,$f);
                   11491:     {
                   11492:         use integer;
                   11493:         $e=($a+$b);
                   11494:         $f=($c+$d);
                   11495:         if ($_64bit) {
                   11496:             $e=(($e<<32)>>32);
                   11497:             $f=(($f<<32)>>32);
                   11498:         }
                   11499:     }
                   11500:     if (wantarray) {
                   11501: 	return ($e,$f);
                   11502:     } else {
                   11503: 	my $g;
                   11504: 	{
                   11505: 	    use integer;
                   11506: 	    $g=($e+$f);
                   11507: 	    if ($_64bit) {
                   11508: 		$g=(($g<<32)>>32);
                   11509: 	    }
                   11510: 	}
                   11511: 	return $g;
                   11512:     }
                   11513: }
                   11514: 
1.368     albertel 11515: sub latest_rnd_algorithm_id {
1.675     albertel 11516:     return '64bit5';
1.366     albertel 11517: }
1.32      www      11518: 
1.503     albertel 11519: sub get_rand_alg {
                   11520:     my ($courseid)=@_;
1.790     albertel 11521:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 11522:     if ($courseid) {
1.620     albertel 11523: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 11524:     }
                   11525:     return &latest_rnd_algorithm_id();
                   11526: }
                   11527: 
1.562     albertel 11528: sub validCODE {
                   11529:     my ($CODE)=@_;
                   11530:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   11531:     return 0;
                   11532: }
                   11533: 
1.491     albertel 11534: sub getCODE {
1.620     albertel 11535:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 11536:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   11537: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   11538: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 11539: 	return $Apache::lonhomework::history{'resource.CODE'};
                   11540:     }
                   11541:     return undef;
                   11542: }
1.1133    foxr     11543: #
                   11544: #  Determines the random seed for a specific context:
                   11545: #
                   11546: # parameters:
                   11547: #   symb      - in course context the symb for the seed.
                   11548: #   course_id - The course id of the form domain_coursenum.
                   11549: #   domain    - Domain for the user.
                   11550: #   course    - Course for the user.
                   11551: #   cenv      - environment of the course.
                   11552: #
                   11553: # NOTE:
                   11554: #   All parameters are picked out of the environment if missing
                   11555: #   or not defined.
                   11556: #   If a symb cannot be determined the current time is used instead.
                   11557: #
                   11558: #  For a given well defined symb, courside, domain, username,
                   11559: #  and course environment, the seed is reproducible.
                   11560: #
1.31      www      11561: sub rndseed {
1.1133    foxr     11562:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 11563:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 11564:     if (!defined($symb)) {
1.366     albertel 11565: 	unless ($symb=$wsymb) { return time; }
                   11566:     }
1.1146    foxr     11567:     if (!defined $courseid) { 
                   11568: 	$courseid=$wcourseid; 
                   11569:     }
                   11570:     if (!defined $domain) { $domain=$wdomain; }
                   11571:     if (!defined $username) { $username=$wusername }
1.1133    foxr     11572: 
                   11573:     my $which;
                   11574:     if (defined($cenv->{'rndseed'})) {
                   11575: 	$which = $cenv->{'rndseed'};
                   11576:     } else {
                   11577: 	$which =&get_rand_alg($courseid);
                   11578:     }
1.491     albertel 11579:     if (defined(&getCODE())) {
1.1133    foxr     11580: 
1.675     albertel 11581: 	if ($which eq '64bit5') {
                   11582: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   11583: 	} elsif ($which eq '64bit4') {
1.575     albertel 11584: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   11585: 	} else {
                   11586: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   11587: 	}
1.675     albertel 11588:     } elsif ($which eq '64bit5') {
                   11589: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 11590:     } elsif ($which eq '64bit4') {
                   11591: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 11592:     } elsif ($which eq '64bit3') {
                   11593: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 11594:     } elsif ($which eq '64bit2') {
                   11595: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 11596:     } elsif ($which eq '64bit') {
                   11597: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   11598:     }
                   11599:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   11600: }
                   11601: 
                   11602: sub rndseed_32bit {
                   11603:     my ($symb,$courseid,$domain,$username)=@_;
                   11604:     {
                   11605: 	use integer;
                   11606: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   11607: 	my $symbseed=numval($symb) << 22;
                   11608: 	my $namechck=unpack("%32C*",$username) << 17;
                   11609: 	my $nameseed=numval($username) << 12;
                   11610: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   11611: 	my $courseseed=unpack("%32C*",$courseid);
                   11612: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 11613: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11614: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11615: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 11616: 	return $num;
                   11617:     }
                   11618: }
                   11619: 
                   11620: sub rndseed_64bit {
                   11621:     my ($symb,$courseid,$domain,$username)=@_;
                   11622:     {
                   11623: 	use integer;
                   11624: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   11625: 	my $symbseed=numval($symb) << 10;
                   11626: 	my $namechck=unpack("%32S*",$username);
                   11627: 	
                   11628: 	my $nameseed=numval($username) << 21;
                   11629: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   11630: 	my $courseseed=unpack("%32S*",$courseid);
                   11631: 	
                   11632: 	my $num1=$symbchck+$symbseed+$namechck;
                   11633: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11634: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11635: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 11636: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 11637: 	return "$num1,$num2";
1.155     albertel 11638:     }
1.366     albertel 11639: }
                   11640: 
1.443     albertel 11641: sub rndseed_64bit2 {
                   11642:     my ($symb,$courseid,$domain,$username)=@_;
                   11643:     {
                   11644: 	use integer;
                   11645: 	# strings need to be an even # of cahracters long, it it is odd the
                   11646:         # last characters gets thrown away
                   11647: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11648: 	my $symbseed=numval($symb) << 10;
                   11649: 	my $namechck=unpack("%32S*",$username.' ');
                   11650: 	
                   11651: 	my $nameseed=numval($username) << 21;
1.501     albertel 11652: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11653: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11654: 	
                   11655: 	my $num1=$symbchck+$symbseed+$namechck;
                   11656: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11657: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11658: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 11659: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 11660: 	return "$num1,$num2";
                   11661:     }
                   11662: }
                   11663: 
                   11664: sub rndseed_64bit3 {
                   11665:     my ($symb,$courseid,$domain,$username)=@_;
                   11666:     {
                   11667: 	use integer;
                   11668: 	# strings need to be an even # of cahracters long, it it is odd the
                   11669:         # last characters gets thrown away
                   11670: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11671: 	my $symbseed=numval2($symb) << 10;
                   11672: 	my $namechck=unpack("%32S*",$username.' ');
                   11673: 	
                   11674: 	my $nameseed=numval2($username) << 21;
1.443     albertel 11675: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11676: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11677: 	
                   11678: 	my $num1=$symbchck+$symbseed+$namechck;
                   11679: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11680: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11681: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 11682: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11683: 	
1.503     albertel 11684: 	return "$num1:$num2";
1.443     albertel 11685:     }
                   11686: }
                   11687: 
1.575     albertel 11688: sub rndseed_64bit4 {
                   11689:     my ($symb,$courseid,$domain,$username)=@_;
                   11690:     {
                   11691: 	use integer;
                   11692: 	# strings need to be an even # of cahracters long, it it is odd the
                   11693:         # last characters gets thrown away
                   11694: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   11695: 	my $symbseed=numval3($symb) << 10;
                   11696: 	my $namechck=unpack("%32S*",$username.' ');
                   11697: 	
                   11698: 	my $nameseed=numval3($username) << 21;
                   11699: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   11700: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11701: 	
                   11702: 	my $num1=$symbchck+$symbseed+$namechck;
                   11703: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 11704: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   11705: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 11706: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      11707: 	
1.575     albertel 11708: 	return "$num1:$num2";
                   11709:     }
                   11710: }
                   11711: 
1.675     albertel 11712: sub rndseed_64bit5 {
                   11713:     my ($symb,$courseid,$domain,$username)=@_;
                   11714:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   11715:     return "$num1:$num2";
                   11716: }
                   11717: 
1.366     albertel 11718: sub rndseed_CODE_64bit {
                   11719:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 11720:     {
1.366     albertel 11721: 	use integer;
1.443     albertel 11722: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 11723: 	my $symbseed=numval2($symb);
1.491     albertel 11724: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11725: 	my $CODEseed=numval(&getCODE());
1.443     albertel 11726: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 11727: 	my $num1=$symbseed+$CODEchck;
                   11728: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11729: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11730: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 11731: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11732: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 11733: 	return "$num1:$num2";
1.366     albertel 11734:     }
                   11735: }
                   11736: 
1.575     albertel 11737: sub rndseed_CODE_64bit4 {
                   11738:     my ($symb,$courseid,$domain,$username)=@_;
                   11739:     {
                   11740: 	use integer;
                   11741: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   11742: 	my $symbseed=numval3($symb);
                   11743: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   11744: 	my $CODEseed=numval3(&getCODE());
                   11745: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   11746: 	my $num1=$symbseed+$CODEchck;
                   11747: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 11748: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   11749: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 11750: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   11751: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   11752: 	return "$num1:$num2";
                   11753:     }
                   11754: }
                   11755: 
1.675     albertel 11756: sub rndseed_CODE_64bit5 {
                   11757:     my ($symb,$courseid,$domain,$username)=@_;
                   11758:     my $code = &getCODE();
                   11759:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   11760:     return "$num1:$num2";
                   11761: }
                   11762: 
1.366     albertel 11763: sub setup_random_from_rndseed {
                   11764:     my ($rndseed)=@_;
1.503     albertel 11765:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  11766:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   11767:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   11768:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   11769:         } else {
                   11770:             &Math::Random::random_set_seed($num1,$num2);
                   11771:         }
1.366     albertel 11772:     } else {
                   11773: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 11774:     }
1.36      albertel 11775: }
                   11776: 
1.474     albertel 11777: sub latest_receipt_algorithm_id {
1.835     albertel 11778:     return 'receipt3';
1.474     albertel 11779: }
                   11780: 
1.480     www      11781: sub recunique {
                   11782:     my $fucourseid=shift;
                   11783:     my $unique;
1.835     albertel 11784:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   11785: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11786: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      11787:     } else {
                   11788: 	$unique=$perlvar{'lonReceipt'};
                   11789:     }
                   11790:     return unpack("%32C*",$unique);
                   11791: }
                   11792: 
                   11793: sub recprefix {
                   11794:     my $fucourseid=shift;
                   11795:     my $prefix;
1.835     albertel 11796:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   11797: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 11798: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      11799:     } else {
                   11800: 	$prefix=$perlvar{'lonHostID'};
                   11801:     }
                   11802:     return unpack("%32C*",$prefix);
                   11803: }
                   11804: 
1.76      www      11805: sub ireceipt {
1.474     albertel 11806:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 11807: 
                   11808:     my $return =&recprefix($fucourseid).'-';
                   11809: 
                   11810:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   11811: 	$env{'request.state'} eq 'construct') {
                   11812: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   11813: 	return $return;
                   11814:     }
                   11815: 
1.76      www      11816:     my $cuname=unpack("%32C*",$funame);
                   11817:     my $cudom=unpack("%32C*",$fudom);
                   11818:     my $cucourseid=unpack("%32C*",$fucourseid);
                   11819:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      11820:     my $cunique=&recunique($fucourseid);
1.474     albertel 11821:     my $cpart=unpack("%32S*",$part);
1.835     albertel 11822:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   11823: 
1.790     albertel 11824: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 11825: 			       
                   11826: 	$return.= ($cunique%$cuname+
                   11827: 		   $cunique%$cudom+
                   11828: 		   $cusymb%$cuname+
                   11829: 		   $cusymb%$cudom+
                   11830: 		   $cucourseid%$cuname+
                   11831: 		   $cucourseid%$cudom+
                   11832: 		   $cpart%$cuname+
                   11833: 		   $cpart%$cudom);
                   11834:     } else {
                   11835: 	$return.= ($cunique%$cuname+
                   11836: 		   $cunique%$cudom+
                   11837: 		   $cusymb%$cuname+
                   11838: 		   $cusymb%$cudom+
                   11839: 		   $cucourseid%$cuname+
                   11840: 		   $cucourseid%$cudom);
                   11841:     }
                   11842:     return $return;
1.76      www      11843: }
                   11844: 
                   11845: sub receipt {
1.474     albertel 11846:     my ($part)=@_;
1.790     albertel 11847:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 11848:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      11849: }
1.260     ng       11850: 
1.790     albertel 11851: sub whichuser {
                   11852:     my ($passedsymb)=@_;
                   11853:     my ($symb,$courseid,$domain,$name,$publicuser);
                   11854:     if (defined($env{'form.grade_symb'})) {
                   11855: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   11856: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   11857: 	if (!$allowed &&
                   11858: 	    exists($env{'request.course.sec'}) &&
                   11859: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   11860: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   11861: 			      '/'.$env{'request.course.sec'});
                   11862: 	}
                   11863: 	if ($allowed) {
                   11864: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   11865: 	    $courseid=$tmp_courseid;
                   11866: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   11867: 	    ($name)=&get_env_multiple('form.grade_username');
                   11868: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   11869: 	}
                   11870:     }
                   11871:     if (!$passedsymb) {
                   11872: 	$symb=&symbread();
                   11873:     } else {
                   11874: 	$symb=$passedsymb;
                   11875:     }
                   11876:     $courseid=$env{'request.course.id'};
                   11877:     $domain=$env{'user.domain'};
                   11878:     $name=$env{'user.name'};
                   11879:     if ($name eq 'public' && $domain eq 'public') {
                   11880: 	if (!defined($env{'form.username'})) {
                   11881: 	    $env{'form.username'}.=time.rand(10000000);
                   11882: 	}
                   11883: 	$name.=$env{'form.username'};
                   11884:     }
                   11885:     return ($symb,$courseid,$domain,$name,$publicuser);
                   11886: 
                   11887: }
                   11888: 
1.36      albertel 11889: # ------------------------------------------------------------ Serves up a file
1.472     albertel 11890: # returns either the contents of the file or 
                   11891: # -1 if the file doesn't exist
1.481     raeburn  11892: #
                   11893: # if the target is a file that was uploaded via DOCS, 
                   11894: # a check will be made to see if a current copy exists on the local server,
                   11895: # if it does this will be served, otherwise a copy will be retrieved from
                   11896: # the home server for the course and stored in /home/httpd/html/userfiles on
                   11897: # the local server.   
1.472     albertel 11898: 
1.36      albertel 11899: sub getfile {
1.538     albertel 11900:     my ($file) = @_;
1.609     banghart 11901:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 11902:     &repcopy($file);
                   11903:     return &readfile($file);
                   11904: }
                   11905: 
                   11906: sub repcopy_userfile {
                   11907:     my ($file)=@_;
1.1142    raeburn  11908:     my $londocroot = $perlvar{'lonDocRoot'};
                   11909:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  11910:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 11911:     my ($cdom,$cnum,$filename) = 
1.811     albertel 11912: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 11913:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   11914:     if (-e "$file") {
1.828     www      11915: # we already have a local copy, check it out
1.538     albertel 11916: 	my @fileinfo = stat($file);
1.828     www      11917: 	my $rtncode;
                   11918: 	my $info;
1.538     albertel 11919: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 11920: 	if ($lwpresp ne 'ok') {
1.828     www      11921: # there is no such file anymore, even though we had a local copy
1.482     albertel 11922: 	    if ($rtncode eq '404') {
1.538     albertel 11923: 		unlink($file);
1.482     albertel 11924: 	    }
                   11925: 	    return -1;
                   11926: 	}
                   11927: 	if ($info < $fileinfo[9]) {
1.828     www      11928: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  11929: 	    return 'ok';
1.828     www      11930: 	} else {
                   11931: # the file is outdated, get rid of it
                   11932: 	    unlink($file);
1.482     albertel 11933: 	}
1.828     www      11934:     }
                   11935: # one way or the other, at this point, we don't have the file
                   11936: # construct the correct path for the file
                   11937:     my @parts = ($cdom,$cnum); 
                   11938:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   11939: 	push @parts, split(/\//,$1);
                   11940:     }
                   11941:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   11942:     foreach my $part (@parts) {
                   11943: 	$path .= '/'.$part;
                   11944: 	if (!-e $path) {
                   11945: 	    mkdir($path,0770);
1.482     albertel 11946: 	}
                   11947:     }
1.828     www      11948: # now the path exists for sure
                   11949: # get a user agent
                   11950:     my $ua=new LWP::UserAgent;
                   11951:     my $transferfile=$file.'.in.transfer';
                   11952: # FIXME: this should flock
                   11953:     if (-e $transferfile) { return 'ok'; }
                   11954:     my $request;
                   11955:     $uri=~s/^\///;
1.980     raeburn  11956:     my $homeserver = &homeserver($cnum,$cdom);
                   11957:     my $protocol = $protocol{$homeserver};
                   11958:     $protocol = 'http' if ($protocol ne 'https');
                   11959:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      11960:     my $response=$ua->request($request,$transferfile);
                   11961: # did it work?
                   11962:     if ($response->is_error()) {
                   11963: 	unlink($transferfile);
                   11964: 	&logthis("Userfile repcopy failed for $uri");
                   11965: 	return -1;
                   11966:     }
                   11967: # worked, rename the transfer file
                   11968:     rename($transferfile,$file);
1.607     raeburn  11969:     return 'ok';
1.481     raeburn  11970: }
                   11971: 
1.517     albertel 11972: sub tokenwrapper {
                   11973:     my $uri=shift;
1.980     raeburn  11974:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 11975:     $uri=~s|^/||;
1.620     albertel 11976:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 11977:     my $token=$1;
1.552     albertel 11978:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   11979:     if ($udom && $uname && $file) {
                   11980: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  11981:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  11982:         my $homeserver = &homeserver($uname,$udom);
                   11983:         my $protocol = $protocol{$homeserver};
                   11984:         $protocol = 'http' if ($protocol ne 'https');
                   11985:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 11986:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   11987:                                '&tokenissued='.$perlvar{'lonHostID'};
                   11988:     } else {
                   11989:         return '/adm/notfound.html';
                   11990:     }
                   11991: }
                   11992: 
1.828     www      11993: # call with reqtype HEAD: get last modification time
                   11994: # call with reqtype GET: get the file contents
                   11995: # Do not call this with reqtype GET for large files! It loads everything into memory
                   11996: #
1.481     raeburn  11997: sub getuploaded {
                   11998:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   11999:     $uri=~s/^\///;
1.980     raeburn  12000:     my $homeserver = &homeserver($cnum,$cdom);
                   12001:     my $protocol = $protocol{$homeserver};
                   12002:     $protocol = 'http' if ($protocol ne 'https');
                   12003:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12004:     my $ua=new LWP::UserAgent;
                   12005:     my $request=new HTTP::Request($reqtype,$uri);
                   12006:     my $response=$ua->request($request);
                   12007:     $$rtncode = $response->code;
1.482     albertel 12008:     if (! $response->is_success()) {
                   12009: 	return 'failed';
                   12010:     }      
                   12011:     if ($reqtype eq 'HEAD') {
1.486     www      12012: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12013:     } elsif ($reqtype eq 'GET') {
                   12014: 	$$info = $response->content;
1.472     albertel 12015:     }
1.482     albertel 12016:     return 'ok';
1.36      albertel 12017: }
                   12018: 
1.481     raeburn  12019: sub readfile {
                   12020:     my $file = shift;
                   12021:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12022:     my $fh;
                   12023:     open($fh,"<$file");
                   12024:     my $a='';
1.800     albertel 12025:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12026:     return $a;
                   12027: }
                   12028: 
1.36      albertel 12029: sub filelocation {
1.590     banghart 12030:     my ($dir,$file) = @_;
                   12031:     my $location;
                   12032:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12033: 
                   12034:     if ($file =~ m-^/adm/-) {
                   12035: 	$file=~s-^/adm/wrapper/-/-;
                   12036: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12037:     }
1.882     albertel 12038: 
1.1139    www      12039:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12040:         $location = $file;
1.609     banghart 12041:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12042:         my ($udom,$uname,$filename)=
1.811     albertel 12043:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12044:         my $home=&homeserver($uname,$udom);
                   12045:         my $is_me=0;
                   12046:         my @ids=&current_machine_ids();
                   12047:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12048:         if ($is_me) {
1.1117    foxr     12049:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12050:         } else {
                   12051:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12052:   	      $udom.'/'.$uname.'/'.$filename;
                   12053:         }
1.882     albertel 12054:     } elsif ($file =~ m-^/adm/-) {
                   12055: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12056:     } else {
                   12057:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12058:         $file=~s:^/(res|priv)/:/:;
                   12059:         my $space=$1;
1.590     banghart 12060:         if ( !( $file =~ m:^/:) ) {
                   12061:             $location = $dir. '/'.$file;
                   12062:         } else {
1.1142    raeburn  12063:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12064:         }
1.59      albertel 12065:     }
1.590     banghart 12066:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12067:     while ($location=~m{/\.\./}) {
                   12068: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12069: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12070: 	} else {
                   12071: 	    $location=~ s{/\.\./}{/}g;
                   12072: 	}
                   12073:     } #remove dir/..
1.590     banghart 12074:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12075:     return $location;
1.46      www      12076: }
1.36      albertel 12077: 
1.46      www      12078: sub hreflocation {
                   12079:     my ($dir,$file)=@_;
1.980     raeburn  12080:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12081: 	$file=filelocation($dir,$file);
1.700     albertel 12082:     } elsif ($file=~m-^/adm/-) {
                   12083: 	$file=~s-^/adm/wrapper/-/-;
                   12084: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12085:     }
                   12086:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12087: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12088:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12089: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12090: 	        {/uploaded/$1/$2/}x;
1.46      www      12091:     }
1.913     albertel 12092:     if ($file=~ m{^/userfiles/}) {
                   12093: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12094:     }
1.462     albertel 12095:     return $file;
1.465     albertel 12096: }
                   12097: 
1.1139    www      12098: 
                   12099: 
                   12100: 
                   12101: 
1.465     albertel 12102: sub current_machine_domains {
1.853     albertel 12103:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12104: }
                   12105: 
                   12106: sub machine_domains {
                   12107:     my ($hostname) = @_;
1.465     albertel 12108:     my @domains;
1.838     albertel 12109:     my %hostname = &all_hostnames();
1.465     albertel 12110:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12111: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12112: 	if ($hostname eq $name) {
1.844     albertel 12113: 	    push(@domains,&host_domain($id));
1.465     albertel 12114: 	}
                   12115:     }
                   12116:     return @domains;
                   12117: }
                   12118: 
                   12119: sub current_machine_ids {
1.853     albertel 12120:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12121: }
                   12122: 
                   12123: sub machine_ids {
                   12124:     my ($hostname) = @_;
                   12125:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12126:     my @ids;
1.888     albertel 12127:     my %name_to_host = &all_names();
1.889     albertel 12128:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12129: 	return @{ $name_to_host{$hostname} };
                   12130:     }
                   12131:     return;
1.31      www      12132: }
                   12133: 
1.824     raeburn  12134: sub additional_machine_domains {
                   12135:     my @domains;
                   12136:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12137:     while( my $line = <$fh>) {
                   12138:         $line =~ s/\s//g;
                   12139:         push(@domains,$line);
                   12140:     }
                   12141:     return @domains;
                   12142: }
                   12143: 
                   12144: sub default_login_domain {
                   12145:     my $domain = $perlvar{'lonDefDomain'};
                   12146:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12147:     foreach my $posdom (&current_machine_domains(),
                   12148:                         &additional_machine_domains()) {
                   12149:         if (lc($posdom) eq lc($testdomain)) {
                   12150:             $domain=$posdom;
                   12151:             last;
                   12152:         }
                   12153:     }
                   12154:     return $domain;
                   12155: }
                   12156: 
1.31      www      12157: # ------------------------------------------------------------- Declutters URLs
                   12158: 
                   12159: sub declutter {
                   12160:     my $thisfn=shift;
1.569     albertel 12161:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  12162:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12163:         $thisfn=~s{^/home/httpd/html}{};
                   12164:     }
1.31      www      12165:     $thisfn=~s/^\///;
1.697     albertel 12166:     $thisfn=~s|^adm/wrapper/||;
                   12167:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12168:     $thisfn=~s/^res\///;
1.1172    bisitz   12169:     $thisfn=~s/^priv\///;
1.1032    raeburn  12170:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12171:         $thisfn=~s/\?.+$//;
                   12172:     }
1.268     www      12173:     return $thisfn;
                   12174: }
                   12175: 
                   12176: # ------------------------------------------------------------- Clutter up URLs
                   12177: 
                   12178: sub clutter {
                   12179:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12180:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12181: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12182:        $thisfn='/res'.$thisfn; 
                   12183:     }
1.1031    raeburn  12184:     if ($thisfn !~m|^/adm|) {
                   12185: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12186: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12187: 	} else {
                   12188: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12189: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12190: 	    if ($embstyle eq 'ssi'
                   12191: 		|| ($embstyle eq 'hdn')
                   12192: 		|| ($embstyle eq 'rat')
                   12193: 		|| ($embstyle eq 'prv')
                   12194: 		|| ($embstyle eq 'ign')) {
                   12195: 		#do nothing with these
                   12196: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12197: 		|| ($embstyle eq 'emb')
                   12198: 		|| ($embstyle eq 'wrp')) {
                   12199: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12200: 	    } elsif ($embstyle eq 'unk'
                   12201: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12202: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12203: 	    } else {
1.718     www      12204: #		&logthis("Got a blank emb style");
1.695     albertel 12205: 	    }
1.694     albertel 12206: 	}
                   12207:     }
1.31      www      12208:     return $thisfn;
1.12      www      12209: }
                   12210: 
1.787     albertel 12211: sub clutter_with_no_wrapper {
                   12212:     my $uri = &clutter(shift);
                   12213:     if ($uri =~ m-^/adm/-) {
                   12214: 	$uri =~ s-^/adm/wrapper/-/-;
                   12215: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12216:     }
                   12217:     return $uri;
                   12218: }
                   12219: 
1.557     albertel 12220: sub freeze_escape {
                   12221:     my ($value)=@_;
                   12222:     if (ref($value)) {
                   12223: 	$value=&nfreeze($value);
                   12224: 	return '__FROZEN__'.&escape($value);
                   12225:     }
                   12226:     return &escape($value);
                   12227: }
                   12228: 
1.11      www      12229: 
1.557     albertel 12230: sub thaw_unescape {
                   12231:     my ($value)=@_;
                   12232:     if ($value =~ /^__FROZEN__/) {
                   12233: 	substr($value,0,10,undef);
                   12234: 	$value=&unescape($value);
                   12235: 	return &thaw($value);
                   12236:     }
                   12237:     return &unescape($value);
                   12238: }
                   12239: 
1.436     albertel 12240: sub correct_line_ends {
                   12241:     my ($result)=@_;
                   12242:     $$result =~s/\r\n/\n/mg;
                   12243:     $$result =~s/\r/\n/mg;
1.415     albertel 12244: }
1.1       albertel 12245: # ================================================================ Main Program
                   12246: 
1.184     www      12247: sub goodbye {
1.204     albertel 12248:    &logthis("Starting Shut down");
1.443     albertel 12249: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12250:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12251: #converted
1.599     albertel 12252: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12253:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12254: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12255: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12256: #1.1 only
1.870     albertel 12257: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12258: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12259: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12260: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12261:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12262:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12263:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12264:    &flushcourselogs();
                   12265:    &logthis("Shutting down");
                   12266: }
                   12267: 
1.852     albertel 12268: sub get_dns {
1.1210    raeburn  12269:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12270:     if (!$ignore_cache) {
                   12271: 	my ($content,$cached)=
                   12272: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12273: 	if ($cached) {
1.1210    raeburn  12274: 	    &$func($content,$hashref);
1.869     albertel 12275: 	    return;
                   12276: 	}
                   12277:     }
                   12278: 
                   12279:     my %alldns;
1.852     albertel 12280:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12281:     foreach my $dns (<$config>) {
                   12282: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12283:         my $line = $1;
                   12284:         my ($host,$protocol) = split(/:/,$line);
                   12285:         if ($protocol ne 'https') {
                   12286:             $protocol = 'http';
                   12287:         }
                   12288: 	$alldns{$host} = $protocol;
1.869     albertel 12289:     }
                   12290:     while (%alldns) {
1.1263    raeburn  12291: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 12292: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  12293:         $ua->timeout(30);
1.979     raeburn  12294: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 12295: 	my $response=$ua->request($request);
1.979     raeburn  12296:         delete($alldns{$dns});
1.852     albertel 12297: 	next if ($response->is_error());
                   12298: 	my @content = split("\n",$response->content);
1.1210    raeburn  12299: 	unless ($nocache) {
1.1219    raeburn  12300: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  12301: 	}
                   12302: 	&$func(\@content,$hashref);
1.869     albertel 12303: 	return;
1.852     albertel 12304:     }
                   12305:     close($config);
1.871     albertel 12306:     my $which = (split('/',$url))[3];
                   12307:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   12308:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 12309:     my @content = <$config>;
1.1210    raeburn  12310:     &$func(\@content,$hashref);
                   12311:     return;
                   12312: }
                   12313: 
                   12314: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  12315: sub parse_dns_checksums_tab {
1.1210    raeburn  12316:     my ($lines,$hashref) = @_;
1.1264    raeburn  12317:     my $lonhost = $perlvar{'lonHostID'};
                   12318:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  12319:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  12320:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   12321:     my $webconfdir = '/etc/httpd/conf';
                   12322:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   12323:         $webconfdir = '/etc/apache2';
                   12324:     } elsif ($distro =~ /^sles(\d+)$/) {
                   12325:         if ($1 >= 10) {
                   12326:             $webconfdir = '/etc/apache2';
                   12327:         }
                   12328:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   12329:         if ($1 >= 10.0) {
                   12330:             $webconfdir = '/etc/apache2';
                   12331:         }
                   12332:     }
1.1210    raeburn  12333:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12334:     my (%chksum,%revnum);
                   12335:     if (ref($lines) eq 'ARRAY') {
                   12336:         chomp(@{$lines});
1.1238    raeburn  12337:         my $version = shift(@{$lines});
                   12338:         if ($version eq $release) {  
1.1210    raeburn  12339:             foreach my $line (@{$lines}) {
1.1238    raeburn  12340:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  12341:                 if ($file =~ m{^/etc/httpd/conf}) {
                   12342:                     if ($webconfdir eq '/etc/apache2') {
                   12343:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   12344:                     }
                   12345:                 }
1.1238    raeburn  12346:                 $chksum{$file} = $shasum;
                   12347:                 $revnum{$file} = $version;
1.1210    raeburn  12348:             }
                   12349:             if (ref($hashref) eq 'HASH') {
                   12350:                 %{$hashref} = (
                   12351:                                 sums     => \%chksum,
                   12352:                                 versions => \%revnum,
                   12353:                               );
                   12354:             }
                   12355:         }
                   12356:     }
1.869     albertel 12357:     return;
1.852     albertel 12358: }
1.1210    raeburn  12359: 
                   12360: sub fetch_dns_checksums {
1.1238    raeburn  12361:     my %checksums;
                   12362:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  12363:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  12364:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   12365:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  12366:              \%checksums);
1.1210    raeburn  12367:     return \%checksums;
                   12368: }
                   12369: 
1.327     albertel 12370: # ------------------------------------------------------------ Read domain file
                   12371: {
1.852     albertel 12372:     my $loaded;
1.846     albertel 12373:     my %domain;
                   12374: 
1.852     albertel 12375:     sub parse_domain_tab {
                   12376: 	my ($lines) = @_;
                   12377: 	foreach my $line (@$lines) {
                   12378: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      12379: 
1.846     albertel 12380: 	    chomp($line);
1.852     albertel 12381: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 12382: 	    my %this_domain;
                   12383: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   12384: 			       'lang_def', 'city', 'longi', 'lati',
                   12385: 			       'primary') {
                   12386: 		$this_domain{$field} = shift(@elements);
                   12387: 	    }
                   12388: 	    $domain{$name} = \%this_domain;
1.852     albertel 12389: 	}
                   12390:     }
1.864     albertel 12391: 
                   12392:     sub reset_domain_info {
                   12393: 	undef($loaded);
                   12394: 	undef(%domain);
                   12395:     }
                   12396: 
1.852     albertel 12397:     sub load_domain_tab {
1.869     albertel 12398: 	my ($ignore_cache) = @_;
                   12399: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 12400: 	my $fh;
                   12401: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   12402: 	    my @lines = <$fh>;
                   12403: 	    &parse_domain_tab(\@lines);
1.448     albertel 12404: 	}
1.852     albertel 12405: 	close($fh);
                   12406: 	$loaded = 1;
1.327     albertel 12407:     }
1.846     albertel 12408: 
                   12409:     sub domain {
1.852     albertel 12410: 	&load_domain_tab() if (!$loaded);
                   12411: 
1.846     albertel 12412: 	my ($name,$what) = @_;
                   12413: 	return if ( !exists($domain{$name}) );
                   12414: 
                   12415: 	if (!$what) {
                   12416: 	    return $domain{$name}{'description'};
                   12417: 	}
                   12418: 	return $domain{$name}{$what};
                   12419:     }
1.974     raeburn  12420: 
                   12421:     sub domain_info {
                   12422:         &load_domain_tab() if (!$loaded);
                   12423:         return %domain;
                   12424:     }
                   12425: 
1.327     albertel 12426: }
                   12427: 
                   12428: 
1.1       albertel 12429: # ------------------------------------------------------------- Read hosts file
                   12430: {
1.838     albertel 12431:     my %hostname;
1.844     albertel 12432:     my %hostdom;
1.845     albertel 12433:     my %libserv;
1.852     albertel 12434:     my $loaded;
1.888     albertel 12435:     my %name_to_host;
1.1074    raeburn  12436:     my %internetdom;
1.1107    raeburn  12437:     my %LC_dns_serv;
1.852     albertel 12438: 
                   12439:     sub parse_hosts_tab {
                   12440: 	my ($file) = @_;
                   12441: 	foreach my $configline (@$file) {
                   12442: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  12443:             chomp($configline);
                   12444: 	    if ($configline =~ /^\^/) {
                   12445:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   12446:                     $LC_dns_serv{$1} = 1;
                   12447:                 }
                   12448:                 next;
                   12449:             }
1.1074    raeburn  12450: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 12451: 	    $name=~s/\s//g;
                   12452: 	    if ($id && $domain && $role && $name) {
                   12453: 		$hostname{$id}=$name;
1.888     albertel 12454: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 12455: 		$hostdom{$id}=$domain;
                   12456: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  12457:                 if (defined($protocol)) {
                   12458:                     if ($protocol eq 'https') {
                   12459:                         $protocol{$id} = $protocol;
                   12460:                     } else {
                   12461:                         $protocol{$id} = 'http'; 
                   12462:                     }
1.968     raeburn  12463:                 } else {
1.969     raeburn  12464:                     $protocol{$id} = 'http';
1.968     raeburn  12465:                 }
1.1074    raeburn  12466:                 if (defined($intdom)) {
                   12467:                     $internetdom{$id} = $intdom;
                   12468:                 }
1.852     albertel 12469: 	    }
                   12470: 	}
                   12471:     }
1.864     albertel 12472:     
                   12473:     sub reset_hosts_info {
1.897     albertel 12474: 	&purge_remembered();
1.864     albertel 12475: 	&reset_domain_info();
                   12476: 	&reset_hosts_ip_info();
1.892     albertel 12477: 	undef(%name_to_host);
1.864     albertel 12478: 	undef(%hostname);
                   12479: 	undef(%hostdom);
                   12480: 	undef(%libserv);
                   12481: 	undef($loaded);
                   12482:     }
1.1       albertel 12483: 
1.852     albertel 12484:     sub load_hosts_tab {
1.869     albertel 12485: 	my ($ignore_cache) = @_;
                   12486: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 12487: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12488: 	my @config = <$config>;
                   12489: 	&parse_hosts_tab(\@config);
                   12490: 	close($config);
                   12491: 	$loaded=1;
1.1       albertel 12492:     }
1.852     albertel 12493: 
1.838     albertel 12494:     sub hostname {
1.852     albertel 12495: 	&load_hosts_tab() if (!$loaded);
                   12496: 
1.838     albertel 12497: 	my ($lonid) = @_;
                   12498: 	return $hostname{$lonid};
                   12499:     }
1.845     albertel 12500: 
1.838     albertel 12501:     sub all_hostnames {
1.852     albertel 12502: 	&load_hosts_tab() if (!$loaded);
                   12503: 
1.838     albertel 12504: 	return %hostname;
                   12505:     }
1.845     albertel 12506: 
1.888     albertel 12507:     sub all_names {
                   12508: 	&load_hosts_tab() if (!$loaded);
                   12509: 
                   12510: 	return %name_to_host;
                   12511:     }
                   12512: 
1.974     raeburn  12513:     sub all_host_domain {
                   12514:         &load_hosts_tab() if (!$loaded);
                   12515:         return %hostdom;
                   12516:     }
                   12517: 
1.845     albertel 12518:     sub is_library {
1.852     albertel 12519: 	&load_hosts_tab() if (!$loaded);
                   12520: 
1.845     albertel 12521: 	return exists($libserv{$_[0]});
                   12522:     }
                   12523: 
                   12524:     sub all_library {
1.852     albertel 12525: 	&load_hosts_tab() if (!$loaded);
                   12526: 
1.845     albertel 12527: 	return %libserv;
                   12528:     }
                   12529: 
1.1062    droeschl 12530:     sub unique_library {
                   12531: 	#2x reverse removes all hostnames that appear more than once
                   12532:         my %unique = reverse &all_library();
                   12533:         return reverse %unique;
                   12534:     }
                   12535: 
1.841     albertel 12536:     sub get_servers {
1.852     albertel 12537: 	&load_hosts_tab() if (!$loaded);
                   12538: 
1.841     albertel 12539: 	my ($domain,$type) = @_;
                   12540: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   12541: 	                                          : %hostname;
                   12542: 	my %result;
1.842     albertel 12543: 	if (ref($domain) eq 'ARRAY') {
                   12544: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 12545: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 12546: 		    $result{$host} = $hostname;
                   12547: 		}
                   12548: 	    }
                   12549: 	} else {
                   12550: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   12551: 		if ($hostdom{$host} eq $domain) {
                   12552: 		    $result{$host} = $hostname;
                   12553: 		}
1.841     albertel 12554: 	    }
                   12555: 	}
                   12556: 	return %result;
                   12557:     }
1.845     albertel 12558: 
1.1062    droeschl 12559:     sub get_unique_servers {
                   12560:         my %unique = reverse &get_servers(@_);
                   12561: 	return reverse %unique;
                   12562:     }
                   12563: 
1.844     albertel 12564:     sub host_domain {
1.852     albertel 12565: 	&load_hosts_tab() if (!$loaded);
                   12566: 
1.844     albertel 12567: 	my ($lonid) = @_;
                   12568: 	return $hostdom{$lonid};
                   12569:     }
                   12570: 
1.841     albertel 12571:     sub all_domains {
1.852     albertel 12572: 	&load_hosts_tab() if (!$loaded);
                   12573: 
1.841     albertel 12574: 	my %seen;
                   12575: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   12576: 	return @uniq;
                   12577:     }
1.1074    raeburn  12578: 
                   12579:     sub internet_dom {
                   12580:         &load_hosts_tab() if (!$loaded);
                   12581: 
                   12582:         my ($lonid) = @_;
                   12583:         return $internetdom{$lonid};
                   12584:     }
1.1107    raeburn  12585: 
                   12586:     sub is_LC_dns {
                   12587:         &load_hosts_tab() if (!$loaded);
                   12588: 
                   12589:         my ($hostname) = @_;
                   12590:         return exists($LC_dns_serv{$hostname});
                   12591:     }
                   12592: 
1.1       albertel 12593: }
                   12594: 
1.847     albertel 12595: { 
                   12596:     my %iphost;
1.856     albertel 12597:     my %name_to_ip;
                   12598:     my %lonid_to_ip;
1.869     albertel 12599: 
1.847     albertel 12600:     sub get_hosts_from_ip {
                   12601: 	my ($ip) = @_;
                   12602: 	my %iphosts = &get_iphost();
                   12603: 	if (ref($iphosts{$ip})) {
                   12604: 	    return @{$iphosts{$ip}};
                   12605: 	}
                   12606: 	return;
1.839     albertel 12607:     }
1.864     albertel 12608:     
                   12609:     sub reset_hosts_ip_info {
                   12610: 	undef(%iphost);
                   12611: 	undef(%name_to_ip);
                   12612: 	undef(%lonid_to_ip);
                   12613:     }
1.856     albertel 12614: 
                   12615:     sub get_host_ip {
                   12616: 	my ($lonid) = @_;
                   12617: 	if (exists($lonid_to_ip{$lonid})) {
                   12618: 	    return $lonid_to_ip{$lonid};
                   12619: 	}
                   12620: 	my $name=&hostname($lonid);
                   12621:    	my $ip = gethostbyname($name);
                   12622: 	return if (!$ip || length($ip) ne 4);
                   12623: 	$ip=inet_ntoa($ip);
                   12624: 	$name_to_ip{$name}   = $ip;
                   12625: 	$lonid_to_ip{$lonid} = $ip;
                   12626: 	return $ip;
                   12627:     }
1.847     albertel 12628:     
                   12629:     sub get_iphost {
1.869     albertel 12630: 	my ($ignore_cache) = @_;
1.894     albertel 12631: 
1.869     albertel 12632: 	if (!$ignore_cache) {
                   12633: 	    if (%iphost) {
                   12634: 		return %iphost;
                   12635: 	    }
                   12636: 	    my ($ip_info,$cached)=
                   12637: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   12638: 	    if ($cached) {
                   12639: 		%iphost      = %{$ip_info->[0]};
                   12640: 		%name_to_ip  = %{$ip_info->[1]};
                   12641: 		%lonid_to_ip = %{$ip_info->[2]};
                   12642: 		return %iphost;
                   12643: 	    }
                   12644: 	}
1.894     albertel 12645: 
                   12646: 	# get yesterday's info for fallback
                   12647: 	my %old_name_to_ip;
                   12648: 	my ($ip_info,$cached)=
                   12649: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   12650: 	if ($cached) {
                   12651: 	    %old_name_to_ip = %{$ip_info->[1]};
                   12652: 	}
                   12653: 
1.888     albertel 12654: 	my %name_to_host = &all_names();
                   12655: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 12656: 	    my $ip;
                   12657: 	    if (!exists($name_to_ip{$name})) {
                   12658: 		$ip = gethostbyname($name);
                   12659: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 12660: 		    if (defined($old_name_to_ip{$name})) {
                   12661: 			$ip = $old_name_to_ip{$name};
                   12662: 			&logthis("Can't find $name defaulting to old $ip");
                   12663: 		    } else {
                   12664: 			&logthis("Name $name no IP found");
                   12665: 			next;
                   12666: 		    }
                   12667: 		} else {
                   12668: 		    $ip=inet_ntoa($ip);
1.847     albertel 12669: 		}
                   12670: 		$name_to_ip{$name} = $ip;
                   12671: 	    } else {
                   12672: 		$ip = $name_to_ip{$name};
1.653     albertel 12673: 	    }
1.888     albertel 12674: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   12675: 		$lonid_to_ip{$id} = $ip;
                   12676: 	    }
                   12677: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 12678: 	}
1.1219    raeburn  12679: 	&do_cache_new('iphost','iphost',
                   12680: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   12681: 		      48*60*60);
1.869     albertel 12682: 
1.847     albertel 12683: 	return %iphost;
1.598     albertel 12684:     }
                   12685: 
1.992     raeburn  12686:     #
                   12687:     #  Given a DNS returns the loncapa host name for that DNS 
                   12688:     # 
                   12689:     sub host_from_dns {
                   12690:         my ($dns) = @_;
                   12691:         my @hosts;
                   12692:         my $ip;
                   12693: 
1.993     raeburn  12694:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  12695:             $ip = $name_to_ip{$dns};
                   12696:         }
                   12697:         if (!$ip) {
                   12698:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   12699:             if (length($ip) == 4) { 
                   12700: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   12701:             }
                   12702:         }
                   12703:         if ($ip) {
                   12704: 	    @hosts = get_hosts_from_ip($ip);
                   12705: 	    return $hosts[0];
                   12706:         }
                   12707:         return undef;
1.986     foxr     12708:     }
1.992     raeburn  12709: 
1.1074    raeburn  12710:     sub get_internet_names {
                   12711:         my ($lonid) = @_;
                   12712:         return if ($lonid eq '');
                   12713:         my ($idnref,$cached)=
                   12714:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   12715:         if ($cached) {
                   12716:             return $idnref;
                   12717:         }
                   12718:         my $ip = &get_host_ip($lonid);
                   12719:         my @hosts = &get_hosts_from_ip($ip);
                   12720:         my %iphost = &get_iphost();
                   12721:         my (@idns,%seen);
                   12722:         foreach my $id (@hosts) {
                   12723:             my $dom = &host_domain($id);
                   12724:             my $prim_id = &domain($dom,'primary');
                   12725:             my $prim_ip = &get_host_ip($prim_id);
                   12726:             next if ($seen{$prim_ip});
                   12727:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   12728:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   12729:                     my $intdom = &internet_dom($id);
                   12730:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   12731:                         push(@idns,$intdom);
                   12732:                     }
                   12733:                 }
                   12734:             }
                   12735:             $seen{$prim_ip} = 1;
                   12736:         }
1.1219    raeburn  12737:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  12738:     }
                   12739: 
1.986     foxr     12740: }
                   12741: 
1.1079    raeburn  12742: sub all_loncaparevs {
1.1249    raeburn  12743:     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 2.11);
1.1079    raeburn  12744: }
                   12745: 
1.1227    raeburn  12746: # ---------------------------------------------------------- Read loncaparev table
                   12747: {
                   12748:     sub load_loncaparevs { 
                   12749:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   12750:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   12751:                 while (my $configline=<$config>) {
                   12752:                     chomp($configline);
                   12753:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   12754:                     $loncaparevs{$hostid}=$loncaparev;
                   12755:                 }
                   12756:                 close($config);
                   12757:             }
                   12758:         }
                   12759:     }
                   12760: }
                   12761: 
                   12762: # ---------------------------------------------------------- Read serverhostID table
                   12763: {
                   12764:     sub load_serverhomeIDs {
                   12765:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   12766:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   12767:                 while (my $configline=<$config>) {
                   12768:                     chomp($configline);
                   12769:                     my ($name,$id)=split(/:/,$configline);
                   12770:                     $serverhomeIDs{$name}=$id;
                   12771:                 }
                   12772:                 close($config);
                   12773:             }
                   12774:         }
                   12775:     }
                   12776: }
                   12777: 
                   12778: 
1.862     albertel 12779: BEGIN {
                   12780: 
                   12781: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   12782:     unless ($readit) {
                   12783: {
                   12784:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   12785:     %perlvar = (%perlvar,%{$configvars});
                   12786: }
                   12787: 
                   12788: 
1.1       albertel 12789: # ------------------------------------------------------ Read spare server file
                   12790: {
1.448     albertel 12791:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 12792: 
                   12793:     while (my $configline=<$config>) {
                   12794:        chomp($configline);
1.284     matthew  12795:        if ($configline) {
1.784     albertel 12796: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 12797: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 12798: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 12799:        }
                   12800:     }
1.448     albertel 12801:     close($config);
1.1       albertel 12802: }
1.11      www      12803: # ------------------------------------------------------------ Read permissions
                   12804: {
1.448     albertel 12805:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      12806: 
                   12807:     while (my $configline=<$config>) {
1.448     albertel 12808: 	chomp($configline);
                   12809: 	if ($configline) {
                   12810: 	    my ($role,$perm)=split(/ /,$configline);
                   12811: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   12812: 	}
1.11      www      12813:     }
1.448     albertel 12814:     close($config);
1.11      www      12815: }
                   12816: 
                   12817: # -------------------------------------------- Read plain texts for permissions
                   12818: {
1.448     albertel 12819:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      12820: 
                   12821:     while (my $configline=<$config>) {
1.448     albertel 12822: 	chomp($configline);
                   12823: 	if ($configline) {
1.742     raeburn  12824: 	    my ($short,@plain)=split(/:/,$configline);
                   12825:             %{$prp{$short}} = ();
                   12826: 	    if (@plain > 0) {
                   12827:                 $prp{$short}{'std'} = $plain[0];
                   12828:                 for (my $i=1; $i<@plain; $i++) {
                   12829:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   12830:                 }
                   12831:             }
1.448     albertel 12832: 	}
1.135     www      12833:     }
1.448     albertel 12834:     close($config);
1.135     www      12835: }
                   12836: 
                   12837: # ---------------------------------------------------------- Read package table
                   12838: {
1.448     albertel 12839:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      12840: 
                   12841:     while (my $configline=<$config>) {
1.483     albertel 12842: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 12843: 	chomp($configline);
                   12844: 	my ($short,$plain)=split(/:/,$configline);
                   12845: 	my ($pack,$name)=split(/\&/,$short);
                   12846: 	if ($plain ne '') {
                   12847: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   12848: 	    $packagetab{$short}=$plain; 
                   12849: 	}
1.11      www      12850:     }
1.448     albertel 12851:     close($config);
1.329     matthew  12852: }
                   12853: 
1.1073    raeburn  12854: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  12855: 
                   12856: &load_loncaparevs();
1.1073    raeburn  12857: 
1.1074    raeburn  12858: # ---------------------------------------------------------- Read serverhostID table
                   12859: 
1.1227    raeburn  12860: &load_serverhomeIDs();
                   12861: 
                   12862: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  12863: {
                   12864:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   12865:     if (-e $file) {
                   12866:         my $parser = HTML::LCParser->new($file);
                   12867:         while (my $token = $parser->get_token()) {
                   12868:             if ($token->[0] eq 'S') {
                   12869:                 my $item = $token->[1];
                   12870:                 my $name = $token->[2]{'name'};
                   12871:                 my $value = $token->[2]{'value'};
1.1285    raeburn  12872:                 my $valuematch = $token->[2]{'valuematch'};
                   12873:                 if ($item ne '' && $name ne '' && ($value ne '' || $valuematch ne '')) {
1.1079    raeburn  12874:                     my $release = $parser->get_text();
                   12875:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1285    raeburn  12876:                     $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch} = $release;
1.1079    raeburn  12877:                 }
                   12878:             }
                   12879:         }
                   12880:     }
1.1073    raeburn  12881: }
                   12882: 
1.1138    raeburn  12883: # ---------------------------------------------------------- Read managers table
                   12884: {
                   12885:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   12886:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   12887:             while (my $configline=<$config>) {
                   12888:                 chomp($configline);
                   12889:                 next if ($configline =~ /^\#/);
                   12890:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   12891:                     $managerstab{$configline} = 1;
                   12892:                 }
                   12893:             }
                   12894:             close($config);
                   12895:         }
                   12896:     }
                   12897: }
                   12898: 
1.329     matthew  12899: # ------------- set up temporary directory
                   12900: {
1.1117    foxr     12901:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  12902: 
1.11      www      12903: }
                   12904: 
1.794     albertel 12905: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   12906: 				'compress_threshold'=> 20_000,
                   12907:  			        });
1.185     www      12908: 
1.281     www      12909: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      12910: $dumpcount=0;
1.958     www      12911: $locknum=0;
1.22      www      12912: 
1.163     harris41 12913: &logtouch();
1.672     albertel 12914: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      12915: $readit=1;
1.564     albertel 12916:     {
                   12917: 	use integer;
                   12918: 	my $test=(2**32)+1;
1.568     albertel 12919: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 12920: 	&logthis(" Detected 64bit platform ($_64bit)");
                   12921:     }
1.195     www      12922: }
1.1       albertel 12923: }
1.179     www      12924: 
1.1       albertel 12925: 1;
1.191     harris41 12926: __END__
                   12927: 
1.243     albertel 12928: =pod
                   12929: 
1.191     harris41 12930: =head1 NAME
                   12931: 
1.243     albertel 12932: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 12933: 
                   12934: =head1 SYNOPSIS
                   12935: 
1.243     albertel 12936: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 12937: 
                   12938:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   12939: 
1.243     albertel 12940: Common parameters:
                   12941: 
                   12942: =over 4
                   12943: 
                   12944: =item *
                   12945: 
                   12946: $uname : an internal username (if $cname expecting a course Id specifically)
                   12947: 
                   12948: =item *
                   12949: 
                   12950: $udom : a domain (if $cdom expecting a course's domain specifically)
                   12951: 
                   12952: =item *
                   12953: 
                   12954: $symb : a resource instance identifier
                   12955: 
                   12956: =item *
                   12957: 
                   12958: $namespace : the name of a .db file that contains the data needed or
                   12959: being set.
                   12960: 
                   12961: =back
                   12962: 
1.394     bowersj2 12963: =head1 OVERVIEW
1.191     harris41 12964: 
1.394     bowersj2 12965: lonnet provides subroutines which interact with the
                   12966: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   12967: about classes, users, and resources.
1.243     albertel 12968: 
                   12969: For many of these objects you can also use this to store data about
                   12970: them or modify them in various ways.
1.191     harris41 12971: 
1.394     bowersj2 12972: =head2 Symbs
1.191     harris41 12973: 
1.394     bowersj2 12974: To identify a specific instance of a resource, LON-CAPA uses symbols
                   12975: or "symbs"X<symb>. These identifiers are built from the URL of the
                   12976: map, the resource number of the resource in the map, and the URL of
                   12977: the resource itself. The latter is somewhat redundant, but might help
                   12978: if maps change.
                   12979: 
                   12980: An example is
                   12981: 
                   12982:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   12983: 
                   12984: The respective map entry is
                   12985: 
                   12986:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   12987:   title="Problem 2">
                   12988:  </resource>
                   12989: 
                   12990: Symbs are used by the random number generator, as well as to store and
                   12991: restore data specific to a certain instance of for example a problem.
                   12992: 
                   12993: =head2 Storing And Retrieving Data
                   12994: 
                   12995: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   12996: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   12997: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   12998: is is the non-critical message twin of cstore. These functions are for
                   12999: handlers to store a perl hash to a user's permanent data space in an
                   13000: easy manner, and to retrieve it again on another call. It is expected
                   13001: that a handler would use this once at the beginning to retrieve data,
                   13002: and then again once at the end to send only the new data back.
                   13003: 
                   13004: The data is stored in the user's data directory on the user's
                   13005: homeserver under the ID of the course.
                   13006: 
                   13007: The hash that is returned by restore will have all of the previous
                   13008: value for all of the elements of the hash.
                   13009: 
                   13010: Example:
                   13011: 
                   13012:  #creating a hash
                   13013:  my %hash;
                   13014:  $hash{'foo'}='bar';
                   13015: 
                   13016:  #storing it
                   13017:  &Apache::lonnet::cstore(\%hash);
                   13018: 
                   13019:  #changing a value
                   13020:  $hash{'foo'}='notbar';
                   13021: 
                   13022:  #adding a new value
                   13023:  $hash{'bar'}='foo';
                   13024:  &Apache::lonnet::cstore(\%hash);
                   13025: 
                   13026:  #retrieving the hash
                   13027:  my %history=&Apache::lonnet::restore();
                   13028: 
                   13029:  #print the hash
                   13030:  foreach my $key (sort(keys(%history))) {
                   13031:    print("\%history{$key} = $history{$key}");
                   13032:  }
                   13033: 
                   13034: Will print out:
1.191     harris41 13035: 
1.394     bowersj2 13036:  %history{1:foo} = bar
                   13037:  %history{1:keys} = foo:timestamp
                   13038:  %history{1:timestamp} = 990455579
                   13039:  %history{2:bar} = foo
                   13040:  %history{2:foo} = notbar
                   13041:  %history{2:keys} = foo:bar:timestamp
                   13042:  %history{2:timestamp} = 990455580
                   13043:  %history{bar} = foo
                   13044:  %history{foo} = notbar
                   13045:  %history{timestamp} = 990455580
                   13046:  %history{version} = 2
                   13047: 
                   13048: Note that the special hash entries C<keys>, C<version> and
                   13049: C<timestamp> were added to the hash. C<version> will be equal to the
                   13050: total number of versions of the data that have been stored. The
                   13051: C<timestamp> attribute will be the UNIX time the hash was
                   13052: stored. C<keys> is available in every historical section to list which
                   13053: keys were added or changed at a specific historical revision of a
                   13054: hash.
                   13055: 
                   13056: B<Warning>: do not store the hash that restore returns directly. This
                   13057: will cause a mess since it will restore the historical keys as if the
                   13058: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13059: 
1.394     bowersj2 13060: Calling convention:
1.191     harris41 13061: 
1.1225    raeburn  13062:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  13063:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13064: 
1.394     bowersj2 13065: For more detailed information, see lonnet specific documentation.
1.191     harris41 13066: 
1.394     bowersj2 13067: =head1 RETURN MESSAGES
1.191     harris41 13068: 
1.394     bowersj2 13069: =over 4
1.191     harris41 13070: 
1.394     bowersj2 13071: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13072: 
1.394     bowersj2 13073: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13074: when the connection is brought back up
1.191     harris41 13075: 
1.394     bowersj2 13076: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13077: for later delivery
1.191     harris41 13078: 
1.967     bisitz   13079: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13080: 
1.394     bowersj2 13081: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13082: that was requested
1.191     harris41 13083: 
1.243     albertel 13084: =back
1.191     harris41 13085: 
1.243     albertel 13086: =head1 PUBLIC SUBROUTINES
1.191     harris41 13087: 
1.243     albertel 13088: =head2 Session Environment Functions
1.191     harris41 13089: 
1.243     albertel 13090: =over 4
1.191     harris41 13091: 
1.394     bowersj2 13092: =item * 
                   13093: X<appenv()>
1.949     raeburn  13094: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13095: the user envirnoment file, and will be restored for each access this
1.620     albertel 13096: user makes during this session, also modifies the %env for the current
1.949     raeburn  13097: process. Optional rolesarrayref - if defined contains a reference to an array
                   13098: of roles which are exempt from the restriction on modifying user.role entries 
                   13099: in the user's environment.db and in %env.    
1.191     harris41 13100: 
                   13101: =item *
1.394     bowersj2 13102: X<delenv()>
1.987     raeburn  13103: B<delenv($delthis,$regexp)>: removes all items from the session
                   13104: environment file that begin with $delthis. If the 
                   13105: optional second arg - $regexp - is true, $delthis is treated as a 
                   13106: regular expression, otherwise \Q$delthis\E is used. 
                   13107: The values are also deleted from the current processes %env.
1.191     harris41 13108: 
1.795     albertel 13109: =item * get_env_multiple($name) 
                   13110: 
                   13111: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13112: values may be defined and end up as an array ref.
                   13113: 
                   13114: returns an array of values
                   13115: 
1.243     albertel 13116: =back
                   13117: 
                   13118: =head2 User Information
1.191     harris41 13119: 
1.243     albertel 13120: =over 4
1.191     harris41 13121: 
                   13122: =item *
1.394     bowersj2 13123: X<queryauthenticate()>
                   13124: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13125: authentication scheme
                   13126: 
                   13127: =item *
1.394     bowersj2 13128: X<authenticate()>
1.1073    raeburn  13129: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13130: authenticate user from domain's lib servers (first use the current
                   13131: one). C<$upass> should be the users password.
1.1073    raeburn  13132: $checkdefauth is optional (value is 1 if a check should be made to
                   13133:    authenticate user using default authentication method, and allow
                   13134:    account creation if username does not have account in the domain).
                   13135: $clientcancheckhost is optional (value is 1 if checking whether the
                   13136:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13137: 
                   13138: =item *
1.394     bowersj2 13139: X<homeserver()>
                   13140: B<homeserver($uname,$udom)>: find the server which has
                   13141: the user's directory and files (there must be only one), this caches
                   13142: the answer, and also caches if there is a borken connection.
1.191     harris41 13143: 
                   13144: =item *
1.394     bowersj2 13145: X<idget()>
                   13146: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   13147: (IDs are a unique resource in a domain, there must be only 1 ID per
                   13148: username, and only 1 username per ID in a specific domain) (returns
                   13149: hash: id=>name,id=>name)
1.191     harris41 13150: 
                   13151: =item *
1.394     bowersj2 13152: X<idrget()>
                   13153: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13154: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13155: 
                   13156: =item *
1.394     bowersj2 13157: X<idput()>
                   13158: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 13159: 
                   13160: =item *
1.394     bowersj2 13161: X<rolesinit()>
1.1169    droeschl 13162: B<rolesinit($udom,$username)>: get user privileges.
                   13163: returns user role, first access and timer interval hashes
1.243     albertel 13164: 
                   13165: =item *
1.1171    droeschl 13166: X<privileged()>
                   13167: B<privileged($username,$domain)>: returns a true if user has a
                   13168: privileged and active role (i.e. su or dc), false otherwise.
                   13169: 
                   13170: =item *
1.551     albertel 13171: X<getsection()>
                   13172: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13173: course $cname, return section name/number or '' for "not in course"
                   13174: and '-1' for "no section"
                   13175: 
                   13176: =item *
1.394     bowersj2 13177: X<userenvironment()>
                   13178: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13179: passed in @what from the requested user's environment, returns a hash
                   13180: 
1.858     raeburn  13181: =item * 
                   13182: X<userlog_query()>
1.859     albertel 13183: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13184: activity.log file. %filters defines filters applied when parsing the
                   13185: log file. These can be start or end timestamps, or the type of action
                   13186: - log to look for Login or Logout events, check for Checkin or
                   13187: Checkout, role for role selection. The response is in the form
                   13188: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13189: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13190: 
1.243     albertel 13191: =back
                   13192: 
                   13193: =head2 User Roles
                   13194: 
                   13195: =over 4
                   13196: 
                   13197: =item *
                   13198: 
1.1284    raeburn  13199: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13200: returns codes for allowed actions.
                   13201: 
                   13202: The first argument is required, all others are optional.
                   13203: 
                   13204: $priv is the privilege being checked.
                   13205: $uri contains additional information about what is being checked for access (e.g.,
                   13206: URL, course ID etc.). 
                   13207: $symb is the unique resource instance identifier in a course; if needed,
                   13208: but not provided, it will be retrieved via a call to &symbread(). 
                   13209: $role is the role for which a priv is being checked (only used if priv is evb). 
                   13210: $clientip is the user's IP address (only used when checking for access to portfolio 
                   13211: files).
                   13212: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   13213: prevents recursive calls to &allowed.
                   13214: 
1.243     albertel 13215:  F: full access
                   13216:  U,I,K: authentication modes (cxx only)
                   13217:  '': forbidden
                   13218:  1: user needs to choose course
                   13219:  2: browse allowed
1.766     albertel 13220:  A: passphrase authentication needed
1.1284    raeburn  13221:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13222: 
                   13223: =item *
                   13224: 
1.1192    raeburn  13225: constructaccess($url,$setpriv) : check for access to construction space URL
                   13226: 
                   13227: See if the owner domain and name in the URL match those in the
                   13228: expected environment.  If so, return three element list
                   13229: ($ownername,$ownerdomain,$ownerhome).
                   13230: 
                   13231: Otherwise return the null string.
                   13232: 
                   13233: If second argument 'setpriv' is true, it assigns the privileges,
                   13234: and returns the same three element list, unless the owner has
                   13235: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13236: in which case the null string is returned.
                   13237: 
                   13238: =item *
                   13239: 
1.243     albertel 13240: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   13241: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   13242: and course level
                   13243: 
                   13244: =item *
                   13245: 
1.988     raeburn  13246: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13247: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13248: $type is Course (default) or Community.
1.988     raeburn  13249: If $forcedefault evaluates to true, text returned will be default 
                   13250: text for $type. Otherwise, if this is a course, the text returned 
                   13251: will be a custom name for the role (if defined in the course's 
                   13252: environment).  If no custom name is defined the default is returned.
                   13253:    
1.832     raeburn  13254: =item *
                   13255: 
1.1219    raeburn  13256: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13257: All arguments are optional. Returns a hash of a roles, either for
                   13258: co-author/assistant author roles for a user's Construction Space
1.906     albertel 13259: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  13260: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   13261: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   13262: For each key, value is set to colon-separated start and end times for
                   13263: the role.  If no username and domain are specified, will default to
1.934     raeburn  13264: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  13265: of role statuses (active, future or previous), roles 
                   13266: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   13267: to restrict the list of roles reported. If no array ref is 
                   13268: provided for types, will default to return only active roles.
1.834     albertel 13269: 
1.1195    raeburn  13270: =item *
                   13271: 
                   13272: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  13273: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   13274: 
                   13275: Additional optional arguments are: $type (if role checking is to be restricted 
                   13276: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  13277: available roles) or future (roles available in the future), and
                   13278: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  13279: have active Domain Coordinator role in course's domain or in additional
                   13280: domains (specified in 'Domains to check for privileged users' in course
                   13281: environment -- set via:  Course Settings -> Classlists and staff listing).
                   13282: 
                   13283: =item *
                   13284: 
                   13285: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   13286: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   13287: $possdomains and $possroles are optional array refs -- to domains to check and
                   13288: roles to check.  If $possdomains is not specified, a dump will be done of the
                   13289: users' roles.db to check for a dc or su role in any domain. This can be
                   13290: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   13291: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   13292: this then allows &privileged_by_domain() to be used, which caches the identity
                   13293: of privileged users, eliminating the need for repeated calls to &dump().
                   13294: 
                   13295: =item *
                   13296: 
                   13297: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   13298: where the outer hash keys are domains specified in the $possdomains array ref,
                   13299: next inner hash keys are privileged roles specified in the $roles array ref,
                   13300: and the innermost hash contains key = value pairs for username:domain = end:start
                   13301: for active or future "privileged" users with that role in that domain. To avoid
                   13302: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   13303: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  13304: 
1.243     albertel 13305: =back
                   13306: 
                   13307: =head2 User Modification
                   13308: 
                   13309: =over 4
                   13310: 
                   13311: =item *
                   13312: 
1.957     raeburn  13313: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 13314: user for the level given by URL.  Optional start and end dates (leave empty
                   13315: string or zero for "no date")
1.191     harris41 13316: 
                   13317: =item *
                   13318: 
1.243     albertel 13319: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   13320: change a users, password, possible return values are: ok,
                   13321: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   13322: refused
1.191     harris41 13323: 
                   13324: =item *
                   13325: 
1.243     albertel 13326: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 13327: 
                   13328: =item *
                   13329: 
1.1058    raeburn  13330: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   13331:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   13332: 
                   13333: will update user information (firstname,middlename,lastname,generation,
                   13334: permanentemail), and if forceid is true, student/employee ID also.
                   13335: A user's institutional affiliation(s) can also be updated.
                   13336: User information fields will not be overwritten with empty entries 
                   13337: unless the field is included in the $candelete array reference.
                   13338: This array is included when a single user is modified via "Manage Users",
                   13339: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 13340: 
                   13341: =item *
                   13342: 
1.286     matthew  13343: modifystudent
                   13344: 
1.957     raeburn  13345: modify a student's enrollment and identification information.
1.1235    raeburn  13346: The course id is resolved based on the current user's environment.  
                   13347: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  13348: associated with a course.
                   13349: 
1.297     matthew  13350: This call is essentially a wrapper for lonnet::modifyuser and
                   13351: lonnet::modify_student_enrollment
1.286     matthew  13352: 
                   13353: Inputs: 
                   13354: 
                   13355: =over 4
                   13356: 
1.957     raeburn  13357: =item B<$udom> Student's loncapa domain
1.286     matthew  13358: 
1.957     raeburn  13359: =item B<$uname> Student's loncapa login name
1.286     matthew  13360: 
1.964     bisitz   13361: =item B<$uid> Student/Employee ID
1.286     matthew  13362: 
1.957     raeburn  13363: =item B<$umode> Student's authentication mode
1.286     matthew  13364: 
1.957     raeburn  13365: =item B<$upass> Student's password
1.286     matthew  13366: 
1.957     raeburn  13367: =item B<$first> Student's first name
1.286     matthew  13368: 
1.957     raeburn  13369: =item B<$middle> Student's middle name
1.286     matthew  13370: 
1.957     raeburn  13371: =item B<$last> Student's last name
1.286     matthew  13372: 
1.957     raeburn  13373: =item B<$gene> Student's generation
1.286     matthew  13374: 
1.957     raeburn  13375: =item B<$usec> Student's section in course
1.286     matthew  13376: 
                   13377: =item B<$end> Unix time of the roles expiration
                   13378: 
                   13379: =item B<$start> Unix time of the roles start date
                   13380: 
                   13381: =item B<$forceid> If defined, allow $uid to be changed
                   13382: 
                   13383: =item B<$desiredhome> server to use as home server for student
                   13384: 
1.957     raeburn  13385: =item B<$email> Student's permanent e-mail address
                   13386: 
                   13387: =item B<$type> Type of enrollment (auto or manual)
                   13388: 
1.963     raeburn  13389: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   13390: 
                   13391: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  13392: 
1.963     raeburn  13393: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  13394: 
1.963     raeburn  13395: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  13396: 
1.1216    raeburn  13397: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   13398: 
                   13399: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
1.957     raeburn  13400: 
1.286     matthew  13401: =back
1.297     matthew  13402: 
                   13403: =item *
                   13404: 
                   13405: modify_student_enrollment
                   13406: 
1.1235    raeburn  13407: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  13408: 'role.request.course' must be defined for this function to proceed.
                   13409: 
                   13410: Inputs:
                   13411: 
                   13412: =over 4
                   13413: 
1.1235    raeburn  13414: =item $udom, student's domain
1.297     matthew  13415: 
1.1235    raeburn  13416: =item $uname, student's name
1.297     matthew  13417: 
1.1235    raeburn  13418: =item $uid, student's user id
1.297     matthew  13419: 
1.1235    raeburn  13420: =item $first, student's first name
1.297     matthew  13421: 
                   13422: =item $middle
                   13423: 
                   13424: =item $last
                   13425: 
                   13426: =item $gene
                   13427: 
                   13428: =item $usec
                   13429: 
                   13430: =item $end
                   13431: 
                   13432: =item $start
                   13433: 
1.957     raeburn  13434: =item $type
                   13435: 
                   13436: =item $locktype
                   13437: 
                   13438: =item $cid
                   13439: 
                   13440: =item $selfenroll
                   13441: 
                   13442: =item $context
                   13443: 
1.1216    raeburn  13444: =item $credits, number of credits student will earn from this class
                   13445: 
1.297     matthew  13446: =back
                   13447: 
1.191     harris41 13448: 
                   13449: =item *
                   13450: 
1.243     albertel 13451: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   13452: custom role; give a custom role to a user for the level given by URL.  Specify
                   13453: name and domain of role author, and role name
1.191     harris41 13454: 
                   13455: =item *
                   13456: 
1.243     albertel 13457: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 13458: 
                   13459: =item *
                   13460: 
1.243     albertel 13461: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   13462: 
                   13463: =back
                   13464: 
                   13465: =head2 Course Infomation
                   13466: 
                   13467: =over 4
1.191     harris41 13468: 
                   13469: =item *
                   13470: 
1.1118    foxr     13471: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 13472: specified course id, including all environment settings for the
                   13473: course, the description of the course will be in the hash under the
                   13474: key 'description'
1.191     harris41 13475: 
1.1118    foxr     13476: $options is an optional parameter that if supplied is a hash reference that controls
                   13477: what how this function works.  It has the following key/values:
                   13478: 
                   13479: =over 4
                   13480: 
                   13481: =item freshen_cache
                   13482: 
                   13483: If defined, and the environment cache for the course is valid, it is 
                   13484: returned in the returned hash.
                   13485: 
                   13486: =item one_time
                   13487: 
                   13488: If defined, the last cache time is set to _now_
                   13489: 
                   13490: =item user
                   13491: 
                   13492: If defined, the supplied username is used instead of the current user.
                   13493: 
                   13494: 
                   13495: =back
                   13496: 
1.191     harris41 13497: =item *
                   13498: 
1.624     albertel 13499: resdata($name,$domain,$type,@which) : request for current parameter
                   13500: setting for a specific $type, where $type is either 'course' or 'user',
                   13501: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  13502: answers for 10 minutes.
1.243     albertel 13503: 
1.877     foxr     13504: =item *
                   13505: 
                   13506: get_courseresdata($courseid, $domain) : dump the entire course resource
                   13507: data base, returning a hash that is keyed by the resource name and has
                   13508: values that are the resource value.  I believe that the timestamps and
                   13509: versions are also returned.
                   13510: 
1.1236    raeburn  13511: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   13512: supplemental content area. This routine caches the number of files for 
                   13513: 10 minutes.
                   13514: 
1.243     albertel 13515: =back
                   13516: 
                   13517: =head2 Course Modification
                   13518: 
                   13519: =over 4
1.191     harris41 13520: 
                   13521: =item *
                   13522: 
1.243     albertel 13523: writecoursepref($courseid,%prefs) : write preferences (environment
                   13524: database) for a course
1.191     harris41 13525: 
                   13526: =item *
                   13527: 
1.1011    raeburn  13528: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   13529: 
                   13530: =item *
                   13531: 
1.1038    raeburn  13532: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 13533: 
1.1167    droeschl 13534: =item *
                   13535: 
                   13536: is_course($courseid), is_course($cdom, $cnum)
                   13537: 
                   13538: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   13539: two component version $cdom, $cnum. It checks if the specified course exists.
                   13540: 
                   13541: Returns:
                   13542:     undef if the course doesn't exist, otherwise
                   13543:     in scalar context the combined courseid.
                   13544:     in list context the two components of the course identifier, domain and 
                   13545:     courseid.    
                   13546: 
1.243     albertel 13547: =back
                   13548: 
                   13549: =head2 Resource Subroutines
                   13550: 
                   13551: =over 4
1.191     harris41 13552: 
                   13553: =item *
                   13554: 
1.243     albertel 13555: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 13556: 
                   13557: =item *
                   13558: 
1.243     albertel 13559: repcopy($filename) : subscribes to the requested file, and attempts to
                   13560: replicate from the owning library server, Might return
1.607     raeburn  13561: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   13562: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 13563: resource. Expects the local filesystem pathname
                   13564: (/home/httpd/html/res/....)
                   13565: 
                   13566: =back
                   13567: 
                   13568: =head2 Resource Information
                   13569: 
                   13570: =over 4
1.191     harris41 13571: 
                   13572: =item *
                   13573: 
1.1228    raeburn  13574: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   13575: and returns the value of a variety of different possible values,
                   13576: $varname should be a request string, and the other parameters can be
                   13577: used to specify who and what one is asking about. Ordinarily, $cid 
                   13578: does not need to be specified, as it is retrived from 
                   13579: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   13580: within lonuserstate::loadmap() when initializing a course, before
                   13581: $env{'request.course.id'} has been set, so it needs to be provided
                   13582: in that one case.
1.243     albertel 13583: 
                   13584: Possible values for $varname are environment.lastname (or other item
                   13585: from the envirnment hash), user.name (or someother aspect about the
                   13586: user), resource.0.maxtries (or some other part and parameter of a
                   13587: resource)
1.204     albertel 13588: 
                   13589: =item *
                   13590: 
1.243     albertel 13591: directcondval($number) : get current value of a condition; reads from a state
                   13592: string
1.204     albertel 13593: 
                   13594: =item *
                   13595: 
1.243     albertel 13596: condval($condidx) : value of condition index based on state
1.204     albertel 13597: 
                   13598: =item *
                   13599: 
1.243     albertel 13600: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   13601: resource's metadata, $what should be either a specific key, or either
                   13602: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   13603: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   13604: 
                   13605: this function automatically caches all requests
1.191     harris41 13606: 
                   13607: =item *
                   13608: 
1.243     albertel 13609: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   13610: network of library servers; returns file handle of where SQL and regex results
                   13611: will be stored for query
1.191     harris41 13612: 
                   13613: =item *
                   13614: 
1.1282    raeburn  13615: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   13616: return symbolic list entry (all arguments optional). 
                   13617: 
                   13618: Args: filename is the filename (including path) for the file for which a symb 
                   13619: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   13620: to check access status if more than one resource was found in the bighash 
                   13621: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   13622: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   13623: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   13624: cause possible symbs to be checked to determine if they are subject to content
                   13625: blocking, if so they will not be included as possible symbs; possibles is a
                   13626: ref to a hash, which, as a side effect, will be populated with all possible 
                   13627: symbs (content blocking not tested).
                   13628:  
1.243     albertel 13629: returns the data handle
1.191     harris41 13630: 
                   13631: =item *
                   13632: 
1.1190    raeburn  13633: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   13634: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 13635: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  13636: on failure, user must be in a course, as it assumes the existence of
                   13637: the course initial hash, and uses $env('request.course.id'}.  The third
                   13638: arg is an optional reference to a scalar.  If this arg is passed in the 
                   13639: call to symbverify, it will be set to 1 if the symb has been set to be 
                   13640: encrypted; otherwise it will be null.  
1.191     harris41 13641: 
                   13642: =item *
                   13643: 
1.243     albertel 13644: symbclean($symb) : removes versions numbers from a symb, returns the
                   13645: cleaned symb
1.191     harris41 13646: 
                   13647: =item *
                   13648: 
1.243     albertel 13649: is_on_map($uri) : checks if the $uri is somewhere on the current
                   13650: course map, user must be in a course for it to work.
1.191     harris41 13651: 
                   13652: =item *
                   13653: 
1.243     albertel 13654: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 13655: 
                   13656: =item *
                   13657: 
1.243     albertel 13658: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   13659: a random seed, all arguments are optional, if they aren't sent it uses the
                   13660: environment to derive them. Note: if symb isn't sent and it can't get one
                   13661: from &symbread it will use the current time as its return value
1.191     harris41 13662: 
                   13663: =item *
                   13664: 
1.243     albertel 13665: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   13666: unfakeable, receipt
1.191     harris41 13667: 
                   13668: =item *
                   13669: 
1.620     albertel 13670: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 13671: 
                   13672: =item *
                   13673: 
1.243     albertel 13674: countacc($url) : count the number of accesses to a given URL
1.191     harris41 13675: 
                   13676: =item *
                   13677: 
1.243     albertel 13678: 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 13679: 
                   13680: =item *
                   13681: 
1.243     albertel 13682: 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 13683: 
                   13684: =item *
                   13685: 
1.243     albertel 13686: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 13687: 
                   13688: =item *
                   13689: 
1.243     albertel 13690: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   13691: forcing spreadsheet to reevaluate the resource scores next time.
                   13692: 
1.1195    raeburn  13693: =item * 
                   13694: 
1.1196    raeburn  13695: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   13696: when viewing in course context.
1.1195    raeburn  13697: 
1.1196    raeburn  13698:  input: six args -- filename (decluttered), course number, course domain,
                   13699:                     url, symb (if registered) and group (if this is a 
                   13700:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  13701: 
1.1196    raeburn  13702:  output: array of five scalars --
1.1195    raeburn  13703:          $cfile -- url for file editing if editable on current server
                   13704:          $home -- homeserver of resource (i.e., for author if published,
                   13705:                                           or course if uploaded.).
                   13706:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  13707:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   13708:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  13709: 
                   13710: =item *
                   13711: 
                   13712: is_course_upload($file,$cnum,$cdom)
                   13713: 
                   13714: Used in course context to determine if current file was uploaded to 
                   13715: the course (i.e., would be found in /userfiles/docs on the course's 
                   13716: homeserver.
                   13717: 
                   13718:   input: 3 args -- filename (decluttered), course number and course domain.
                   13719:   output: boolean -- 1 if file was uploaded.
                   13720: 
1.243     albertel 13721: =back
                   13722: 
                   13723: =head2 Storing/Retreiving Data
                   13724: 
                   13725: =over 4
1.191     harris41 13726: 
                   13727: =item *
                   13728: 
1.1269    raeburn  13729: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   13730: permanently for this url; hashref needs to be given and should be a \%hashname;
                   13731: the remaining args aren't required and if they aren't passed or are '' they will
                   13732: be derived from the env (with the exception of $laststore, which is an 
                   13733: optional arg used when a user's submission is stored in grading).
                   13734: $laststore is $version=$timestamp, where $version is the most recent version
                   13735: number retrieved for the corresponding $symb in the $namespace db file, and
                   13736: $timestamp is the timestamp for that transaction (UNIX time).
                   13737: $laststore is currently only passed when cstore() is called by 
                   13738: structuretags::finalize_storage().
1.191     harris41 13739: 
                   13740: =item *
                   13741: 
1.1269    raeburn  13742: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   13743: but uses critical subroutine
1.191     harris41 13744: 
                   13745: =item *
                   13746: 
1.243     albertel 13747: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   13748: all args are optional
1.191     harris41 13749: 
                   13750: =item *
                   13751: 
1.717     albertel 13752: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   13753: dumps the complete (or key matching regexp) namespace into a hash
                   13754: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   13755: normally &store()ed into
                   13756: 
                   13757: $range should be either an integer '100' (give me the first 100
                   13758:                                            matching records)
                   13759:               or be  two integers sperated by a - with no spaces
                   13760:                  '30-50' (give me the 30th through the 50th matching
                   13761:                           records)
                   13762: 
                   13763: 
                   13764: =item *
                   13765: 
1.1269    raeburn  13766: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 13767: replaces a &store() version of data with a replacement set of data
                   13768: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  13769: reference. If $tolog is true, the transaction is logged in the courselog
                   13770: with an action=PUTSTORE.
1.717     albertel 13771: 
                   13772: =item *
                   13773: 
1.243     albertel 13774: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   13775: works very similar to store/cstore, but all data is stored in a
                   13776: temporary location and can be reset using tmpreset, $storehash should
                   13777: be a hash reference, returns nothing on success
1.191     harris41 13778: 
                   13779: =item *
                   13780: 
1.243     albertel 13781: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   13782: similar to restore, but all data is stored in a temporary location and
                   13783: can be reset using tmpreset. Returns a hash of values on success,
                   13784: error string otherwise.
1.191     harris41 13785: 
                   13786: =item *
                   13787: 
1.243     albertel 13788: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   13789: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 13790: 
                   13791: =item *
                   13792: 
1.243     albertel 13793: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13794: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 13795: 
                   13796: =item *
                   13797: 
1.243     albertel 13798: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   13799: namesp ($udom and $uname are optional)
1.191     harris41 13800: 
                   13801: =item *
                   13802: 
1.702     albertel 13803: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 13804: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 13805: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  13806: 
1.702     albertel 13807: $range should be either an integer '100' (give me the first 100
                   13808:                                            matching records)
                   13809:               or be  two integers sperated by a - with no spaces
                   13810:                  '30-50' (give me the 30th through the 50th matching
                   13811:                           records)
1.449     matthew  13812: =item *
                   13813: 
                   13814: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   13815: $store can be a scalar, an array reference, or if the amount to be 
                   13816: incremented is > 1, a hash reference.
                   13817: 
                   13818: ($udom and $uname are optional)
1.191     harris41 13819: 
                   13820: =item *
                   13821: 
1.243     albertel 13822: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   13823: ($udom and $uname are optional)
1.191     harris41 13824: 
                   13825: =item *
                   13826: 
1.243     albertel 13827: cput($namespace,$storehash,$udom,$uname) : critical put
                   13828: ($udom and $uname are optional)
1.191     harris41 13829: 
                   13830: =item *
                   13831: 
1.748     albertel 13832: newput($namespace,$storehash,$udom,$uname) :
                   13833: 
                   13834: Attempts to store the items in the $storehash, but only if they don't
                   13835: currently exist, if this succeeds you can be certain that you have 
                   13836: successfully created a new key value pair in the $namespace db.
                   13837: 
                   13838: 
                   13839: Args:
                   13840:  $namespace: name of database to store values to
                   13841:  $storehash: hashref to store to the db
                   13842:  $udom: (optional) domain of user containing the db
                   13843:  $uname: (optional) name of user caontaining the db
                   13844: 
                   13845: Returns:
                   13846:  'ok' -> succeeded in storing all keys of $storehash
                   13847:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   13848:                         least <key> already existed in the db (other
                   13849:                         requested keys may also already exist)
1.967     bisitz   13850:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 13851:  'con_lost' -> unable to contact request server
                   13852:  'refused' -> action was not allowed by remote machine
                   13853: 
                   13854: 
                   13855: =item *
                   13856: 
1.243     albertel 13857: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   13858: reference filled in from namesp (encrypts the return communication)
                   13859: ($udom and $uname are optional)
1.191     harris41 13860: 
                   13861: =item *
                   13862: 
1.243     albertel 13863: log($udom,$name,$home,$message) : write to permanent log for user; use
                   13864: critical subroutine
                   13865: 
1.806     raeburn  13866: =item *
                   13867: 
1.860     raeburn  13868: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   13869: array reference filled in from namespace found in domain level on either
                   13870: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  13871: 
                   13872: =item *
                   13873: 
1.860     raeburn  13874: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   13875: domain level either on specified domain server ($uhome) or primary domain 
                   13876: server ($udom and $uhome are optional)
1.806     raeburn  13877: 
1.943     raeburn  13878: =item * 
                   13879: 
1.1240    raeburn  13880: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   13881: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   13882: the target domain.
                   13883: 
                   13884: May also include additional key => value pairs for the following groups:
                   13885: 
                   13886: =over
                   13887: 
                   13888: =item
                   13889: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   13890: 
                   13891: =over
                   13892: 
                   13893: =item defaultquota, authorquota
                   13894: 
                   13895: =back
                   13896: 
                   13897: =item
                   13898: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   13899: portfolio for users).
                   13900: 
                   13901: =over
                   13902: 
                   13903: =item
                   13904: aboutme, blog, webdav, portfolio
                   13905: 
                   13906: =back
                   13907: 
                   13908: =item
                   13909: requestcourses: ability to request courses, and how requests are processed.
                   13910: 
                   13911: =over
                   13912: 
                   13913: =item
1.1246    raeburn  13914: official, unofficial, community, textbook
1.1240    raeburn  13915: 
                   13916: =back
                   13917: 
                   13918: =item
                   13919: inststatus: types of institutional affiliation, and order in which they are displayed.
                   13920: 
                   13921: =over
                   13922: 
                   13923: =item
1.1256    raeburn  13924: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  13925: 
                   13926: =back
                   13927: 
                   13928: =item
                   13929: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   13930: for course's uploaded content.
                   13931: 
                   13932: =over
                   13933: 
                   13934: =item
1.1246    raeburn  13935: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
                   13936: communityquota, textbookquota
1.1240    raeburn  13937: 
                   13938: =back
                   13939: 
                   13940: =item
                   13941: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   13942: on your servers.
                   13943: 
                   13944: =over
                   13945: 
                   13946: =item 
                   13947: remotesessions, hostedsessions
                   13948: 
                   13949: =back
                   13950: 
                   13951: =back
                   13952: 
                   13953: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   13954: utility to create a configuration.db file on a domain's primary library server 
                   13955: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   13956: -- corresponding values are authentication type (internal, krb4, krb5,
                   13957: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   13958: will be available. Values are retrieved from cache (if current), unless the
                   13959: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   13960: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   13961: 
                   13962: Typical usage:
1.943     raeburn  13963: 
1.1240    raeburn  13964: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  13965: 
1.243     albertel 13966: =back
                   13967: 
                   13968: =head2 Network Status Functions
                   13969: 
                   13970: =over 4
1.191     harris41 13971: 
                   13972: =item *
                   13973: 
1.1137    raeburn  13974: dirlist() : return directory list based on URI (first arg).
                   13975: 
                   13976: Inputs: 1 required, 5 optional.
                   13977: 
                   13978: =over
                   13979: 
                   13980: =item 
                   13981: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   13982: 
                   13983: =item
                   13984: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   13985: 
                   13986: =item
                   13987: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   13988: 
                   13989: =item
                   13990: $getpropath - boolean: 1 if prepend path using &propath(). 
                   13991: 
                   13992: =item
                   13993: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   13994: 
                   13995: =item 
                   13996: $alternateRoot - path to prepend in place of path from $uri.
                   13997: 
                   13998: =back
                   13999: 
                   14000: Returns: Array of up to two items.
                   14001: 
                   14002: =over
                   14003: 
                   14004: a reference to an array of files/subdirectories
                   14005: 
                   14006: =over
                   14007: 
                   14008: Each element in the array of files/subdirectories is a & separated list of
                   14009: item name and the result of running stat on the item.  If dirlist was requested
                   14010: for a file instead of a directory, the item name will be ''. For a directory 
                   14011: listing, if the item is a metadata file, the element will end &N&M 
                   14012: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14013: default copyright set (1).  
                   14014: 
                   14015: =back
                   14016: 
                   14017: a scalar containing error condition (if encountered).
                   14018: 
                   14019: =over
                   14020: 
                   14021: =item 
                   14022: no_host (no homeserver identified for $username:$domain).
                   14023: 
                   14024: =item 
                   14025: no_such_host (server contacted for listing not identified as valid host).
                   14026: 
                   14027: =item 
                   14028: con_lost (connection to remote server failed).
                   14029: 
                   14030: =item 
                   14031: refused (invalid $username:$domain received on lond side).
                   14032: 
                   14033: =item 
                   14034: no_such_dir (directory at specified path on lond side does not exist). 
                   14035: 
                   14036: =item 
                   14037: empty (directory at specified path on lond side is empty).
                   14038: 
                   14039: =over
                   14040: 
                   14041: This is currently not encountered because the &ls3, &ls2, 
                   14042: &ls (_handler) routines on the lond side do not filter out
                   14043: . and .. from a directory listing. 
                   14044: 
                   14045: =back
                   14046: 
                   14047: =back
                   14048: 
                   14049: =back
1.191     harris41 14050: 
                   14051: =item *
                   14052: 
1.243     albertel 14053: spareserver() : find server with least workload from spare.tab
                   14054: 
1.986     foxr     14055: 
                   14056: =item *
                   14057: 
                   14058: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14059: if there is no corresponding loncapa host.
                   14060: 
1.243     albertel 14061: =back
                   14062: 
1.986     foxr     14063: 
1.243     albertel 14064: =head2 Apache Request
                   14065: 
                   14066: =over 4
1.191     harris41 14067: 
                   14068: =item *
                   14069: 
1.243     albertel 14070: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14071: localhost, posts hash
                   14072: 
                   14073: =back
                   14074: 
                   14075: =head2 Data to String to Data
                   14076: 
                   14077: =over 4
1.191     harris41 14078: 
                   14079: =item *
                   14080: 
1.243     albertel 14081: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14082: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14083: 
                   14084: =item *
                   14085: 
1.243     albertel 14086: hashref2str($hashref) : convert a hashref into a string complete with
                   14087: escaping and '=' and '&' separators, supports elements that are
                   14088: arrayrefs and hashrefs
1.191     harris41 14089: 
                   14090: =item *
                   14091: 
1.243     albertel 14092: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14093: with escaping and '&' separators, supports elements that are arrayrefs
                   14094: and hashrefs
1.191     harris41 14095: 
                   14096: =item *
                   14097: 
1.243     albertel 14098: str2hash($string) : convert string to hash using unescaping and
                   14099: splitting on '=' and '&', supports elements that are arrayrefs and
                   14100: hashrefs
1.191     harris41 14101: 
                   14102: =item *
                   14103: 
1.243     albertel 14104: str2array($string) : convert string to hash using unescaping and
                   14105: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14106: 
                   14107: =back
                   14108: 
                   14109: =head2 Logging Routines
                   14110: 
                   14111: 
                   14112: These routines allow one to make log messages in the lonnet.log and
                   14113: lonnet.perm logfiles.
1.191     harris41 14114: 
1.1119    foxr     14115: =over 4
                   14116: 
1.191     harris41 14117: =item *
                   14118: 
1.243     albertel 14119: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14120: 
                   14121: =item *
                   14122: 
1.243     albertel 14123: logthis() : append message to the normal lonnet.log file, it gets
                   14124: preiodically rolled over and deleted.
1.191     harris41 14125: 
                   14126: =item *
                   14127: 
1.243     albertel 14128: logperm() : append a permanent message to lonnet.perm.log, this log
                   14129: file never gets deleted by any automated portion of the system, only
                   14130: messages of critical importance should go in here.
                   14131: 
1.1119    foxr     14132: 
1.243     albertel 14133: =back
                   14134: 
                   14135: =head2 General File Helper Routines
                   14136: 
                   14137: =over 4
1.191     harris41 14138: 
                   14139: =item *
                   14140: 
1.481     raeburn  14141: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14142: (a) files in /uploaded
                   14143:   (i) If a local copy of the file exists - 
                   14144:       compares modification date of local copy with last-modified date for 
                   14145:       definitive version stored on home server for course. If local copy is 
                   14146:       stale, requests a new version from the home server and stores it. 
                   14147:       If the original has been removed from the home server, then local copy 
                   14148:       is unlinked.
                   14149:   (ii) If local copy does not exist -
                   14150:       requests the file from the home server and stores it. 
                   14151:   
                   14152:   If $caller is 'uploadrep':  
                   14153:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14154:     for request for files originally uploaded via DOCS. 
                   14155:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14156:   
                   14157:   Otherwise:
                   14158:      This indicates a call from the content generation phase of the request.
                   14159:      -  returns the entire contents of the file or -1.
                   14160:      
                   14161: (b) files in /res
                   14162:    - returns the entire contents of a file or -1; 
                   14163:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14164: 
1.712     albertel 14165: 
                   14166: =item *
                   14167: 
                   14168: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14169:                   reference
                   14170: 
                   14171: returns either a stat() list of data about the file or an empty list
                   14172: if the file doesn't exist or couldn't find out about it (connection
                   14173: problems or user unknown)
                   14174: 
1.191     harris41 14175: =item *
                   14176: 
1.243     albertel 14177: filelocation($dir,$file) : returns file system location of a file
                   14178: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14179: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14180: and a file of ../bob will become /a/bob)
1.191     harris41 14181: 
                   14182: =item *
                   14183: 
                   14184: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14185: filelocation except for hrefs
                   14186: 
                   14187: =item *
                   14188: 
1.1261    raeburn  14189: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14190: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14191: 
1.243     albertel 14192: =back
                   14193: 
1.608     albertel 14194: =head2 Usererfile file routines (/uploaded*)
                   14195: 
                   14196: =over 4
                   14197: 
                   14198: =item *
                   14199: 
                   14200: userfileupload(): main rotine for putting a file in a user or course's
                   14201:                   filespace, arguments are,
                   14202: 
1.620     albertel 14203:  formname - required - this is the name of the element in $env where the
1.608     albertel 14204:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14205:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14206:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14207:  context - if coursedoc, store the file in the course of the active role
                   14208:              of the current user; 
                   14209:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14210:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14211:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14212:          if undefined, it will be placed in "unknown"
                   14213: 
                   14214:  (This routine calls clean_filename() to remove any dangerous
                   14215:  characters from the filename, and then calls finuserfileupload() to
                   14216:  complete the transaction)
                   14217: 
                   14218:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14219:  and /adm/notfound.html if unsuccessful
                   14220: 
                   14221: =item *
                   14222: 
                   14223: clean_filename(): routine for cleaing a filename up for storage in
                   14224:                  userfile space, argument is:
                   14225: 
                   14226:  filename - proposed filename
                   14227: 
                   14228: returns: the new clean filename
                   14229: 
                   14230: =item *
                   14231: 
1.1090    raeburn  14232: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14233: userspace, probably shouldn't be called directly
                   14234: 
                   14235:   docuname: username or courseid of destination for the file
                   14236:   docudom: domain of user/course of destination for the file
                   14237:   formname: same as for userfileupload()
1.1090    raeburn  14238:   fname: filename (including subdirectories) for the file
                   14239:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14240:   allfiles: reference to hash used to store objects found by parser
                   14241:   codebase: reference to hash used for codebases of java objects found by parser
                   14242:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14243:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14244:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14245:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14246:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14247:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14248:   mimetype: reference to scalar to accommodate mime type determined
                   14249:             from File::MMagic if $parser = parse.
1.608     albertel 14250: 
                   14251:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14252:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14253:  was 'overwrite').
                   14254:  
1.608     albertel 14255: 
                   14256: =item *
                   14257: 
                   14258: renameuserfile(): renames an existing userfile to a new name
                   14259: 
                   14260:   Args:
                   14261:    docuname: username or courseid of destination for the file
                   14262:    docudom: domain of user/course of destination for the file
                   14263:    old: current file name (including any subdirs under userfiles)
                   14264:    new: desired file name (including any subdirs under userfiles)
                   14265: 
                   14266: =item *
                   14267: 
                   14268: mkdiruserfile(): creates a directory is a userfiles dir
                   14269: 
                   14270:   Args:
                   14271:    docuname: username or courseid of destination for the file
                   14272:    docudom: domain of user/course of destination for the file
                   14273:    dir: dir to create (including any subdirs under userfiles)
                   14274: 
                   14275: =item *
                   14276: 
                   14277: removeuserfile(): removes a file that exists in userfiles
                   14278: 
                   14279:   Args:
                   14280:    docuname: username or courseid of destination for the file
                   14281:    docudom: domain of user/course of destination for the file
                   14282:    fname: filname to delete (including any subdirs under userfiles)
                   14283: 
                   14284: =item *
                   14285: 
                   14286: removeuploadedurl(): convience function for removeuserfile()
                   14287: 
                   14288:   Args:
                   14289:    url:  a full /uploaded/... url to delete
                   14290: 
1.747     albertel 14291: =item * 
                   14292: 
                   14293: get_portfile_permissions():
                   14294:   Args:
                   14295:     domain: domain of user or course contain the portfolio files
                   14296:     user: name of user or num of course contain the portfolio files
                   14297:   Returns:
                   14298:     hashref of a dump of the proper file_permissions.db
                   14299:    
                   14300: 
                   14301: =item * 
                   14302: 
                   14303: get_access_controls():
                   14304: 
                   14305: Args:
                   14306:   current_permissions: the hash ref returned from get_portfile_permissions()
                   14307:   group: (optional) the group you want the files associated with
                   14308:   file: (optional) the file you want access info on
                   14309: 
                   14310: Returns:
1.749     raeburn  14311:     a hash (keys are file names) of hashes containing
                   14312:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   14313:         values are XML containing access control settings (see below) 
1.747     albertel 14314: 
                   14315: Internal notes:
                   14316: 
1.749     raeburn  14317:  access controls are stored in file_permissions.db as key=value pairs.
                   14318:     key -> path to file/file_name\0uniqueID:scope_end_start
                   14319:         where scope -> public,guest,course,group,domains or users.
                   14320:               end -> UNIX time for end of access (0 -> no end date)
                   14321:               start -> UNIX time for start of access
                   14322: 
                   14323:     value -> XML description of access control
                   14324:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   14325:             <start></start>
                   14326:             <end></end>
                   14327: 
                   14328:             <password></password>  for scope type = guest
                   14329: 
                   14330:             <domain></domain>     for scope type = course or group
                   14331:             <number></number>
                   14332:             <roles id="">
                   14333:              <role></role>
                   14334:              <access></access>
                   14335:              <section></section>
                   14336:              <group></group>
                   14337:             </roles>
                   14338: 
                   14339:             <dom></dom>         for scope type = domains
                   14340: 
                   14341:             <users>             for scope type = users
                   14342:              <user>
                   14343:               <uname></uname>
                   14344:               <udom></udom>
                   14345:              </user>
                   14346:             </users>
                   14347:            </scope> 
                   14348:               
                   14349:  Access data is also aggregated for each file in an additional key=value pair:
                   14350:  key -> path to file/file_name\0accesscontrol 
                   14351:  value -> reference to hash
                   14352:           hash contains key = value pairs
                   14353:           where key = uniqueID:scope_end_start
                   14354:                 value = UNIX time record was last updated
                   14355: 
                   14356:           Used to improve speed of look-ups of access controls for each file.  
                   14357:  
                   14358:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   14359: 
1.1198    raeburn  14360: =item *
                   14361: 
1.749     raeburn  14362: modify_access_controls():
                   14363: 
                   14364: Modifies access controls for a portfolio file
                   14365: Args
                   14366: 1. file name
                   14367: 2. reference to hash of required changes,
                   14368: 3. domain
                   14369: 4. username
                   14370:   where domain,username are the domain of the portfolio owner 
                   14371:   (either a user or a course) 
                   14372: 
                   14373: Returns:
                   14374: 1. result of additions or updates ('ok' or 'error', with error message). 
                   14375: 2. result of deletions ('ok' or 'error', with error message).
                   14376: 3. reference to hash of any new or updated access controls.
                   14377: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   14378:    key = integer (inbound ID)
1.1198    raeburn  14379:    value = uniqueID
                   14380: 
                   14381: =item *
                   14382: 
                   14383: get_timebased_id():
                   14384: 
                   14385: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   14386: course via the Course Editor (e.g., folders, composite pages, 
                   14387: group bulletin boards).
                   14388: 
                   14389: Args: (first three required; six others optional)
                   14390: 
                   14391: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   14392:    docssequence, or name of group
                   14393: 
                   14394: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   14395:    e.g., num, boardids
                   14396: 
                   14397: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   14398:    file will be named nohist_namespace.db
                   14399: 
                   14400: 4. cdom: domain of course; default is current course domain from %env
                   14401: 
                   14402: 5. cnum: course number; default is current course number from %env
                   14403: 
                   14404: 6. idtype: set to concat if an additional digit is to be appended to the 
                   14405:    unix timestamp to form the suffix, if the plain timestamp is already
                   14406:    in use.  Default is to not do this, but simply increment the unix 
                   14407:    timestamp by 1 until a unique key is obtained.
                   14408: 
                   14409: 7. who: holder of locking key; defaults to user:domain for user.
                   14410: 
                   14411: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   14412:    retrying); default is 3.
                   14413: 
                   14414: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   14415: 
                   14416: Returns:
                   14417: 
                   14418: 1. suffix obtained (numeric)
                   14419: 
                   14420: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   14421: 
                   14422: 3. error: contains (localized) error message if an error occurred.
                   14423: 
1.747     albertel 14424: 
1.608     albertel 14425: =back
                   14426: 
1.243     albertel 14427: =head2 HTTP Helper Routines
                   14428: 
                   14429: =over 4
                   14430: 
1.191     harris41 14431: =item *
                   14432: 
                   14433: escape() : unpack non-word characters into CGI-compatible hex codes
                   14434: 
                   14435: =item *
                   14436: 
                   14437: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   14438: 
1.243     albertel 14439: =back
                   14440: 
                   14441: =head1 PRIVATE SUBROUTINES
                   14442: 
                   14443: =head2 Underlying communication routines (Shouldn't call)
                   14444: 
                   14445: =over 4
                   14446: 
                   14447: =item *
                   14448: 
                   14449: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   14450: 
                   14451: =item *
                   14452: 
                   14453: reply() : uses subreply to send a message to remote machine, logs all failures
                   14454: 
                   14455: =item *
                   14456: 
                   14457: critical() : passes a critical message to another server; if cannot
                   14458: get through then place message in connection buffer directory and
                   14459: returns con_delayed, if incapable of saving message, returns
                   14460: con_failed
                   14461: 
                   14462: =item *
                   14463: 
                   14464: reconlonc() : tries to reconnect lonc client processes.
                   14465: 
                   14466: =back
                   14467: 
                   14468: =head2 Resource Access Logging
                   14469: 
                   14470: =over 4
                   14471: 
                   14472: =item *
                   14473: 
                   14474: flushcourselogs() : flush (save) buffer logs and access logs
                   14475: 
                   14476: =item *
                   14477: 
                   14478: courselog($what) : save message for course in hash
                   14479: 
                   14480: =item *
                   14481: 
                   14482: courseacclog($what) : save message for course using &courselog().  Perform
                   14483: special processing for specific resource types (problems, exams, quizzes, etc).
                   14484: 
1.191     harris41 14485: =item *
                   14486: 
                   14487: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   14488: as a PerlChildExitHandler
1.243     albertel 14489: 
                   14490: =back
                   14491: 
                   14492: =head2 Other
                   14493: 
                   14494: =over 4
                   14495: 
                   14496: =item *
                   14497: 
                   14498: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 14499: 
                   14500: =back
                   14501: 
                   14502: =cut
1.877     foxr     14503: 

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