Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1056.4.3
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1056.4.3! raeburn 4: # $Id: lonnet.pm,v 1.1056.4.2 2010/05/26 17:14:43 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1056.4.3! raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs);
1.871 albertel 80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 84: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 85:
1.1 albertel 86: use IO::Socket;
1.31 www 87: use GDBM_File;
1.208 albertel 88: use HTML::LCParser;
1.88 www 89: use Fcntl qw(:flock);
1.870 albertel 90: use Storable qw(thaw nfreeze);
1.539 albertel 91: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 92: use Cache::Memcached;
1.676 albertel 93: use Digest::MD5;
1.790 albertel 94: use Math::Random;
1.1024 raeburn 95: use File::MMagic;
1.807 albertel 96: use LONCAPA qw(:DEFAULT :match);
1.740 www 97: use LONCAPA::Configuration;
1.676 albertel 98:
1.195 www 99: my $readit;
1.550 foxr 100: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 101:
1.619 albertel 102: require Exporter;
103:
104: our @ISA = qw (Exporter);
105: our @EXPORT = qw(%env);
106:
1.449 matthew 107:
1.1 albertel 108: # --------------------------------------------------------------------- Logging
1.729 www 109: {
110: my $logid;
111: sub instructor_log {
1.957 raeburn 112: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
113: if (($cnum eq '') || ($cdom eq '')) {
114: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
115: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
116: }
1.729 www 117: $logid++;
1.957 raeburn 118: my $now = time();
119: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 120: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 121: { $id => {
122: 'exe_uname' => $env{'user.name'},
123: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 124: 'exe_time' => $now,
1.730 www 125: 'exe_ip' => $ENV{'REMOTE_ADDR'},
126: 'delflag' => $delflag,
127: 'logentry' => $storehash,
128: 'uname' => $uname,
129: 'udom' => $udom,
130: }
1.957 raeburn 131: },$cdom,$cnum);
1.729 www 132: }
133: }
1.1 albertel 134:
1.163 harris41 135: sub logtouch {
136: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 137: unless (-e "$execdir/logs/lonnet.log") {
138: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 139: close $fh;
140: }
141: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
142: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
143: }
144:
1.1 albertel 145: sub logthis {
146: my $message=shift;
147: my $execdir=$perlvar{'lonDaemons'};
148: my $now=time;
149: my $local=localtime($now);
1.448 albertel 150: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 151: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
152: print $fh $logstring;
1.448 albertel 153: close($fh);
154: }
1.1 albertel 155: return 1;
156: }
157:
158: sub logperm {
159: my $message=shift;
160: my $execdir=$perlvar{'lonDaemons'};
161: my $now=time;
162: my $local=localtime($now);
1.448 albertel 163: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
164: print $fh "$now:$message:$local\n";
165: close($fh);
166: }
1.1 albertel 167: return 1;
168: }
169:
1.850 albertel 170: sub create_connection {
1.853 albertel 171: my ($hostname,$lonid) = @_;
1.851 albertel 172: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 173: Type => SOCK_STREAM,
174: Timeout => 10);
175: return 0 if (!$client);
1.890 albertel 176: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 177: my $result = <$client>;
178: chomp($result);
179: return 1 if ($result eq 'done');
180: return 0;
181: }
182:
1.983 raeburn 183: sub get_server_timezone {
184: my ($cnum,$cdom) = @_;
185: my $home=&homeserver($cnum,$cdom);
186: if ($home ne 'no_host') {
187: my $cachetime = 24*3600;
188: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
189: if (defined($cached)) {
190: return $timezone;
191: } else {
192: my $timezone = &reply('servertimezone',$home);
193: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
194: }
195: }
196: }
1.850 albertel 197:
1.993 raeburn 198: sub get_server_loncaparev {
1.1056.4.3! raeburn 199: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 200: if (defined($lonhost)) {
201: if (!defined(&hostname($lonhost))) {
202: undef($lonhost);
203: }
204: }
205: if (!defined($lonhost)) {
206: if (defined(&domain($dom,'primary'))) {
207: $lonhost=&domain($dom,'primary');
208: if ($lonhost eq 'no_host') {
209: undef($lonhost);
210: }
211: }
212: }
213: if (defined($lonhost)) {
1.1056.4.3! raeburn 214: my $cachetime = 12*3600;
! 215: if (!$ignore_cache) {
! 216: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
! 217: if (defined($cached)) {
! 218: return $loncaparev;
! 219: }
! 220: }
! 221: my ($answer,$loncaparev);
! 222: my @ids=¤t_machine_ids();
! 223: if (grep(/^\Q$lonhost\E$/,@ids)) {
! 224: $answer = $perlvar{'lonVersion'};
! 225: if ($answer =~ /^[\'\"]?([\d.\-]+)[\'\"]?$/) {
! 226: $loncaparev = $1;
! 227: }
! 228: } else {
! 229: $answer = &reply('serverloncaparev',$lonhost);
! 230: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
! 231: if ($caller eq 'loncron') {
! 232: my $ua=new LWP::UserAgent;
! 233: $ua->timeout(20);
! 234: my $protocol = $protocol{$lonhost};
! 235: $protocol = 'http' if ($protocol ne 'https');
! 236: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
! 237: my $request=new HTTP::Request('GET',$url);
! 238: my $response=$ua->request($request);
! 239: unless ($response->is_error()) {
! 240: my $content = $response->content;
! 241: if ($content =~ /<p>VERSION\:\s*([\d.\-]+)<\/p>/) {
! 242: $loncaparev = $1;
! 243: }
! 244: }
! 245: } else {
! 246: $loncaparev = $loncaparevs{$lonhost};
! 247: }
! 248: } elsif ($answer =~ /^[\'\"]?([\d.\-]+)[\'\"]?$/) {
! 249: $loncaparev = $1;
! 250: }
! 251: }
! 252: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
! 253: }
! 254: }
! 255:
! 256: sub get_server_homeID {
! 257: my ($hostname,$ignore_cache,$caller) = @_;
! 258: unless ($ignore_cache) {
! 259: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
1.993 raeburn 260: if (defined($cached)) {
1.1056.4.3! raeburn 261: return $serverhomeID;
! 262: }
! 263: }
! 264: my $cachetime = 12*3600;
! 265: my $serverhomeID;
! 266: if ($caller eq 'loncron') {
! 267: my @machine_ids = &machine_ids($hostname);
! 268: foreach my $id (@machine_ids) {
! 269: my $response = &reply('serverhomeID',$id);
! 270: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
! 271: $serverhomeID = $response;
! 272: last;
! 273: }
1.993 raeburn 274: }
1.1056.4.3! raeburn 275: if ($serverhomeID eq '') {
! 276: $serverhomeID = $machine_ids[-1];
! 277: }
! 278: } else {
! 279: $serverhomeID = $serverhomeIDs{$hostname};
1.993 raeburn 280: }
1.1056.4.3! raeburn 281: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
1.993 raeburn 282: }
283:
1.1 albertel 284: # -------------------------------------------------- Non-critical communication
285: sub subreply {
286: my ($cmd,$server)=@_;
1.838 albertel 287: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 288: #
289: # With loncnew process trimming, there's a timing hole between lonc server
290: # process exit and the master server picking up the listen on the AF_UNIX
291: # socket. In that time interval, a lock file will exist:
292:
293: my $lockfile=$peerfile.".lock";
294: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
295: sleep(1);
296: }
297: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 298: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 299: #
1.550 foxr 300: # We'll give the connection a few tries before abandoning it. If
301: # connection is not possible, we'll con_lost back to the client.
302: #
303: my $client;
304: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
305: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
306: Type => SOCK_STREAM,
307: Timeout => 10);
1.869 albertel 308: if ($client) {
1.550 foxr 309: last; # Connected!
1.850 albertel 310: } else {
1.853 albertel 311: &create_connection(&hostname($server),$server);
1.550 foxr 312: }
1.850 albertel 313: sleep(1); # Try again later if failed connection.
1.550 foxr 314: }
315: my $answer;
316: if ($client) {
1.704 albertel 317: print $client "sethost:$server:$cmd\n";
1.550 foxr 318: $answer=<$client>;
319: if (!$answer) { $answer="con_lost"; }
320: chomp($answer);
321: } else {
322: $answer = 'con_lost'; # Failed connection.
323: }
1.1 albertel 324: return $answer;
325: }
326:
327: sub reply {
328: my ($cmd,$server)=@_;
1.838 albertel 329: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 330: my $answer=subreply($cmd,$server);
1.65 www 331: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 332: &logthis("<font color=\"blue\">WARNING:".
1.12 www 333: " $cmd to $server returned $answer</font>");
334: }
1.1 albertel 335: return $answer;
336: }
337:
338: # ----------------------------------------------------------- Send USR1 to lonc
339:
340: sub reconlonc {
1.891 albertel 341: my ($lonid) = @_;
342: my $hostname = &hostname($lonid);
343: if ($lonid) {
344: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
345: if ($hostname && -e $peerfile) {
346: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
347: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
348: Type => SOCK_STREAM,
349: Timeout => 10);
350: if ($client) {
351: print $client ("reset_retries\n");
352: my $answer=<$client>;
353: #reset just this one.
354: }
355: }
356: return;
357: }
358:
1.836 www 359: &logthis("Trying to reconnect lonc");
1.1 albertel 360: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 361: if (open(my $fh,"<$loncfile")) {
1.1 albertel 362: my $loncpid=<$fh>;
363: chomp($loncpid);
364: if (kill 0 => $loncpid) {
365: &logthis("lonc at pid $loncpid responding, sending USR1");
366: kill USR1 => $loncpid;
367: sleep 1;
1.836 www 368: } else {
1.12 www 369: &logthis(
1.672 albertel 370: "<font color=\"blue\">WARNING:".
1.12 www 371: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 372: }
373: } else {
1.836 www 374: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 375: }
376: }
377:
378: # ------------------------------------------------------ Critical communication
1.12 www 379:
1.1 albertel 380: sub critical {
381: my ($cmd,$server)=@_;
1.838 albertel 382: unless (&hostname($server)) {
1.672 albertel 383: &logthis("<font color=\"blue\">WARNING:".
1.89 www 384: " Critical message to unknown server ($server)</font>");
385: return 'no_such_host';
386: }
1.1 albertel 387: my $answer=reply($cmd,$server);
388: if ($answer eq 'con_lost') {
389: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 390: my $answer=reply($cmd,$server);
1.1 albertel 391: if ($answer eq 'con_lost') {
392: my $now=time;
393: my $middlename=$cmd;
1.5 www 394: $middlename=substr($middlename,0,16);
1.1 albertel 395: $middlename=~s/\W//g;
396: my $dfilename=
1.305 www 397: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
398: $dumpcount++;
1.1 albertel 399: {
1.448 albertel 400: my $dfh;
401: if (open($dfh,">$dfilename")) {
402: print $dfh "$cmd\n";
403: close($dfh);
404: }
1.1 albertel 405: }
406: sleep 2;
407: my $wcmd='';
408: {
1.448 albertel 409: my $dfh;
410: if (open($dfh,"<$dfilename")) {
411: $wcmd=<$dfh>;
412: close($dfh);
413: }
1.1 albertel 414: }
415: chomp($wcmd);
1.7 www 416: if ($wcmd eq $cmd) {
1.672 albertel 417: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 418: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 419: &logperm("D:$server:$cmd");
420: return 'con_delayed';
421: } else {
1.672 albertel 422: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 423: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 424: &logperm("F:$server:$cmd");
425: return 'con_failed';
426: }
427: }
428: }
429: return $answer;
1.405 albertel 430: }
431:
1.755 albertel 432: # ------------------------------------------- check if return value is an error
433:
434: sub error {
435: my ($result) = @_;
1.756 albertel 436: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 437: if ($2 == 2) { return undef; }
438: return $1;
439: }
440: return undef;
441: }
442:
1.783 albertel 443: sub convert_and_load_session_env {
444: my ($lonidsdir,$handle)=@_;
445: my @profile;
446: {
1.917 albertel 447: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
448: if (!$opened) {
1.915 albertel 449: return 0;
450: }
1.783 albertel 451: flock($idf,LOCK_SH);
452: @profile=<$idf>;
453: close($idf);
454: }
455: my %temp_env;
456: foreach my $line (@profile) {
1.786 albertel 457: if ($line !~ m/=/) {
458: return 0;
459: }
1.783 albertel 460: chomp($line);
461: my ($envname,$envvalue)=split(/=/,$line,2);
462: $temp_env{&unescape($envname)} = &unescape($envvalue);
463: }
464: unlink("$lonidsdir/$handle.id");
465: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
466: 0640)) {
467: %disk_env = %temp_env;
468: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
469: untie(%disk_env);
470: }
1.786 albertel 471: return 1;
1.783 albertel 472: }
473:
1.374 www 474: # ------------------------------------------- Transfer profile into environment
1.780 albertel 475: my $env_loaded;
476: sub transfer_profile_to_env {
1.788 albertel 477: my ($lonidsdir,$handle,$force_transfer) = @_;
478: if (!$force_transfer && $env_loaded) { return; }
1.374 www 479:
1.720 albertel 480: if (!defined($lonidsdir)) {
481: $lonidsdir = $perlvar{'lonIDsDir'};
482: }
483: if (!defined($handle)) {
484: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
485: }
486:
1.786 albertel 487: my $convert;
488: {
1.917 albertel 489: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
490: if (!$opened) {
1.915 albertel 491: return;
492: }
1.786 albertel 493: flock($idf,LOCK_SH);
494: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
495: &GDBM_READER(),0640)) {
496: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
497: untie(%disk_env);
498: } else {
499: $convert = 1;
500: }
501: }
502: if ($convert) {
503: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
504: &logthis("Failed to load session, or convert session.");
505: }
1.374 www 506: }
1.783 albertel 507:
1.786 albertel 508: my %remove;
1.783 albertel 509: while ( my $envname = each(%env) ) {
1.433 matthew 510: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
511: if ($time < time-300) {
1.783 albertel 512: $remove{$key}++;
1.433 matthew 513: }
514: }
515: }
1.783 albertel 516:
1.619 albertel 517: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 518: $env_loaded=1;
1.783 albertel 519: foreach my $expired_key (keys(%remove)) {
1.433 matthew 520: &delenv($expired_key);
1.374 www 521: }
1.1 albertel 522: }
523:
1.916 albertel 524: # ---------------------------------------------------- Check for valid session
525: sub check_for_valid_session {
526: my ($r) = @_;
527: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
528: my $lonid=$cookies{'lonID'};
529: return undef if (!$lonid);
530:
531: my $handle=&LONCAPA::clean_handle($lonid->value);
532: my $lonidsdir=$r->dir_config('lonIDsDir');
533: return undef if (!-e "$lonidsdir/$handle.id");
534:
1.917 albertel 535: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
536: return undef if (!$opened);
1.916 albertel 537:
538: flock($idf,LOCK_SH);
539: my %disk_env;
540: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
541: &GDBM_READER(),0640)) {
542: return undef;
543: }
544:
545: if (!defined($disk_env{'user.name'})
546: || !defined($disk_env{'user.domain'})) {
547: return undef;
548: }
549: return $handle;
550: }
551:
1.830 albertel 552: sub timed_flock {
553: my ($file,$lock_type) = @_;
554: my $failed=0;
555: eval {
556: local $SIG{__DIE__}='DEFAULT';
557: local $SIG{ALRM}=sub {
558: $failed=1;
559: die("failed lock");
560: };
561: alarm(13);
562: flock($file,$lock_type);
563: alarm(0);
564: };
565: if ($failed) {
566: return undef;
567: } else {
568: return 1;
569: }
570: }
571:
1.5 www 572: # ---------------------------------------------------------- Append Environment
573:
574: sub appenv {
1.949 raeburn 575: my ($newenv,$roles) = @_;
576: if (ref($newenv) eq 'HASH') {
577: foreach my $key (keys(%{$newenv})) {
578: my $refused = 0;
579: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
580: $refused = 1;
581: if (ref($roles) eq 'ARRAY') {
582: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
583: if (grep(/^\Q$role\E$/,@{$roles})) {
584: $refused = 0;
585: }
586: }
587: }
588: if ($refused) {
589: &logthis("<font color=\"blue\">WARNING: ".
590: "Attempt to modify environment ".$key." to ".$newenv->{$key}
591: .'</font>');
592: delete($newenv->{$key});
593: } else {
594: $env{$key}=$newenv->{$key};
595: }
596: }
597: my $opened = open(my $env_file,'+<',$env{'user.environment'});
598: if ($opened
599: && &timed_flock($env_file,LOCK_EX)
600: &&
601: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
602: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
603: while (my ($key,$value) = each(%{$newenv})) {
604: $disk_env{$key} = $value;
605: }
606: untie(%disk_env);
1.35 www 607: }
1.191 harris41 608: }
1.56 www 609: return 'ok';
610: }
611: # ----------------------------------------------------- Delete from Environment
612:
613: sub delenv {
1.987 raeburn 614: my ($delthis,$regexp) = @_;
1.56 www 615: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 616: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 617: "Attempt to delete from environment ".$delthis);
618: return 'error';
619: }
1.917 albertel 620: my $opened = open(my $env_file,'+<',$env{'user.environment'});
621: if ($opened
1.915 albertel 622: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 623: &&
624: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
625: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 626: foreach my $key (keys(%disk_env)) {
1.987 raeburn 627: if ($regexp) {
628: if ($key=~/^$delthis/) {
629: delete($env{$key});
630: delete($disk_env{$key});
631: }
632: } else {
633: if ($key=~/^\Q$delthis\E/) {
634: delete($env{$key});
635: delete($disk_env{$key});
636: }
637: }
1.448 albertel 638: }
1.783 albertel 639: untie(%disk_env);
1.5 www 640: }
641: return 'ok';
1.369 albertel 642: }
643:
1.790 albertel 644: sub get_env_multiple {
645: my ($name) = @_;
646: my @values;
647: if (defined($env{$name})) {
648: # exists is it an array
649: if (ref($env{$name})) {
650: @values=@{ $env{$name} };
651: } else {
652: $values[0]=$env{$name};
653: }
654: }
655: return(@values);
656: }
657:
1.958 www 658: # ------------------------------------------------------------------- Locking
659:
660: sub set_lock {
661: my ($text)=@_;
662: $locknum++;
663: my $id=$$.'-'.$locknum;
664: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
665: 'session.lock.'.$id => $text});
666: return $id;
667: }
668:
669: sub get_locks {
670: my $num=0;
671: my %texts=();
672: foreach my $lock (split(/\,/,$env{'session.locks'})) {
673: if ($lock=~/\w/) {
674: $num++;
675: $texts{$lock}=$env{'session.lock.'.$lock};
676: }
677: }
678: return ($num,%texts);
679: }
680:
681: sub remove_lock {
682: my ($id)=@_;
683: my $newlocks='';
684: foreach my $lock (split(/\,/,$env{'session.locks'})) {
685: if (($lock=~/\w/) && ($lock ne $id)) {
686: $newlocks.=','.$lock;
687: }
688: }
689: &appenv({'session.locks' => $newlocks});
690: &delenv('session.lock.'.$id);
691: }
692:
693: sub remove_all_locks {
694: my $activelocks=$env{'session.locks'};
695: foreach my $lock (split(/\,/,$env{'session.locks'})) {
696: if ($lock=~/\w/) {
697: &remove_lock($lock);
698: }
699: }
700: }
701:
702:
1.369 albertel 703: # ------------------------------------------ Find out current server userload
704: sub userload {
705: my $numusers=0;
706: {
707: opendir(LONIDS,$perlvar{'lonIDsDir'});
708: my $filename;
709: my $curtime=time;
710: while ($filename=readdir(LONIDS)) {
1.925 albertel 711: next if ($filename eq '.' || $filename eq '..');
712: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 713: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 714: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 715: }
716: closedir(LONIDS);
717: }
718: my $userloadpercent=0;
719: my $maxuserload=$perlvar{'lonUserLoadLim'};
720: if ($maxuserload) {
1.371 albertel 721: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 722: }
1.372 albertel 723: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 724: return $userloadpercent;
1.283 www 725: }
726:
727: # ------------------------------------------ Fight off request when overloaded
728:
729: sub overloaderror {
730: my ($r,$checkserver)=@_;
731: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
732: my $loadavg;
733: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 734: open(my $loadfile,'/proc/loadavg');
1.283 www 735: $loadavg=<$loadfile>;
736: $loadavg =~ s/\s.*//g;
1.285 matthew 737: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 738: close($loadfile);
1.283 www 739: } else {
740: $loadavg=&reply('load',$checkserver);
741: }
1.285 matthew 742: my $overload=$loadavg-100;
1.283 www 743: if ($overload>0) {
1.285 matthew 744: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 745: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 746: return 413;
1.283 www 747: }
748: return '';
1.5 www 749: }
1.1 albertel 750:
751: # ------------------------------ Find server with least workload from spare.tab
1.11 www 752:
1.1 albertel 753: sub spareserver {
1.670 albertel 754: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 755: my $spare_server;
1.370 albertel 756: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 757: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
758: : $userloadpercent;
759:
760: foreach my $try_server (@{ $spareid{'primary'} }) {
761: ($spare_server, $lowest_load) =
762: &compare_server_load($try_server, $spare_server, $lowest_load);
763: }
764:
765: my $found_server = ($spare_server ne '' && $lowest_load < 100);
766:
767: if (!$found_server) {
768: foreach my $try_server (@{ $spareid{'default'} }) {
769: ($spare_server, $lowest_load) =
770: &compare_server_load($try_server, $spare_server, $lowest_load);
771: }
772: }
773:
774: if (!$want_server_name) {
1.968 raeburn 775: my $protocol = 'http';
776: if ($protocol{$spare_server} eq 'https') {
777: $protocol = $protocol{$spare_server};
778: }
1.1001 raeburn 779: if (defined($spare_server)) {
780: my $hostname = &hostname($spare_server);
781: if (defined($hostname)) {
782: $spare_server = $protocol.'://'.$hostname;
783: }
784: }
1.784 albertel 785: }
786: return $spare_server;
787: }
788:
789: sub compare_server_load {
790: my ($try_server, $spare_server, $lowest_load) = @_;
791:
792: my $loadans = &reply('load', $try_server);
793: my $userloadans = &reply('userload',$try_server);
794:
795: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1056.4.3! raeburn 796: return; #didn't get a number from the server
1.784 albertel 797: }
798:
799: my $load;
800: if ($loadans =~ /\d/) {
801: if ($userloadans =~ /\d/) {
802: #both are numbers, pick the bigger one
803: $load = ($loadans > $userloadans) ? $loadans
804: : $userloadans;
1.411 albertel 805: } else {
1.784 albertel 806: $load = $loadans;
1.411 albertel 807: }
1.784 albertel 808: } else {
809: $load = $userloadans;
810: }
811:
812: if (($load =~ /\d/) && ($load < $lowest_load)) {
813: $spare_server = $try_server;
814: $lowest_load = $load;
1.370 albertel 815: }
1.784 albertel 816: return ($spare_server,$lowest_load);
1.202 matthew 817: }
1.914 albertel 818:
819: # --------------------------- ask offload servers if user already has a session
820: sub find_existing_session {
821: my ($udom,$uname) = @_;
822: foreach my $try_server (@{ $spareid{'primary'} },
823: @{ $spareid{'default'} }) {
824: return $try_server if (&has_user_session($try_server, $udom, $uname));
825: }
826: return;
827: }
828:
829: # -------------------------------- ask if server already has a session for user
830: sub has_user_session {
831: my ($lonid,$udom,$uname) = @_;
832: my $result = &reply(join(':','userhassession',
833: map {&escape($_)} ($udom,$uname)),$lonid);
834: return 1 if ($result eq 'ok');
835:
836: return 0;
837: }
838:
1.1056.4.3! raeburn 839: # --------- determine least loaded server in a user's domain which allows login
! 840:
! 841: sub choose_server {
! 842: my ($udom) = @_;
! 843: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
! 844: my %servers = &get_servers($udom);
! 845: my $lowest_load = 30000;
! 846: my ($login_host,$hostname);
! 847: foreach my $lonhost (keys(%servers)) {
! 848: my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
! 849: if ($loginvia eq '') {
! 850: ($login_host, $lowest_load) =
! 851: &compare_server_load($lonhost, $login_host, $lowest_load);
! 852: }
! 853: }
! 854: if ($login_host ne '') {
! 855: $hostname = $servers{$login_host};
! 856: }
! 857: return ($login_host,$hostname);
! 858: }
! 859:
1.202 matthew 860: # --------------------------------------------- Try to change a user's password
861:
862: sub changepass {
1.799 raeburn 863: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 864: $currentpass = &escape($currentpass);
865: $newpass = &escape($newpass);
1.1030 raeburn 866: my $lonhost = $perlvar{'lonHostID'};
867: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 868: $server);
869: if (! $answer) {
870: &logthis("No reply on password change request to $server ".
871: "by $uname in domain $udom.");
872: } elsif ($answer =~ "^ok") {
873: &logthis("$uname in $udom successfully changed their password ".
874: "on $server.");
875: } elsif ($answer =~ "^pwchange_failure") {
876: &logthis("$uname in $udom was unable to change their password ".
877: "on $server. The action was blocked by either lcpasswd ".
878: "or pwchange");
879: } elsif ($answer =~ "^non_authorized") {
880: &logthis("$uname in $udom did not get their password correct when ".
881: "attempting to change it on $server.");
882: } elsif ($answer =~ "^auth_mode_error") {
883: &logthis("$uname in $udom attempted to change their password despite ".
884: "not being locally or internally authenticated on $server.");
885: } elsif ($answer =~ "^unknown_user") {
886: &logthis("$uname in $udom attempted to change their password ".
887: "on $server but were unable to because $server is not ".
888: "their home server.");
889: } elsif ($answer =~ "^refused") {
890: &logthis("$server refused to change $uname in $udom password because ".
891: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 892: } elsif ($answer =~ "invalid_client") {
893: &logthis("$server refused to change $uname in $udom password because ".
894: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 895: }
896: return $answer;
1.1 albertel 897: }
898:
1.169 harris41 899: # ----------------------- Try to determine user's current authentication scheme
900:
901: sub queryauthenticate {
902: my ($uname,$udom)=@_;
1.456 albertel 903: my $uhome=&homeserver($uname,$udom);
904: if (!$uhome) {
905: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
906: return 'no_host';
907: }
908: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
909: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
910: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 911: }
1.456 albertel 912: return $answer;
1.169 harris41 913: }
914:
1.1 albertel 915: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 916:
1.1 albertel 917: sub authenticate {
1.1056.4.3! raeburn 918: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 919: $upass=&escape($upass);
920: $uname= &LONCAPA::clean_username($uname);
1.836 www 921: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 922: my $newhome;
1.836 www 923: if ((!$uhome) || ($uhome eq 'no_host')) {
924: # Maybe the machine was offline and only re-appeared again recently?
925: &reconlonc();
926: # One more
1.952 raeburn 927: $uhome=&homeserver($uname,$udom,1);
928: if (($uhome eq 'no_host') && $checkdefauth) {
929: if (defined(&domain($udom,'primary'))) {
930: $newhome=&domain($udom,'primary');
931: }
932: if ($newhome ne '') {
933: $uhome = $newhome;
934: }
935: }
1.836 www 936: if ((!$uhome) || ($uhome eq 'no_host')) {
937: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 938: return 'no_host';
939: }
1.1 albertel 940: }
1.1056.4.3! raeburn 941: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 942: if ($answer eq 'authorized') {
1.952 raeburn 943: if ($newhome) {
944: &logthis("User $uname at $udom authorized by $uhome, but needs account");
945: return 'no_account_on_host';
946: } else {
947: &logthis("User $uname at $udom authorized by $uhome");
948: return $uhome;
949: }
1.471 albertel 950: }
951: if ($answer eq 'non_authorized') {
952: &logthis("User $uname at $udom rejected by $uhome");
953: return 'no_host';
1.9 www 954: }
1.471 albertel 955: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 956: return 'no_host';
957: }
958:
1.1056.4.3! raeburn 959: sub can_host_session {
! 960: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
! 961: my $canhost = 1;
! 962: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
! 963: if (ref($remotesessions) eq 'HASH') {
! 964: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
! 965: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
! 966: $canhost = 0;
! 967: } else {
! 968: $canhost = 1;
! 969: }
! 970: }
! 971: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
! 972: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
! 973: $canhost = 1;
! 974: } else {
! 975: $canhost = 0;
! 976: }
! 977: }
! 978: if ($canhost) {
! 979: if ($remotesessions->{'version'} ne '') {
! 980: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
! 981: if ($reqmajor ne '' && $reqminor ne '') {
! 982: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
! 983: my $major = $1;
! 984: my $minor = $2;
! 985: if (($major < $reqmajor ) ||
! 986: (($major == $reqmajor) && ($minor < $reqminor))) {
! 987: $canhost = 0;
! 988: }
! 989: } else {
! 990: $canhost = 0;
! 991: }
! 992: }
! 993: }
! 994: }
! 995: }
! 996: if ($canhost) {
! 997: if (ref($hostedsessions) eq 'HASH') {
! 998: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
! 999: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
! 1000: $canhost = 0;
! 1001: } else {
! 1002: $canhost = 1;
! 1003: }
! 1004: }
! 1005: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
! 1006: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
! 1007: $canhost = 1;
! 1008: } else {
! 1009: $canhost = 0;
! 1010: }
! 1011: }
! 1012: }
! 1013: }
! 1014: return $canhost;
! 1015: }
! 1016:
1.1 albertel 1017: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1018:
1.599 albertel 1019: my %homecache;
1.1 albertel 1020: sub homeserver {
1.230 stredwic 1021: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1022: my $index="$uname:$udom";
1.426 albertel 1023:
1.599 albertel 1024: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1025:
1026: my %servers = &get_servers($udom,'library');
1027: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1028: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1029: exists($badServerCache{$tryserver}));
1.841 albertel 1030:
1031: my $answer=reply("home:$udom:$uname",$tryserver);
1032: if ($answer eq 'found') {
1033: delete($badServerCache{$tryserver});
1034: return $homecache{$index}=$tryserver;
1035: } elsif ($answer eq 'no_host') {
1036: $badServerCache{$tryserver}=1;
1037: }
1.1 albertel 1038: }
1039: return 'no_host';
1.70 www 1040: }
1041:
1042: # ------------------------------------- Find the usernames behind a list of IDs
1043:
1044: sub idget {
1045: my ($udom,@ids)=@_;
1046: my %returnhash=();
1047:
1.841 albertel 1048: my %servers = &get_servers($udom,'library');
1049: foreach my $tryserver (keys(%servers)) {
1050: my $idlist=join('&',@ids);
1051: $idlist=~tr/A-Z/a-z/;
1052: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1053: my @answer=();
1054: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1055: @answer=split(/\&/,$reply);
1056: } ;
1057: my $i;
1058: for ($i=0;$i<=$#ids;$i++) {
1059: if ($answer[$i]) {
1060: $returnhash{$ids[$i]}=$answer[$i];
1061: }
1062: }
1063: }
1.70 www 1064: return %returnhash;
1065: }
1066:
1067: # ------------------------------------- Find the IDs behind a list of usernames
1068:
1069: sub idrget {
1070: my ($udom,@unames)=@_;
1071: my %returnhash=();
1.800 albertel 1072: foreach my $uname (@unames) {
1073: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1074: }
1.70 www 1075: return %returnhash;
1076: }
1077:
1078: # ------------------------------- Store away a list of names and associated IDs
1079:
1080: sub idput {
1081: my ($udom,%ids)=@_;
1082: my %servers=();
1.800 albertel 1083: foreach my $uname (keys(%ids)) {
1084: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1085: my $uhom=&homeserver($uname,$udom);
1.70 www 1086: if ($uhom ne 'no_host') {
1.800 albertel 1087: my $id=&escape($ids{$uname});
1.70 www 1088: $id=~tr/A-Z/a-z/;
1.800 albertel 1089: my $esc_unam=&escape($uname);
1.70 www 1090: if ($servers{$uhom}) {
1.800 albertel 1091: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1092: } else {
1.800 albertel 1093: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1094: }
1095: }
1.191 harris41 1096: }
1.800 albertel 1097: foreach my $server (keys(%servers)) {
1098: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1099: }
1.344 www 1100: }
1101:
1.1023 raeburn 1102: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1103: sub dump_dom {
1.1023 raeburn 1104: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1105: if (!$udom) {
1106: $udom=$env{'user.domain'};
1107: }
1108: my %returnhash;
1.1023 raeburn 1109: if ($udom) {
1110: my $uname = &get_domainconfiguser($udom);
1111: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1112: }
1113: return %returnhash;
1114: }
1115:
1.1023 raeburn 1116: # ------------------------------------------ get items from domain db files
1.806 raeburn 1117:
1118: sub get_dom {
1.860 raeburn 1119: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1120: my $items='';
1121: foreach my $item (@$storearr) {
1122: $items.=&escape($item).'&';
1123: }
1124: $items=~s/\&$//;
1.860 raeburn 1125: if (!$udom) {
1126: $udom=$env{'user.domain'};
1127: if (defined(&domain($udom,'primary'))) {
1128: $uhome=&domain($udom,'primary');
1129: } else {
1.874 albertel 1130: undef($uhome);
1.860 raeburn 1131: }
1132: } else {
1133: if (!$uhome) {
1134: if (defined(&domain($udom,'primary'))) {
1135: $uhome=&domain($udom,'primary');
1136: }
1137: }
1138: }
1139: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1140: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1141: my %returnhash;
1.875 albertel 1142: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1143: return %returnhash;
1144: }
1.806 raeburn 1145: my @pairs=split(/\&/,$rep);
1146: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1147: return @pairs;
1148: }
1149: my $i=0;
1150: foreach my $item (@$storearr) {
1151: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1152: $i++;
1153: }
1154: return %returnhash;
1155: } else {
1.880 banghart 1156: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1157: }
1158: }
1159:
1160: # -------------------------------------------- put items in domain db files
1161:
1162: sub put_dom {
1.860 raeburn 1163: my ($namespace,$storehash,$udom,$uhome)=@_;
1164: if (!$udom) {
1165: $udom=$env{'user.domain'};
1166: if (defined(&domain($udom,'primary'))) {
1167: $uhome=&domain($udom,'primary');
1168: } else {
1.874 albertel 1169: undef($uhome);
1.860 raeburn 1170: }
1171: } else {
1172: if (!$uhome) {
1173: if (defined(&domain($udom,'primary'))) {
1174: $uhome=&domain($udom,'primary');
1175: }
1176: }
1177: }
1178: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1179: my $items='';
1180: foreach my $item (keys(%$storehash)) {
1181: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1182: }
1183: $items=~s/\&$//;
1184: return &reply("putdom:$udom:$namespace:$items",$uhome);
1185: } else {
1.860 raeburn 1186: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1187: }
1188: }
1189:
1.1023 raeburn 1190: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1191: sub newput_dom {
1.1023 raeburn 1192: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1193: my $result;
1194: if (!$udom) {
1195: $udom=$env{'user.domain'};
1196: }
1.1023 raeburn 1197: if ($udom) {
1198: my $uname = &get_domainconfiguser($udom);
1199: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1200: }
1201: return $result;
1202: }
1203:
1.1023 raeburn 1204: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1205: sub del_dom {
1.1023 raeburn 1206: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1207: if (ref($storearr) eq 'ARRAY') {
1208: if (!$udom) {
1209: $udom=$env{'user.domain'};
1210: }
1.1023 raeburn 1211: if ($udom) {
1212: my $uname = &get_domainconfiguser($udom);
1213: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1214: }
1215: }
1216: }
1217:
1.1023 raeburn 1218: # ----------------------------------construct domainconfig user for a domain
1219: sub get_domainconfiguser {
1220: my ($udom) = @_;
1221: return $udom.'-domainconfig';
1222: }
1223:
1.837 raeburn 1224: sub retrieve_inst_usertypes {
1225: my ($udom) = @_;
1226: my (%returnhash,@order);
1.989 raeburn 1227: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1228: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1229: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1230: %returnhash = %{$domdefs{'inststatustypes'}};
1231: @order = @{$domdefs{'inststatusorder'}};
1232: } else {
1233: if (defined(&domain($udom,'primary'))) {
1234: my $uhome=&domain($udom,'primary');
1235: my $rep=&reply("inst_usertypes:$udom",$uhome);
1236: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1237: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1238: return (\%returnhash,\@order);
1239: }
1240: my ($hashitems,$orderitems) = split(/:/,$rep);
1241: my @pairs=split(/\&/,$hashitems);
1242: foreach my $item (@pairs) {
1243: my ($key,$value)=split(/=/,$item,2);
1244: $key = &unescape($key);
1245: next if ($key =~ /^error: 2 /);
1246: $returnhash{$key}=&thaw_unescape($value);
1247: }
1248: my @esc_order = split(/\&/,$orderitems);
1249: foreach my $item (@esc_order) {
1250: push(@order,&unescape($item));
1251: }
1252: } else {
1253: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1254: }
1255: }
1256: return (\%returnhash,\@order);
1257: }
1258:
1.868 raeburn 1259: sub is_domainimage {
1260: my ($url) = @_;
1261: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1262: if (&domain($1) ne '') {
1263: return '1';
1264: }
1265: }
1266: return;
1267: }
1268:
1.899 raeburn 1269: sub inst_directory_query {
1270: my ($srch) = @_;
1271: my $udom = $srch->{'srchdomain'};
1272: my %results;
1273: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1274: my $outcome;
1.899 raeburn 1275: if ($homeserver ne '') {
1.904 albertel 1276: my $queryid=&reply("querysend:instdirsearch:".
1277: &escape($srch->{'srchby'}).':'.
1278: &escape($srch->{'srchterm'}).':'.
1279: &escape($srch->{'srchtype'}),$homeserver);
1280: my $host=&hostname($homeserver);
1281: if ($queryid !~/^\Q$host\E\_/) {
1282: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1283: return;
1284: }
1285: my $response = &get_query_reply($queryid);
1286: my $maxtries = 5;
1287: my $tries = 1;
1288: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1289: $response = &get_query_reply($queryid);
1290: $tries ++;
1291: }
1292:
1293: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1294: if ($response eq 'unavailable') {
1295: $outcome = $response;
1296: } else {
1297: $outcome = 'ok';
1298: my @matches = split(/\n/,$response);
1299: foreach my $match (@matches) {
1300: my ($key,$value) = split(/=/,$match);
1301: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1302: }
1.899 raeburn 1303: }
1304: }
1305: }
1.909 raeburn 1306: return ($outcome,%results);
1.899 raeburn 1307: }
1308:
1309: sub usersearch {
1310: my ($srch) = @_;
1311: my $dom = $srch->{'srchdomain'};
1312: my %results;
1313: my %libserv = &all_library();
1314: my $query = 'usersearch';
1315: foreach my $tryserver (keys(%libserv)) {
1316: if (&host_domain($tryserver) eq $dom) {
1317: my $host=&hostname($tryserver);
1318: my $queryid=
1.911 raeburn 1319: &reply("querysend:".&escape($query).':'.
1320: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1321: &escape($srch->{'srchtype'}).':'.
1322: &escape($srch->{'srchterm'}),$tryserver);
1323: if ($queryid !~/^\Q$host\E\_/) {
1324: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1325: next;
1.899 raeburn 1326: }
1327: my $reply = &get_query_reply($queryid);
1328: my $maxtries = 1;
1329: my $tries = 1;
1330: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1331: $reply = &get_query_reply($queryid);
1332: $tries ++;
1333: }
1334: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1335: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1336: } else {
1.911 raeburn 1337: my @matches;
1338: if ($reply =~ /\n/) {
1339: @matches = split(/\n/,$reply);
1340: } else {
1341: @matches = split(/\&/,$reply);
1342: }
1.899 raeburn 1343: foreach my $match (@matches) {
1344: my ($uname,$udom,%userhash);
1.911 raeburn 1345: foreach my $entry (split(/:/,$match)) {
1346: my ($key,$value) =
1347: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1348: $userhash{$key} = $value;
1349: if ($key eq 'username') {
1350: $uname = $value;
1351: } elsif ($key eq 'domain') {
1352: $udom = $value;
1.911 raeburn 1353: }
1.899 raeburn 1354: }
1355: $results{$uname.':'.$udom} = \%userhash;
1356: }
1357: }
1358: }
1359: }
1360: return %results;
1361: }
1362:
1.912 raeburn 1363: sub get_instuser {
1364: my ($udom,$uname,$id) = @_;
1365: my $homeserver = &domain($udom,'primary');
1366: my ($outcome,%results);
1367: if ($homeserver ne '') {
1368: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1369: &escape($id).':'.&escape($udom),$homeserver);
1370: my $host=&hostname($homeserver);
1371: if ($queryid !~/^\Q$host\E\_/) {
1372: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1373: return;
1374: }
1375: my $response = &get_query_reply($queryid);
1376: my $maxtries = 5;
1377: my $tries = 1;
1378: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1379: $response = &get_query_reply($queryid);
1380: $tries ++;
1381: }
1382: if (!&error($response) && $response ne 'refused') {
1383: if ($response eq 'unavailable') {
1384: $outcome = $response;
1385: } else {
1386: $outcome = 'ok';
1387: my @matches = split(/\n/,$response);
1388: foreach my $match (@matches) {
1389: my ($key,$value) = split(/=/,$match);
1390: $results{&unescape($key)} = &thaw_unescape($value);
1391: }
1392: }
1393: }
1394: }
1395: my %userinfo;
1396: if (ref($results{$uname}) eq 'HASH') {
1397: %userinfo = %{$results{$uname}};
1398: }
1399: return ($outcome,%userinfo);
1400: }
1401:
1402: sub inst_rulecheck {
1.923 raeburn 1403: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1404: my %returnhash;
1405: if ($udom ne '') {
1406: if (ref($rules) eq 'ARRAY') {
1407: @{$rules} = map {&escape($_);} (@{$rules});
1408: my $rulestr = join(':',@{$rules});
1409: my $homeserver=&domain($udom,'primary');
1410: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1411: my $response;
1412: if ($item eq 'username') {
1413: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1414: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1415: $homeserver));
1.923 raeburn 1416: } elsif ($item eq 'id') {
1417: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1418: ':'.&escape($id).':'.$rulestr,
1419: $homeserver));
1.945 raeburn 1420: } elsif ($item eq 'selfcreate') {
1421: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1422: &escape($udom).':'.&escape($uname).
1423: ':'.$rulestr,$homeserver));
1.923 raeburn 1424: }
1.912 raeburn 1425: if ($response ne 'refused') {
1426: my @pairs=split(/\&/,$response);
1427: foreach my $item (@pairs) {
1428: my ($key,$value)=split(/=/,$item,2);
1429: $key = &unescape($key);
1430: next if ($key =~ /^error: 2 /);
1431: $returnhash{$key}=&thaw_unescape($value);
1432: }
1433: }
1434: }
1435: }
1436: }
1437: return %returnhash;
1438: }
1439:
1440: sub inst_userrules {
1.923 raeburn 1441: my ($udom,$check) = @_;
1.912 raeburn 1442: my (%ruleshash,@ruleorder);
1443: if ($udom ne '') {
1444: my $homeserver=&domain($udom,'primary');
1445: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1446: my $response;
1447: if ($check eq 'id') {
1448: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1449: $homeserver);
1.943 raeburn 1450: } elsif ($check eq 'email') {
1451: $response=&reply('instemailrules:'.&escape($udom),
1452: $homeserver);
1.923 raeburn 1453: } else {
1454: $response=&reply('instuserrules:'.&escape($udom),
1455: $homeserver);
1456: }
1.912 raeburn 1457: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1458: ($response ne 'unknown_cmd') &&
1.912 raeburn 1459: ($response ne 'no_such_host')) {
1460: my ($hashitems,$orderitems) = split(/:/,$response);
1461: my @pairs=split(/\&/,$hashitems);
1462: foreach my $item (@pairs) {
1463: my ($key,$value)=split(/=/,$item,2);
1464: $key = &unescape($key);
1465: next if ($key =~ /^error: 2 /);
1466: $ruleshash{$key}=&thaw_unescape($value);
1467: }
1468: my @esc_order = split(/\&/,$orderitems);
1469: foreach my $item (@esc_order) {
1470: push(@ruleorder,&unescape($item));
1471: }
1472: }
1473: }
1474: }
1475: return (\%ruleshash,\@ruleorder);
1476: }
1477:
1.976 raeburn 1478: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1479:
1480: sub get_domain_defaults {
1481: my ($domain) = @_;
1482: my $cachetime = 60*60*24;
1483: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1484: if (defined($cached)) {
1485: if (ref($result) eq 'HASH') {
1486: return %{$result};
1487: }
1488: }
1489: my %domdefaults;
1490: my %domconfig =
1.989 raeburn 1491: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1492: 'requestcourses','inststatus',
1.1056.4.3! raeburn 1493: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1494: if (ref($domconfig{'defaults'}) eq 'HASH') {
1495: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1496: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1497: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1498: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1499: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1500: } else {
1501: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1502: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1503: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1504: }
1.976 raeburn 1505: if (ref($domconfig{'quotas'}) eq 'HASH') {
1506: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1507: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1508: } else {
1509: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1510: }
1511: my @usertools = ('aboutme','blog','portfolio');
1512: foreach my $item (@usertools) {
1513: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1514: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1515: }
1516: }
1517: }
1.985 raeburn 1518: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1519: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1520: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1521: }
1522: }
1.989 raeburn 1523: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1524: foreach my $item ('inststatustypes','inststatusorder') {
1525: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1526: }
1527: }
1.1047 raeburn 1528: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1529: foreach my $item ('canuse_pdfforms') {
1530: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1531: }
1532: }
1.1056.4.3! raeburn 1533: if (ref($domconfig{'usersessions'}) eq 'HASH') {
! 1534: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
! 1535: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
! 1536: }
! 1537: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
! 1538: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
! 1539: }
! 1540: }
1.943 raeburn 1541: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1542: $cachetime);
1543: return %domdefaults;
1544: }
1545:
1.344 www 1546: # --------------------------------------------------- Assign a key to a student
1547:
1548: sub assign_access_key {
1.364 www 1549: #
1550: # a valid key looks like uname:udom#comments
1551: # comments are being appended
1552: #
1.498 www 1553: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1554: $kdom=
1.620 albertel 1555: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1556: $knum=
1.620 albertel 1557: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1558: $cdom=
1.620 albertel 1559: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1560: $cnum=
1.620 albertel 1561: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1562: $udom=$env{'user.name'} unless (defined($udom));
1563: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1564: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1565: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1566: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1567: # assigned to this person
1568: # - this should not happen,
1.345 www 1569: # unless something went wrong
1570: # the first time around
1571: # ready to assign
1.364 www 1572: $logentry=$1.'; '.$logentry;
1.496 www 1573: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1574: $kdom,$knum) eq 'ok') {
1.345 www 1575: # key now belongs to user
1.346 www 1576: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1577: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1578: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1579: return 'ok';
1580: } else {
1581: return
1582: 'error: Count not permanently assign key, will need to be re-entered later.';
1583: }
1584: } else {
1585: return 'error: Could not assign key, try again later.';
1586: }
1.364 www 1587: } elsif (!$existing{$ckey}) {
1.345 www 1588: # the key does not exist
1589: return 'error: The key does not exist';
1590: } else {
1591: # the key is somebody else's
1592: return 'error: The key is already in use';
1593: }
1.344 www 1594: }
1595:
1.364 www 1596: # ------------------------------------------ put an additional comment on a key
1597:
1598: sub comment_access_key {
1599: #
1600: # a valid key looks like uname:udom#comments
1601: # comments are being appended
1602: #
1603: my ($ckey,$cdom,$cnum,$logentry)=@_;
1604: $cdom=
1.620 albertel 1605: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1606: $cnum=
1.620 albertel 1607: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1608: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1609: if ($existing{$ckey}) {
1610: $existing{$ckey}.='; '.$logentry;
1611: # ready to assign
1.367 www 1612: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1613: $cdom,$cnum) eq 'ok') {
1614: return 'ok';
1615: } else {
1616: return 'error: Count not store comment.';
1617: }
1618: } else {
1619: # the key does not exist
1620: return 'error: The key does not exist';
1621: }
1622: }
1623:
1.344 www 1624: # ------------------------------------------------------ Generate a set of keys
1625:
1626: sub generate_access_keys {
1.364 www 1627: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1628: $cdom=
1.620 albertel 1629: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1630: $cnum=
1.620 albertel 1631: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1632: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1633: unless (($cdom) && ($cnum)) { return 0; }
1634: if ($number>10000) { return 0; }
1635: sleep(2); # make sure don't get same seed twice
1636: srand(time()^($$+($$<<15))); # from "Programming Perl"
1637: my $total=0;
1638: for (my $i=1;$i<=$number;$i++) {
1639: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1640: sprintf("%lx",int(100000*rand)).'-'.
1641: sprintf("%lx",int(100000*rand));
1642: $newkey=~s/1/g/g; # folks mix up 1 and l
1643: $newkey=~s/0/h/g; # and also 0 and O
1644: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1645: if ($existing{$newkey}) {
1646: $i--;
1647: } else {
1.364 www 1648: if (&put('accesskeys',
1649: { $newkey => '# generated '.localtime().
1.620 albertel 1650: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1651: '; '.$logentry },
1652: $cdom,$cnum) eq 'ok') {
1.344 www 1653: $total++;
1654: }
1655: }
1656: }
1.620 albertel 1657: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1658: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1659: return $total;
1660: }
1661:
1662: # ------------------------------------------------------- Validate an accesskey
1663:
1664: sub validate_access_key {
1665: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1666: $cdom=
1.620 albertel 1667: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1668: $cnum=
1.620 albertel 1669: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1670: $udom=$env{'user.domain'} unless (defined($udom));
1671: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1672: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1673: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1674: }
1675:
1676: # ------------------------------------- Find the section of student in a course
1.652 albertel 1677: sub devalidate_getsection_cache {
1678: my ($udom,$unam,$courseid)=@_;
1679: my $hashid="$udom:$unam:$courseid";
1680: &devalidate_cache_new('getsection',$hashid);
1681: }
1.298 matthew 1682:
1.815 albertel 1683: sub courseid_to_courseurl {
1684: my ($courseid) = @_;
1685: #already url style courseid
1686: return $courseid if ($courseid =~ m{^/});
1687:
1688: if (exists($env{'course.'.$courseid.'.num'})) {
1689: my $cnum = $env{'course.'.$courseid.'.num'};
1690: my $cdom = $env{'course.'.$courseid.'.domain'};
1691: return "/$cdom/$cnum";
1692: }
1693:
1694: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1695: if (exists($courseinfo{'num'})) {
1696: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1697: }
1698:
1699: return undef;
1700: }
1701:
1.298 matthew 1702: sub getsection {
1703: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1704: my $cachetime=1800;
1.551 albertel 1705:
1706: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1707: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1708: if (defined($cached)) { return $result; }
1709:
1.298 matthew 1710: my %Pending;
1711: my %Expired;
1712: #
1713: # Each role can either have not started yet (pending), be active,
1714: # or have expired.
1715: #
1716: # If there is an active role, we are done.
1717: #
1718: # If there is more than one role which has not started yet,
1719: # choose the one which will start sooner
1720: # If there is one role which has not started yet, return it.
1721: #
1722: # If there is more than one expired role, choose the one which ended last.
1723: # If there is a role which has expired, return it.
1724: #
1.815 albertel 1725: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1726: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1727: foreach my $key (keys(%roleshash)) {
1.479 albertel 1728: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1729: my $section=$1;
1730: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1731: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1732: my $now=time;
1.548 albertel 1733: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1734: $Expired{$end}=$section;
1735: next;
1736: }
1.548 albertel 1737: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1738: $Pending{$start}=$section;
1739: next;
1740: }
1.599 albertel 1741: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1742: }
1743: #
1744: # Presumedly there will be few matching roles from the above
1745: # loop and the sorting time will be negligible.
1746: if (scalar(keys(%Pending))) {
1747: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1748: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1749: }
1750: if (scalar(keys(%Expired))) {
1751: my @sorted = sort {$a <=> $b} keys(%Expired);
1752: my $time = pop(@sorted);
1.599 albertel 1753: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1754: }
1.599 albertel 1755: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1756: }
1.70 www 1757:
1.599 albertel 1758: sub save_cache {
1759: &purge_remembered();
1.722 albertel 1760: #&Apache::loncommon::validate_page();
1.620 albertel 1761: undef(%env);
1.780 albertel 1762: undef($env_loaded);
1.599 albertel 1763: }
1.452 albertel 1764:
1.599 albertel 1765: my $to_remember=-1;
1766: my %remembered;
1767: my %accessed;
1768: my $kicks=0;
1769: my $hits=0;
1.849 albertel 1770: sub make_key {
1771: my ($name,$id) = @_;
1.872 albertel 1772: if (length($id) > 65
1773: && length(&escape($id)) > 200) {
1774: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1775: }
1.849 albertel 1776: return &escape($name.':'.$id);
1777: }
1778:
1.599 albertel 1779: sub devalidate_cache_new {
1780: my ($name,$id,$debug) = @_;
1781: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1782: $id=&make_key($name,$id);
1.599 albertel 1783: $memcache->delete($id);
1784: delete($remembered{$id});
1785: delete($accessed{$id});
1786: }
1787:
1788: sub is_cached_new {
1789: my ($name,$id,$debug) = @_;
1.849 albertel 1790: $id=&make_key($name,$id);
1.599 albertel 1791: if (exists($remembered{$id})) {
1792: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1793: $accessed{$id}=[&gettimeofday()];
1794: $hits++;
1795: return ($remembered{$id},1);
1796: }
1797: my $value = $memcache->get($id);
1798: if (!(defined($value))) {
1799: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1800: return (undef,undef);
1.416 albertel 1801: }
1.599 albertel 1802: if ($value eq '__undef__') {
1803: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1804: $value=undef;
1805: }
1806: &make_room($id,$value,$debug);
1807: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1808: return ($value,1);
1809: }
1810:
1811: sub do_cache_new {
1812: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1813: $id=&make_key($name,$id);
1.599 albertel 1814: my $setvalue=$value;
1815: if (!defined($setvalue)) {
1816: $setvalue='__undef__';
1817: }
1.623 albertel 1818: if (!defined($time) ) {
1819: $time=600;
1820: }
1.599 albertel 1821: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1822: my $result = $memcache->set($id,$setvalue,$time);
1823: if (! $result) {
1.872 albertel 1824: &logthis("caching of id -> $id failed");
1.910 albertel 1825: $memcache->disconnect_all();
1.872 albertel 1826: }
1.600 albertel 1827: # need to make a copy of $value
1.919 albertel 1828: &make_room($id,$value,$debug);
1.599 albertel 1829: return $value;
1830: }
1831:
1832: sub make_room {
1833: my ($id,$value,$debug)=@_;
1.919 albertel 1834:
1835: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1836: : $value;
1.599 albertel 1837: if ($to_remember<0) { return; }
1838: $accessed{$id}=[&gettimeofday()];
1839: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1840: my $to_kick;
1841: my $max_time=0;
1842: foreach my $other (keys(%accessed)) {
1843: if (&tv_interval($accessed{$other}) > $max_time) {
1844: $to_kick=$other;
1845: $max_time=&tv_interval($accessed{$other});
1846: }
1847: }
1848: delete($remembered{$to_kick});
1849: delete($accessed{$to_kick});
1850: $kicks++;
1851: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1852: return;
1853: }
1854:
1.599 albertel 1855: sub purge_remembered {
1.604 albertel 1856: #&logthis("Tossing ".scalar(keys(%remembered)));
1857: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1858: undef(%remembered);
1859: undef(%accessed);
1.428 albertel 1860: }
1.70 www 1861: # ------------------------------------- Read an entry from a user's environment
1862:
1863: sub userenvironment {
1864: my ($udom,$unam,@what)=@_;
1.976 raeburn 1865: my $items;
1866: foreach my $item (@what) {
1867: $items.=&escape($item).'&';
1868: }
1869: $items=~s/\&$//;
1.70 www 1870: my %returnhash=();
1.1009 raeburn 1871: my $uhome = &homeserver($unam,$udom);
1872: unless ($uhome eq 'no_host') {
1873: my @answer=split(/\&/,
1874: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1875: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1876: return %returnhash;
1877: }
1.1009 raeburn 1878: my $i;
1879: for ($i=0;$i<=$#what;$i++) {
1880: $returnhash{$what[$i]}=&unescape($answer[$i]);
1881: }
1.70 www 1882: }
1883: return %returnhash;
1.1 albertel 1884: }
1885:
1.617 albertel 1886: # ---------------------------------------------------------- Get a studentphoto
1887: sub studentphoto {
1888: my ($udom,$unam,$ext) = @_;
1889: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1890: if (defined($env{'request.course.id'})) {
1.708 raeburn 1891: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1892: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1893: return(&retrievestudentphoto($udom,$unam,$ext));
1894: } else {
1895: my ($result,$perm_reqd)=
1.707 albertel 1896: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1897: if ($result eq 'ok') {
1898: if (!($perm_reqd eq 'yes')) {
1899: return(&retrievestudentphoto($udom,$unam,$ext));
1900: }
1901: }
1902: }
1903: }
1904: } else {
1905: my ($result,$perm_reqd) =
1.707 albertel 1906: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1907: if ($result eq 'ok') {
1908: if (!($perm_reqd eq 'yes')) {
1909: return(&retrievestudentphoto($udom,$unam,$ext));
1910: }
1911: }
1912: }
1913: return '/adm/lonKaputt/lonlogo_broken.gif';
1914: }
1915:
1916: sub retrievestudentphoto {
1917: my ($udom,$unam,$ext,$type) = @_;
1918: my $home=&Apache::lonnet::homeserver($unam,$udom);
1919: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1920: if ($ret eq 'ok') {
1921: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1922: if ($type eq 'thumbnail') {
1923: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1924: }
1925: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1926: return $tokenurl;
1927: } else {
1928: if ($type eq 'thumbnail') {
1929: return '/adm/lonKaputt/genericstudent_tn.gif';
1930: } else {
1931: return '/adm/lonKaputt/lonlogo_broken.gif';
1932: }
1.617 albertel 1933: }
1934: }
1935:
1.263 www 1936: # -------------------------------------------------------------------- New chat
1937:
1938: sub chatsend {
1.724 raeburn 1939: my ($newentry,$anon,$group)=@_;
1.620 albertel 1940: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1941: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1942: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1943: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1944: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1945: &escape($newentry)).':'.$group,$chome);
1.292 www 1946: }
1947:
1948: # ------------------------------------------ Find current version of a resource
1949:
1950: sub getversion {
1951: my $fname=&clutter(shift);
1952: unless ($fname=~/^\/res\//) { return -1; }
1953: return ¤tversion(&filelocation('',$fname));
1954: }
1955:
1956: sub currentversion {
1957: my $fname=shift;
1.599 albertel 1958: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1959: if (defined($cached)) { return $result; }
1.292 www 1960: my $author=$fname;
1961: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1962: my ($udom,$uname)=split(/\//,$author);
1963: my $home=homeserver($uname,$udom);
1964: if ($home eq 'no_host') {
1965: return -1;
1966: }
1967: my $answer=reply("currentversion:$fname",$home);
1968: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1969: return -1;
1970: }
1.599 albertel 1971: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1972: }
1973:
1.1 albertel 1974: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1975:
1.1 albertel 1976: sub subscribe {
1977: my $fname=shift;
1.761 raeburn 1978: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1979: $fname=~s/[\n\r]//g;
1.1 albertel 1980: my $author=$fname;
1981: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1982: my ($udom,$uname)=split(/\//,$author);
1983: my $home=homeserver($uname,$udom);
1.335 albertel 1984: if ($home eq 'no_host') {
1985: return 'not_found';
1.1 albertel 1986: }
1987: my $answer=reply("sub:$fname",$home);
1.64 www 1988: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1989: $answer.=' by '.$home;
1990: }
1.1 albertel 1991: return $answer;
1992: }
1993:
1.8 www 1994: # -------------------------------------------------------------- Replicate file
1995:
1996: sub repcopy {
1997: my $filename=shift;
1.23 www 1998: $filename=~s/\/+/\//g;
1.607 raeburn 1999: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2000: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2001: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2002: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2003: return &repcopy_userfile($filename);
2004: }
1.532 albertel 2005: $filename=~s/[\n\r]//g;
1.8 www 2006: my $transname="$filename.in.transfer";
1.828 www 2007: # FIXME: this should flock
1.607 raeburn 2008: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2009: my $remoteurl=subscribe($filename);
1.64 www 2010: if ($remoteurl =~ /^con_lost by/) {
2011: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2012: return 'unavailable';
1.8 www 2013: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2014: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2015: return 'not_found';
1.64 www 2016: } elsif ($remoteurl =~ /^rejected by/) {
2017: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2018: return 'forbidden';
1.20 www 2019: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2020: return 'ok';
1.8 www 2021: } else {
1.290 www 2022: my $author=$filename;
2023: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2024: my ($udom,$uname)=split(/\//,$author);
2025: my $home=homeserver($uname,$udom);
2026: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2027: my @parts=split(/\//,$filename);
2028: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2029: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2030: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2031: return 'bad_request';
1.8 www 2032: }
2033: my $count;
2034: for ($count=5;$count<$#parts;$count++) {
2035: $path.="/$parts[$count]";
2036: if ((-e $path)!=1) {
2037: mkdir($path,0777);
2038: }
2039: }
2040: my $ua=new LWP::UserAgent;
2041: my $request=new HTTP::Request('GET',"$remoteurl");
2042: my $response=$ua->request($request,$transname);
2043: if ($response->is_error()) {
2044: unlink($transname);
2045: my $message=$response->status_line;
1.672 albertel 2046: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2047: ." LWP get: $message: $filename</font>");
1.607 raeburn 2048: return 'unavailable';
1.8 www 2049: } else {
1.16 www 2050: if ($remoteurl!~/\.meta$/) {
2051: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2052: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2053: if ($mresponse->is_error()) {
2054: unlink($filename.'.meta');
2055: &logthis(
1.672 albertel 2056: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2057: }
2058: }
1.8 www 2059: rename($transname,$filename);
1.607 raeburn 2060: return 'ok';
1.8 www 2061: }
1.290 www 2062: }
1.8 www 2063: }
1.330 www 2064: }
2065:
2066: # ------------------------------------------------ Get server side include body
2067: sub ssi_body {
1.381 albertel 2068: my ($filelink,%form)=@_;
1.606 matthew 2069: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2070: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2071: }
1.953 www 2072: my $output='';
2073: my $response;
1.980 raeburn 2074: if ($filelink=~/^https?\:/) {
1.954 raeburn 2075: ($output,$response)=&externalssi($filelink);
1.953 www 2076: } else {
1.1004 droeschl 2077: $filelink .= $filelink=~/\?/ ? '&' : '?';
2078: $filelink .= 'inhibitmenu=yes';
1.953 www 2079: ($output,$response)=&ssi($filelink,%form);
2080: }
1.778 albertel 2081: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2082: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2083: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2084: if (wantarray) {
2085: return ($output, $response);
2086: } else {
2087: return $output;
2088: }
1.8 www 2089: }
2090:
1.15 www 2091: # --------------------------------------------------------- Server Side Include
2092:
1.782 albertel 2093: sub absolute_url {
2094: my ($host_name) = @_;
2095: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2096: if ($host_name eq '') {
2097: $host_name = $ENV{'SERVER_NAME'};
2098: }
2099: return $protocol.$host_name;
2100: }
2101:
1.942 foxr 2102: #
2103: # Server side include.
2104: # Parameters:
2105: # fn Possibly encrypted resource name/id.
2106: # form Hash that describes how the rendering should be done
2107: # and other things.
1.944 foxr 2108: # Returns:
1.950 raeburn 2109: # Scalar context: The content of the response.
2110: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2111: #
1.15 www 2112: sub ssi {
2113:
1.944 foxr 2114: my ($fn,%form)=@_;
1.15 www 2115: my $ua=new LWP::UserAgent;
1.23 www 2116: my $request;
1.711 albertel 2117:
2118: $form{'no_update_last_known'}=1;
1.895 albertel 2119: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2120: if (%form) {
1.782 albertel 2121: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2122: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2123: } else {
1.782 albertel 2124: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2125: }
2126:
1.15 www 2127: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2128: my $response=$ua->request($request);
2129:
1.944 foxr 2130: if (wantarray) {
2131: return ($response->content, $response);
2132: } else {
2133: return $response->content;
1.942 foxr 2134: }
1.324 www 2135: }
2136:
2137: sub externalssi {
2138: my ($url)=@_;
2139: my $ua=new LWP::UserAgent;
2140: my $request=new HTTP::Request('GET',$url);
2141: my $response=$ua->request($request);
1.954 raeburn 2142: if (wantarray) {
2143: return ($response->content, $response);
2144: } else {
2145: return $response->content;
2146: }
1.15 www 2147: }
1.254 www 2148:
1.492 albertel 2149: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2150:
2151: sub allowuploaded {
2152: my ($srcurl,$url)=@_;
2153: $url=&clutter(&declutter($url));
2154: my $dir=$url;
2155: $dir=~s/\/[^\/]+$//;
2156: my %httpref=();
2157: my $httpurl=&hreflocation('',$url);
2158: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2159: &Apache::lonnet::appenv(\%httpref);
1.254 www 2160: }
1.477 raeburn 2161:
1.478 albertel 2162: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2163: # input: action, courseID, current domain, intended
1.637 raeburn 2164: # path to file, source of file, instruction to parse file for objects,
2165: # ref to hash for embedded objects,
2166: # ref to hash for codebase of java objects.
2167: #
1.485 raeburn 2168: # output: url to file (if action was uploaddoc),
2169: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2170: #
1.478 albertel 2171: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2172: # course.
1.477 raeburn 2173: #
1.478 albertel 2174: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2175: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2176: # course's home server.
1.477 raeburn 2177: #
1.478 albertel 2178: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2179: # be copied from $source (current location) to
2180: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2181: # and will then be copied to
2182: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2183: # course's home server.
1.485 raeburn 2184: #
1.481 raeburn 2185: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2186: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2187: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2188: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2189: # in course's home server.
1.637 raeburn 2190: #
1.477 raeburn 2191:
2192: sub process_coursefile {
1.638 albertel 2193: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 2194: my $fetchresult;
1.638 albertel 2195: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2196: if ($action eq 'propagate') {
1.638 albertel 2197: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2198: $home);
1.481 raeburn 2199: } else {
1.477 raeburn 2200: my $fpath = '';
2201: my $fname = $file;
1.478 albertel 2202: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2203: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2204: my $filepath = &build_filepath($fpath);
1.481 raeburn 2205: if ($action eq 'copy') {
2206: if ($source eq '') {
2207: $fetchresult = 'no source file';
2208: return $fetchresult;
2209: } else {
2210: my $destination = $filepath.'/'.$fname;
2211: rename($source,$destination);
2212: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2213: $home);
1.481 raeburn 2214: }
2215: } elsif ($action eq 'uploaddoc') {
2216: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2217: print $fh $env{'form.'.$source};
1.481 raeburn 2218: close($fh);
1.637 raeburn 2219: if ($parser eq 'parse') {
1.1024 raeburn 2220: my $mm = new File::MMagic;
2221: my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
2222: if ($mime_type eq 'text/html') {
2223: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2224: unless ($parse_result eq 'ok') {
2225: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2226: }
1.637 raeburn 2227: }
2228: }
1.477 raeburn 2229: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2230: $home);
1.481 raeburn 2231: if ($fetchresult eq 'ok') {
2232: return '/uploaded/'.$fpath.'/'.$fname;
2233: } else {
2234: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2235: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2236: return '/adm/notfound.html';
2237: }
1.477 raeburn 2238: }
2239: }
1.485 raeburn 2240: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2241: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2242: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2243: }
2244: return $fetchresult;
2245: }
2246:
1.637 raeburn 2247: sub build_filepath {
2248: my ($fpath) = @_;
2249: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2250: unless ($fpath eq '') {
2251: my @parts=split('/',$fpath);
2252: foreach my $part (@parts) {
2253: $filepath.= '/'.$part;
2254: if ((-e $filepath)!=1) {
2255: mkdir($filepath,0777);
2256: }
2257: }
2258: }
2259: return $filepath;
2260: }
2261:
2262: sub store_edited_file {
1.638 albertel 2263: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2264: my $file = $primary_url;
2265: $file =~ s#^/uploaded/$docudom/$docuname/##;
2266: my $fpath = '';
2267: my $fname = $file;
2268: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2269: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2270: my $filepath = &build_filepath($fpath);
2271: open(my $fh,'>'.$filepath.'/'.$fname);
2272: print $fh $content;
2273: close($fh);
1.638 albertel 2274: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2275: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2276: $home);
1.637 raeburn 2277: if ($$fetchresult eq 'ok') {
2278: return '/uploaded/'.$fpath.'/'.$fname;
2279: } else {
1.638 albertel 2280: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2281: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2282: return '/adm/notfound.html';
2283: }
2284: }
2285:
1.531 albertel 2286: sub clean_filename {
1.831 albertel 2287: my ($fname,$args)=@_;
1.315 www 2288: # Replace Windows backslashes by forward slashes
1.257 www 2289: $fname=~s/\\/\//g;
1.831 albertel 2290: if (!$args->{'keep_path'}) {
2291: # Get rid of everything but the actual filename
2292: $fname=~s/^.*\/([^\/]+)$/$1/;
2293: }
1.315 www 2294: # Replace spaces by underscores
2295: $fname=~s/\s+/\_/g;
2296: # Replace all other weird characters by nothing
1.831 albertel 2297: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2298: # Replace all .\d. sequences with _\d. so they no longer look like version
2299: # numbers
2300: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2301: return $fname;
2302: }
1.1051 raeburn 2303: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2304: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2305: # image with the same aspect ratio as the original, but with dimensions which do
2306: # not exceed $resizewidth and $resizeheight.
2307:
1.984 neumanie 2308: sub resizeImage {
1.1051 raeburn 2309: my ($img_path,$resizewidth,$resizeheight) = @_;
2310: my $ima = Image::Magick->new;
2311: my $resized;
2312: if (-e $img_path) {
2313: $ima->Read($img_path);
2314: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2315: my $width = $ima->Get('width');
2316: my $height = $ima->Get('height');
2317: if ($width > $resizewidth) {
2318: my $factor = $width/$resizewidth;
2319: my $newheight = $height/$factor;
2320: $ima->Scale(width=>$resizewidth,height=>$newheight);
2321: $resized = 1;
2322: }
2323: }
2324: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2325: my $width = $ima->Get('width');
2326: my $height = $ima->Get('height');
2327: if ($height > $resizeheight) {
2328: my $factor = $height/$resizeheight;
2329: my $newwidth = $width/$factor;
2330: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2331: $resized = 1;
2332: }
2333: }
2334: if ($resized) {
2335: $ima->Write($img_path);
2336: }
2337: }
2338: return;
1.977 amueller 2339: }
2340:
1.608 albertel 2341: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2342: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2343: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2344: # $coursedoc - if true up to the current course
2345: # if false
2346: # $subdir - directory in userfile to store the file into
1.858 raeburn 2347: # $parser - instruction to parse file for objects ($parser = parse)
2348: # $allfiles - reference to hash for embedded objects
2349: # $codebase - reference to hash for codebase of java objects
2350: # $desuname - username for permanent storage of uploaded file
2351: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2352: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2353: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2354: # $resizewidth - width (pixels) to which to resize uploaded image
2355: # $resizeheight - height (pixels) to which to resize uploaded image
1.858 raeburn 2356: #
1.686 albertel 2357: # output: url of file in userspace, or error: <message>
2358: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2359:
1.531 albertel 2360: sub userfileupload {
1.860 raeburn 2361: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051 raeburn 2362: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531 albertel 2363: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2364: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2365: $fname=&clean_filename($fname);
1.315 www 2366: # See if there is anything left
1.257 www 2367: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2368: chop($env{'form.'.$formname});
1.523 raeburn 2369: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2370: my $now = time;
2371: my $filepath = 'tmp/helprequests/'.$now;
2372: my @parts=split(/\//,$filepath);
2373: my $fullpath = $perlvar{'lonDaemons'};
2374: for (my $i=0;$i<@parts;$i++) {
2375: $fullpath .= '/'.$parts[$i];
2376: if ((-e $fullpath)!=1) {
2377: mkdir($fullpath,0777);
2378: }
2379: }
2380: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2381: print $fh $env{'form.'.$formname};
1.523 raeburn 2382: close($fh);
1.741 raeburn 2383: return $fullpath.'/'.$fname;
2384: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2385: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2386: '_'.$env{'user.domain'}.'/pending';
2387: my @parts=split(/\//,$filepath);
2388: my $fullpath = $perlvar{'lonDaemons'};
2389: for (my $i=0;$i<@parts;$i++) {
2390: $fullpath .= '/'.$parts[$i];
2391: if ((-e $fullpath)!=1) {
2392: mkdir($fullpath,0777);
2393: }
2394: }
2395: open(my $fh,'>'.$fullpath.'/'.$fname);
2396: print $fh $env{'form.'.$formname};
2397: close($fh);
2398: return $fullpath.'/'.$fname;
1.523 raeburn 2399: }
1.995 raeburn 2400: if ($subdir eq 'scantron') {
2401: $fname = 'scantron_orig_'.$fname;
2402: } else {
1.258 www 2403: # Create the directory if not present
1.995 raeburn 2404: $fname="$subdir/$fname";
2405: }
1.259 www 2406: if ($coursedoc) {
1.638 albertel 2407: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2408: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2409: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2410: return &finishuserfileupload($docuname,$docudom,
2411: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2412: $codebase,$thumbwidth,$thumbheight,
2413: $resizewidth,$resizeheight);
1.481 raeburn 2414: } else {
1.620 albertel 2415: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2416: return &process_coursefile('uploaddoc',$docuname,$docudom,
2417: $fname,$formname,$parser,
2418: $allfiles,$codebase);
1.481 raeburn 2419: }
1.719 banghart 2420: } elsif (defined($destuname)) {
2421: my $docuname=$destuname;
2422: my $docudom=$destudom;
1.860 raeburn 2423: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2424: $parser,$allfiles,$codebase,
1.1051 raeburn 2425: $thumbwidth,$thumbheight,
2426: $resizewidth,$resizeheight);
1.719 banghart 2427:
1.259 www 2428: } else {
1.638 albertel 2429: my $docuname=$env{'user.name'};
2430: my $docudom=$env{'user.domain'};
1.714 raeburn 2431: if (exists($env{'form.group'})) {
2432: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2433: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2434: }
1.860 raeburn 2435: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2436: $parser,$allfiles,$codebase,
1.1051 raeburn 2437: $thumbwidth,$thumbheight,
2438: $resizewidth,$resizeheight);
1.259 www 2439: }
1.271 www 2440: }
2441:
2442: sub finishuserfileupload {
1.860 raeburn 2443: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051 raeburn 2444: $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477 raeburn 2445: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2446: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2447:
1.860 raeburn 2448: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2449: $file=$fname;
2450: if ($fname=~m|/|) {
2451: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2452: $path.=$fnamepath.'/';
2453: }
1.259 www 2454: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2455: my $count;
2456: for ($count=4;$count<=$#parts;$count++) {
2457: $filepath.="/$parts[$count]";
2458: if ((-e $filepath)!=1) {
2459: mkdir($filepath,0777);
2460: }
2461: }
1.984 neumanie 2462:
1.258 www 2463: # Save the file
2464: {
1.701 albertel 2465: if (!open(FH,'>'.$filepath.'/'.$file)) {
2466: &logthis('Failed to create '.$filepath.'/'.$file);
2467: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2468: return '/adm/notfound.html';
2469: }
2470: if (!print FH ($env{'form.'.$formname})) {
2471: &logthis('Failed to write to '.$filepath.'/'.$file);
2472: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2473: return '/adm/notfound.html';
2474: }
1.570 albertel 2475: close(FH);
1.1051 raeburn 2476: if ($resizewidth && $resizeheight) {
2477: my $mm = new File::MMagic;
2478: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2479: if ($mime_type =~ m{^image/}) {
2480: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2481: }
1.977 amueller 2482: }
1.258 www 2483: }
1.637 raeburn 2484: if ($parser eq 'parse') {
1.1024 raeburn 2485: my $mm = new File::MMagic;
2486: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2487: if ($mime_type eq 'text/html') {
2488: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2489: $allfiles,$codebase);
2490: unless ($parse_result eq 'ok') {
2491: &logthis('Failed to parse '.$filepath.$file.
2492: ' for embedded media: '.$parse_result);
2493: }
1.637 raeburn 2494: }
2495: }
1.860 raeburn 2496: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2497: my $input = $filepath.'/'.$file;
2498: my $output = $filepath.'/'.'tn-'.$file;
2499: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2500: system("convert -sample $thumbsize $input $output");
2501: if (-e $filepath.'/'.'tn-'.$file) {
2502: $fetchthumb = 1;
2503: }
2504: }
1.858 raeburn 2505:
1.259 www 2506: # Notify homeserver to grep it
2507: #
1.984 neumanie 2508: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2509: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2510: if ($fetchresult eq 'ok') {
1.860 raeburn 2511: if ($fetchthumb) {
2512: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2513: if ($thumbresult ne 'ok') {
2514: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2515: $docuhome.': '.$thumbresult);
2516: }
2517: }
1.259 www 2518: #
1.258 www 2519: # Return the URL to it
1.494 albertel 2520: return '/uploaded/'.$path.$file;
1.263 www 2521: } else {
1.494 albertel 2522: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2523: ': '.$fetchresult);
1.263 www 2524: return '/adm/notfound.html';
1.858 raeburn 2525: }
1.493 albertel 2526: }
2527:
1.637 raeburn 2528: sub extract_embedded_items {
1.961 raeburn 2529: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2530: my @state = ();
2531: my %javafiles = (
2532: codebase => '',
2533: code => '',
2534: archive => ''
2535: );
2536: my %mediafiles = (
2537: src => '',
2538: movie => '',
2539: );
1.648 raeburn 2540: my $p;
2541: if ($content) {
2542: $p = HTML::LCParser->new($content);
2543: } else {
1.961 raeburn 2544: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2545: }
1.641 albertel 2546: while (my $t=$p->get_token()) {
1.640 albertel 2547: if ($t->[0] eq 'S') {
2548: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2549: push(@state, $tagname);
1.648 raeburn 2550: if (lc($tagname) eq 'allow') {
2551: &add_filetype($allfiles,$attr->{'src'},'src');
2552: }
1.640 albertel 2553: if (lc($tagname) eq 'img') {
2554: &add_filetype($allfiles,$attr->{'src'},'src');
2555: }
1.886 albertel 2556: if (lc($tagname) eq 'a') {
2557: &add_filetype($allfiles,$attr->{'href'},'href');
2558: }
1.645 raeburn 2559: if (lc($tagname) eq 'script') {
2560: if ($attr->{'archive'} =~ /\.jar$/i) {
2561: &add_filetype($allfiles,$attr->{'archive'},'archive');
2562: } else {
2563: &add_filetype($allfiles,$attr->{'src'},'src');
2564: }
2565: }
2566: if (lc($tagname) eq 'link') {
2567: if (lc($attr->{'rel'}) eq 'stylesheet') {
2568: &add_filetype($allfiles,$attr->{'href'},'href');
2569: }
2570: }
1.640 albertel 2571: if (lc($tagname) eq 'object' ||
2572: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2573: foreach my $item (keys(%javafiles)) {
2574: $javafiles{$item} = '';
2575: }
2576: }
2577: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2578: my $name = lc($attr->{'name'});
2579: foreach my $item (keys(%javafiles)) {
2580: if ($name eq $item) {
2581: $javafiles{$item} = $attr->{'value'};
2582: last;
2583: }
2584: }
2585: foreach my $item (keys(%mediafiles)) {
2586: if ($name eq $item) {
2587: &add_filetype($allfiles, $attr->{'value'}, 'value');
2588: last;
2589: }
2590: }
2591: }
2592: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2593: foreach my $item (keys(%javafiles)) {
2594: if ($attr->{$item}) {
2595: $javafiles{$item} = $attr->{$item};
2596: last;
2597: }
2598: }
2599: foreach my $item (keys(%mediafiles)) {
2600: if ($attr->{$item}) {
2601: &add_filetype($allfiles,$attr->{$item},$item);
2602: last;
2603: }
2604: }
2605: }
2606: } elsif ($t->[0] eq 'E') {
2607: my ($tagname) = ($t->[1]);
2608: if ($javafiles{'codebase'} ne '') {
2609: $javafiles{'codebase'} .= '/';
2610: }
2611: if (lc($tagname) eq 'applet' ||
2612: lc($tagname) eq 'object' ||
2613: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2614: ) {
2615: foreach my $item (keys(%javafiles)) {
2616: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2617: my $file=$javafiles{'codebase'}.$javafiles{$item};
2618: &add_filetype($allfiles,$file,$item);
2619: }
2620: }
2621: }
2622: pop @state;
2623: }
2624: }
1.637 raeburn 2625: return 'ok';
2626: }
2627:
1.639 albertel 2628: sub add_filetype {
2629: my ($allfiles,$file,$type)=@_;
2630: if (exists($allfiles->{$file})) {
2631: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2632: push(@{$allfiles->{$file}}, &escape($type));
2633: }
2634: } else {
2635: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2636: }
2637: }
2638:
1.493 albertel 2639: sub removeuploadedurl {
1.984 neumanie 2640: my ($url)=@_;
2641: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2642: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2643: }
2644:
2645: sub removeuserfile {
2646: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2647: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2648: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2649: if ($result eq 'ok') {
1.798 raeburn 2650: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2651: my $metafile = $fname.'.meta';
2652: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2653: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2654: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2655: my $sqlresult =
1.823 albertel 2656: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2657: 'portfolio_metadata',$group,
2658: 'delete');
1.798 raeburn 2659: }
2660: }
2661: return $result;
1.257 www 2662: }
1.15 www 2663:
1.530 albertel 2664: sub mkdiruserfile {
2665: my ($docuname,$docudom,$dir)=@_;
2666: my $home=&homeserver($docuname,$docudom);
2667: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2668: }
2669:
1.531 albertel 2670: sub renameuserfile {
2671: my ($docuname,$docudom,$old,$new)=@_;
2672: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2673: my $result = &reply("renameuserfile:$docudom:$docuname:".
2674: &escape("$old").':'.&escape("$new"),$home);
2675: if ($result eq 'ok') {
2676: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2677: my $oldmeta = $old.'.meta';
2678: my $newmeta = $new.'.meta';
2679: my $metaresult =
2680: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2681: my $url = "/uploaded/$docudom/$docuname/$old";
2682: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2683: my $sqlresult =
1.823 albertel 2684: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2685: 'portfolio_metadata',$group,
2686: 'delete');
1.798 raeburn 2687: }
2688: }
2689: return $result;
1.531 albertel 2690: }
2691:
1.14 www 2692: # ------------------------------------------------------------------------- Log
2693:
2694: sub log {
2695: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2696: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2697: }
2698:
2699: # ------------------------------------------------------------------ Course Log
1.352 www 2700: #
2701: # This routine flushes several buffers of non-mission-critical nature
2702: #
1.157 www 2703:
2704: sub flushcourselogs {
1.352 www 2705: &logthis('Flushing log buffers');
2706: #
2707: # course logs
2708: # This is a log of all transactions in a course, which can be used
2709: # for data mining purposes
2710: #
2711: # It also collects the courseid database, which lists last transaction
2712: # times and course titles for all courseids
2713: #
2714: my %courseidbuffer=();
1.921 raeburn 2715: foreach my $crsid (keys(%courselogs)) {
1.352 www 2716: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2717: &escape($courselogs{$crsid}),
2718: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2719: delete $courselogs{$crsid};
2720: } else {
2721: &logthis('Failed to flush log buffer for '.$crsid);
2722: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2723: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2724: " exceeded maximum size, deleting.</font>");
2725: delete $courselogs{$crsid};
2726: }
1.352 www 2727: }
1.920 raeburn 2728: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2729: 'description' => $coursedescrbuf{$crsid},
2730: 'inst_code' => $courseinstcodebuf{$crsid},
2731: 'type' => $coursetypebuf{$crsid},
2732: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2733: };
1.191 harris41 2734: }
1.352 www 2735: #
2736: # Write course id database (reverse lookup) to homeserver of courses
2737: # Is used in pickcourse
2738: #
1.840 albertel 2739: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2740: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2741: $courseidbuffer{$crs_home},
2742: $crs_home,'timeonly');
1.352 www 2743: }
2744: #
2745: # File accesses
2746: # Writes to the dynamic metadata of resources to get hit counts, etc.
2747: #
1.449 matthew 2748: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2749: if ($entry =~ /___count$/) {
2750: my ($dom,$name);
1.807 albertel 2751: ($dom,$name,undef)=
1.811 albertel 2752: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2753: if (! defined($dom) || $dom eq '' ||
2754: ! defined($name) || $name eq '') {
1.620 albertel 2755: my $cid = $env{'request.course.id'};
2756: $dom = $env{'request.'.$cid.'.domain'};
2757: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2758: }
1.450 matthew 2759: my $value = $accesshash{$entry};
2760: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2761: my %temphash=($url => $value);
1.449 matthew 2762: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2763: if ($result eq 'ok') {
2764: delete $accesshash{$entry};
2765: } elsif ($result eq 'unknown_cmd') {
2766: # Target server has old code running on it.
1.450 matthew 2767: my %temphash=($entry => $value);
1.449 matthew 2768: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2769: delete $accesshash{$entry};
2770: }
2771: }
2772: } else {
1.811 albertel 2773: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2774: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2775: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2776: delete $accesshash{$entry};
2777: }
1.185 www 2778: }
1.191 harris41 2779: }
1.352 www 2780: #
2781: # Roles
2782: # Reverse lookup of user roles for course faculty/staff and co-authorship
2783: #
1.800 albertel 2784: foreach my $entry (keys(%userrolehash)) {
1.351 www 2785: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2786: split(/\:/,$entry);
2787: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2788: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2789: $rudom,$runame) eq 'ok') {
2790: delete $userrolehash{$entry};
2791: }
2792: }
1.662 raeburn 2793: #
2794: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2795: #
2796: my %domrolebuffer = ();
1.1000 raeburn 2797: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2798: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2799: if ($domrolebuffer{$rudom}) {
2800: $domrolebuffer{$rudom}.='&'.&escape($entry).
2801: '='.&escape($domainrolehash{$entry});
2802: } else {
2803: $domrolebuffer{$rudom}.=&escape($entry).
2804: '='.&escape($domainrolehash{$entry});
2805: }
2806: delete $domainrolehash{$entry};
2807: }
2808: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2809: my %servers = &get_servers($dom,'library');
2810: foreach my $tryserver (keys(%servers)) {
2811: unless (&reply('domroleput:'.$dom.':'.
2812: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2813: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2814: }
1.662 raeburn 2815: }
2816: }
1.186 www 2817: $dumpcount++;
1.157 www 2818: }
2819:
2820: sub courselog {
2821: my $what=shift;
1.158 www 2822: $what=time.':'.$what;
1.620 albertel 2823: unless ($env{'request.course.id'}) { return ''; }
2824: $coursedombuf{$env{'request.course.id'}}=
2825: $env{'course.'.$env{'request.course.id'}.'.domain'};
2826: $coursenumbuf{$env{'request.course.id'}}=
2827: $env{'course.'.$env{'request.course.id'}.'.num'};
2828: $coursehombuf{$env{'request.course.id'}}=
2829: $env{'course.'.$env{'request.course.id'}.'.home'};
2830: $coursedescrbuf{$env{'request.course.id'}}=
2831: $env{'course.'.$env{'request.course.id'}.'.description'};
2832: $courseinstcodebuf{$env{'request.course.id'}}=
2833: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2834: $courseownerbuf{$env{'request.course.id'}}=
2835: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2836: $coursetypebuf{$env{'request.course.id'}}=
2837: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2838: if (defined $courselogs{$env{'request.course.id'}}) {
2839: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2840: } else {
1.620 albertel 2841: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2842: }
1.620 albertel 2843: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2844: &flushcourselogs();
2845: }
1.158 www 2846: }
2847:
2848: sub courseacclog {
2849: my $fnsymb=shift;
1.620 albertel 2850: unless ($env{'request.course.id'}) { return ''; }
2851: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2852: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2853: $what.=':POST';
1.583 matthew 2854: # FIXME: Probably ought to escape things....
1.800 albertel 2855: foreach my $key (keys(%env)) {
2856: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2857: my $formitem = $1;
2858: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2859: $what.=':'.$formitem.'='.$env{$key};
2860: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2861: $what.=':'.$formitem.'='.$env{$key};
2862: }
1.158 www 2863: }
1.191 harris41 2864: }
1.583 matthew 2865: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2866: # FIXME: We should not be depending on a form parameter that someone
2867: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2868: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2869: $what.= ':POST';
2870: # FIXME: Probably ought to escape things....
2871: foreach my $element ('courseexp','crsfulltext','crsrelated',
2872: 'crsdiscuss') {
1.620 albertel 2873: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2874: }
2875: }
1.158 www 2876: }
2877: &courselog($what);
1.149 www 2878: }
2879:
1.185 www 2880: sub countacc {
2881: my $url=&declutter(shift);
1.458 matthew 2882: return if (! defined($url) || $url eq '');
1.620 albertel 2883: unless ($env{'request.course.id'}) { return ''; }
2884: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2885: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2886: $accesshash{$key}++;
1.185 www 2887: }
1.349 www 2888:
1.361 www 2889: sub linklog {
2890: my ($from,$to)=@_;
2891: $from=&declutter($from);
2892: $to=&declutter($to);
2893: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2894: $accesshash{$to.'___'.$from.'___goto'}=1;
2895: }
2896:
1.349 www 2897: sub userrolelog {
2898: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2899: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2900: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2901: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 2902: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 2903: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2904: $userrolehash
2905: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2906: =$tend.':'.$tstart;
1.662 raeburn 2907: }
1.898 albertel 2908: if (($env{'request.role'} =~ /dc\./) &&
2909: (($trole=~/^au/) || ($trole=~/^in/) ||
2910: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 2911: ($trole=~/^cr/) || ($trole=~/^ta/) ||
2912: ($trole=~/^co/))) {
1.898 albertel 2913: $userrolehash
2914: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2915: =$tend.':'.$tstart;
2916: }
1.662 raeburn 2917: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2918: ($trole=~/^li/) || ($trole=~/^li/) ||
2919: ($trole=~/^au/) || ($trole=~/^dg/) ||
2920: ($trole=~/^sc/)) {
2921: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2922: $domainrolehash
2923: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2924: = $tend.':'.$tstart;
2925: }
1.351 www 2926: }
2927:
1.957 raeburn 2928: sub courserolelog {
2929: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2930: if (($trole eq 'cc') || ($trole eq 'in') ||
2931: ($trole eq 'ep') || ($trole eq 'ad') ||
2932: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 2933: ($trole=~/^cr/) || ($trole eq 'gr') ||
2934: ($trole eq 'co')) {
1.957 raeburn 2935: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2936: my $cdom = $1;
2937: my $cnum = $2;
2938: my $sec = $3;
2939: my $namespace = 'rolelog';
2940: my %storehash = (
2941: role => $trole,
2942: start => $tstart,
2943: end => $tend,
2944: selfenroll => $selfenroll,
2945: context => $context,
2946: );
2947: if ($trole eq 'gr') {
2948: $namespace = 'groupslog';
2949: $storehash{'group'} = $sec;
2950: } else {
2951: $storehash{'section'} = $sec;
2952: }
2953: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 2954: if (($trole ne 'st') || ($sec ne '')) {
2955: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2956: }
1.957 raeburn 2957: }
2958: }
2959: return;
2960: }
2961:
1.351 www 2962: sub get_course_adv_roles {
1.948 raeburn 2963: my ($cid,$codes) = @_;
1.620 albertel 2964: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2965: my %coursehash=&coursedescription($cid);
1.988 raeburn 2966: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 2967: my %nothide=();
1.800 albertel 2968: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2969: if ($user !~ /:/) {
2970: $nothide{join(':',split(/[\@]/,$user))}=1;
2971: } else {
2972: $nothide{$user}=1;
2973: }
1.470 www 2974: }
1.351 www 2975: my %returnhash=();
2976: my %dumphash=
2977: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2978: my $now=time;
1.997 raeburn 2979: my %privileged;
1.1000 raeburn 2980: foreach my $entry (keys(%dumphash)) {
1.800 albertel 2981: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2982: if (($tstart) && ($tstart<0)) { next; }
2983: if (($tend) && ($tend<$now)) { next; }
2984: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2985: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2986: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 2987: unless (ref($privileged{$domain}) eq 'HASH') {
2988: my %dompersonnel =
1.998 raeburn 2989: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 2990: $privileged{$domain} = {};
2991: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 2992: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 2993: foreach my $user (keys(%{$dompersonnel{$server}})) {
2994: my ($trole,$uname,$udom) = split(/:/,$user);
2995: $privileged{$udom}{$uname} = 1;
2996: }
2997: }
2998: }
2999: }
3000: if ((exists($privileged{$domain}{$username})) &&
3001: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3002: if ($role eq 'cr') { next; }
1.948 raeburn 3003: if ($codes) {
3004: if ($section) { $role .= ':'.$section; }
3005: if ($returnhash{$role}) {
3006: $returnhash{$role}.=','.$username.':'.$domain;
3007: } else {
3008: $returnhash{$role}=$username.':'.$domain;
3009: }
1.351 www 3010: } else {
1.988 raeburn 3011: my $key=&plaintext($role,$crstype);
1.973 bisitz 3012: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3013: if ($returnhash{$key}) {
3014: $returnhash{$key}.=','.$username.':'.$domain;
3015: } else {
3016: $returnhash{$key}=$username.':'.$domain;
3017: }
1.351 www 3018: }
1.948 raeburn 3019: }
1.400 www 3020: return %returnhash;
3021: }
3022:
3023: sub get_my_roles {
1.937 raeburn 3024: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3025: unless (defined($uname)) { $uname=$env{'user.name'}; }
3026: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3027: my (%dumphash,%nothide);
1.858 raeburn 3028: if ($context eq 'userroles') {
3029: %dumphash = &dump('roles',$udom,$uname);
3030: } else {
3031: %dumphash=
1.400 www 3032: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3033: if ($hidepriv) {
3034: my %coursehash=&coursedescription($udom.'_'.$uname);
3035: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3036: if ($user !~ /:/) {
3037: $nothide{join(':',split(/[\@]/,$user))} = 1;
3038: } else {
3039: $nothide{$user} = 1;
3040: }
3041: }
3042: }
1.858 raeburn 3043: }
1.400 www 3044: my %returnhash=();
3045: my $now=time;
1.999 raeburn 3046: my %privileged;
1.800 albertel 3047: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3048: my ($role,$tend,$tstart);
3049: if ($context eq 'userroles') {
3050: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3051: } else {
3052: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3053: }
1.400 www 3054: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3055: my $status = 'active';
1.939 raeburn 3056: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3057: $status = 'previous';
3058: }
3059: if (($tstart) && ($now<$tstart)) {
3060: $status = 'future';
3061: }
3062: if (ref($types) eq 'ARRAY') {
3063: if (!grep(/^\Q$status\E$/,@{$types})) {
3064: next;
3065: }
3066: } else {
3067: if ($status ne 'active') {
3068: next;
3069: }
3070: }
1.867 raeburn 3071: my ($rolecode,$username,$domain,$section,$area);
3072: if ($context eq 'userroles') {
3073: ($area,$rolecode) = split(/_/,$entry);
3074: (undef,$domain,$username,$section) = split(/\//,$area);
3075: } else {
3076: ($role,$username,$domain,$section) = split(/\:/,$entry);
3077: }
1.832 raeburn 3078: if (ref($roledoms) eq 'ARRAY') {
3079: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3080: next;
3081: }
3082: }
3083: if (ref($roles) eq 'ARRAY') {
3084: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3085: if ($role =~ /^cr\//) {
3086: if (!grep(/^cr$/,@{$roles})) {
3087: next;
3088: }
3089: } else {
3090: next;
3091: }
1.832 raeburn 3092: }
1.867 raeburn 3093: }
1.937 raeburn 3094: if ($hidepriv) {
1.999 raeburn 3095: if ($context eq 'userroles') {
3096: if ((&privileged($username,$domain)) &&
3097: (!$nothide{$username.':'.$domain})) {
3098: next;
3099: }
3100: } else {
3101: unless (ref($privileged{$domain}) eq 'HASH') {
3102: my %dompersonnel =
3103: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3104: $privileged{$domain} = {};
3105: if (keys(%dompersonnel)) {
3106: foreach my $server (keys(%dompersonnel)) {
3107: if (ref($dompersonnel{$server}) eq 'HASH') {
3108: foreach my $user (keys(%{$dompersonnel{$server}})) {
3109: my ($trole,$uname,$udom) = split(/:/,$user);
3110: $privileged{$udom}{$uname} = $trole;
3111: }
3112: }
3113: }
3114: }
3115: }
3116: if (exists($privileged{$domain}{$username})) {
3117: if (!$nothide{$username.':'.$domain}) {
3118: next;
3119: }
3120: }
1.937 raeburn 3121: }
3122: }
1.933 raeburn 3123: if ($withsec) {
3124: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3125: $tstart.':'.$tend;
3126: } else {
3127: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3128: }
1.832 raeburn 3129: }
1.373 www 3130: return %returnhash;
1.399 www 3131: }
3132:
3133: # ----------------------------------------------------- Frontpage Announcements
3134: #
3135: #
3136:
3137: sub postannounce {
3138: my ($server,$text)=@_;
1.844 albertel 3139: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3140: unless ($text=~/\w/) { $text=''; }
3141: return &reply('setannounce:'.&escape($text),$server);
3142: }
3143:
3144: sub getannounce {
1.448 albertel 3145:
3146: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3147: my $announcement='';
1.800 albertel 3148: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3149: close($fh);
1.399 www 3150: if ($announcement=~/\w/) {
3151: return
3152: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3153: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3154: } else {
3155: return '';
3156: }
3157: } else {
3158: return '';
3159: }
1.351 www 3160: }
1.353 www 3161:
3162: # ---------------------------------------------------------- Course ID routines
3163: # Deal with domain's nohist_courseid.db files
3164: #
3165:
3166: sub courseidput {
1.921 raeburn 3167: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3168: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3169: my $outcome;
3170: if ($caller eq 'timeonly') {
3171: my $cids = '';
3172: foreach my $item (keys(%$storehash)) {
3173: $cids.=&escape($item).'&';
3174: }
3175: $cids=~s/\&$//;
3176: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3177: $coursehome);
3178: } else {
3179: my $items = '';
3180: foreach my $item (keys(%$storehash)) {
3181: $items.= &escape($item).'='.
3182: &freeze_escape($$storehash{$item}).'&';
3183: }
3184: $items=~s/\&$//;
3185: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3186: $coursehome);
1.918 raeburn 3187: }
3188: if ($outcome eq 'unknown_cmd') {
3189: my $what;
3190: foreach my $cid (keys(%$storehash)) {
3191: $what .= &escape($cid).'=';
1.921 raeburn 3192: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3193: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3194: }
3195: $what =~ s/\:$/&/;
3196: }
3197: $what =~ s/\&$//;
3198: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3199: } else {
3200: return $outcome;
3201: }
1.353 www 3202: }
3203:
3204: sub courseiddump {
1.921 raeburn 3205: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3206: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3207: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3! raeburn 3208: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3209: my $as_hash = 1;
3210: my %returnhash;
3211: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3212: my %libserv = &all_library();
3213: foreach my $tryserver (keys(%libserv)) {
3214: if ( ( $hostidflag == 1
3215: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3216: || (!defined($hostidflag)) ) {
3217:
1.918 raeburn 3218: if (($domfilter eq '') ||
3219: (&host_domain($tryserver) eq $domfilter)) {
3220: my $rep =
3221: &reply('courseiddump:'.&host_domain($tryserver).':'.
3222: $sincefilter.':'.&escape($descfilter).':'.
3223: &escape($instcodefilter).':'.&escape($ownerfilter).
3224: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3225: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3226: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3227: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3228: &escape($cc_clone).':'.$cloneonly.':'.
3229: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3! raeburn 3230: &escape($creationcontext).':'.$domcloner,
! 3231: $tryserver);
1.918 raeburn 3232: my @pairs=split(/\&/,$rep);
3233: foreach my $item (@pairs) {
3234: my ($key,$value)=split(/\=/,$item,2);
3235: $key = &unescape($key);
3236: next if ($key =~ /^error: 2 /);
3237: my $result = &thaw_unescape($value);
3238: if (ref($result) eq 'HASH') {
3239: $returnhash{$key}=$result;
3240: } else {
1.921 raeburn 3241: my @responses = split(/:/,$value);
3242: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3243: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3244: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3245: }
1.1008 raeburn 3246: }
1.353 www 3247: }
3248: }
3249: }
3250: }
3251: return %returnhash;
3252: }
3253:
1.1055 raeburn 3254: sub courselastaccess {
3255: my ($cdom,$cnum,$hostidref) = @_;
3256: my %returnhash;
3257: if ($cdom && $cnum) {
3258: my $chome = &homeserver($cnum,$cdom);
3259: if ($chome ne 'no_host') {
3260: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3261: &extract_lastaccess(\%returnhash,$rep);
3262: }
3263: } else {
3264: if (!$cdom) { $cdom=''; }
3265: my %libserv = &all_library();
3266: foreach my $tryserver (keys(%libserv)) {
3267: if (ref($hostidref) eq 'ARRAY') {
3268: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3269: }
3270: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3271: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3272: &extract_lastaccess(\%returnhash,$rep);
3273: }
3274: }
3275: }
3276: return %returnhash;
3277: }
3278:
3279: sub extract_lastaccess {
3280: my ($returnhash,$rep) = @_;
3281: if (ref($returnhash) eq 'HASH') {
3282: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3283: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3284: $rep eq '') {
3285: my @pairs=split(/\&/,$rep);
3286: foreach my $item (@pairs) {
3287: my ($key,$value)=split(/\=/,$item,2);
3288: $key = &unescape($key);
3289: next if ($key =~ /^error: 2 /);
3290: $returnhash->{$key} = &thaw_unescape($value);
3291: }
3292: }
3293: }
3294: return;
3295: }
3296:
1.658 raeburn 3297: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3298:
3299: sub dcmailput {
1.685 raeburn 3300: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3301: my $status = &Apache::lonnet::critical(
1.740 www 3302: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3303: &escape($message),$server);
1.662 raeburn 3304: return $status;
3305: }
3306:
1.658 raeburn 3307: sub dcmaildump {
3308: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3309: my %returnhash=();
1.846 albertel 3310:
3311: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3312: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3313: &escape($enddate).':';
3314: my @esc_senders=map { &escape($_)} @$senders;
3315: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3316: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3317: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3318: if (($key) && ($value)) {
3319: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3320: }
3321: }
3322: }
3323: return %returnhash;
3324: }
1.662 raeburn 3325: # ---------------------------------------------------------- Domain roles
3326:
3327: sub get_domain_roles {
3328: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3329: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3330: $startdate = '.';
3331: }
1.1018 raeburn 3332: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3333: $enddate = '.';
3334: }
1.922 raeburn 3335: my $rolelist;
3336: if (ref($roles) eq 'ARRAY') {
3337: $rolelist = join(':',@{$roles});
3338: }
1.662 raeburn 3339: my %personnel = ();
1.841 albertel 3340:
3341: my %servers = &get_servers($dom,'library');
3342: foreach my $tryserver (keys(%servers)) {
3343: %{$personnel{$tryserver}}=();
3344: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3345: &escape($startdate).':'.
3346: &escape($enddate).':'.
3347: &escape($rolelist), $tryserver))) {
3348: my ($key,$value) = split(/\=/,$line,2);
3349: if (($key) && ($value)) {
3350: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3351: }
3352: }
1.662 raeburn 3353: }
3354: return %personnel;
3355: }
1.658 raeburn 3356:
1.149 www 3357: # ----------------------------------------------------------- Check out an item
3358:
1.504 albertel 3359: sub get_first_access {
3360: my ($type,$argsymb)=@_;
1.790 albertel 3361: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3362: if ($argsymb) { $symb=$argsymb; }
3363: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3364: if ($type eq 'course') {
3365: $res='course';
3366: } elsif ($type eq 'map') {
1.588 albertel 3367: $res=&symbread($map);
3368: } else {
3369: $res=$symb;
3370: }
3371: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3372: return $times{"$courseid\0$res"};
1.504 albertel 3373: }
3374:
3375: sub set_first_access {
3376: my ($type)=@_;
1.790 albertel 3377: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3378: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3379: if ($type eq 'course') {
3380: $res='course';
3381: } elsif ($type eq 'map') {
1.588 albertel 3382: $res=&symbread($map);
3383: } else {
3384: $res=$symb;
3385: }
3386: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3387: if (!$firstaccess) {
1.588 albertel 3388: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3389: }
3390: return 'already_set';
1.504 albertel 3391: }
3392:
1.149 www 3393: sub checkout {
3394: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3395: my $now=time;
3396: my $lonhost=$perlvar{'lonHostID'};
3397: my $infostr=&escape(
1.234 www 3398: 'CHECKOUTTOKEN&'.
1.149 www 3399: $tuname.'&'.
3400: $tudom.'&'.
3401: $tcrsid.'&'.
3402: $symb.'&'.
3403: $now.'&'.$ENV{'REMOTE_ADDR'});
3404: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 3405: if ($token=~/^error\:/) {
1.672 albertel 3406: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3407: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3408: "</font>");
3409: return '';
3410: }
3411:
1.149 www 3412: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3413: $token=~tr/a-z/A-Z/;
3414:
1.153 www 3415: my %infohash=('resource.0.outtoken' => $token,
3416: 'resource.0.checkouttime' => $now,
3417: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 3418:
3419: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3420: return '';
1.151 www 3421: } else {
1.672 albertel 3422: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3423: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3424: "</font>");
1.149 www 3425: }
3426:
3427: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3428: &escape('Checkout '.$infostr.' - '.
3429: $token)) ne 'ok') {
3430: return '';
1.151 www 3431: } else {
1.672 albertel 3432: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3433: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3434: "</font>");
1.149 www 3435: }
1.151 www 3436: return $token;
1.149 www 3437: }
3438:
3439: # ------------------------------------------------------------ Check in an item
3440:
3441: sub checkin {
3442: my $token=shift;
1.150 www 3443: my $now=time;
3444: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3445: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 3446: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 3447: $dtoken=~s/\W/\_/g;
1.234 www 3448: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 3449: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3450:
1.154 www 3451: unless (($tuname) && ($tudom)) {
3452: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3453: return '';
3454: }
3455:
3456: unless (&allowed('mgr',$tcrsid)) {
3457: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 3458: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 3459: return '';
3460: }
3461:
1.153 www 3462: my %infohash=('resource.0.intoken' => $token,
3463: 'resource.0.checkintime' => $now,
3464: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 3465:
3466: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3467: return '';
3468: }
3469:
3470: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3471: &escape('Checkin - '.$token)) ne 'ok') {
3472: return '';
3473: }
3474:
3475: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 3476: }
3477:
3478: # --------------------------------------------- Set Expire Date for Spreadsheet
3479:
3480: sub expirespread {
3481: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3482: my $cid=$env{'request.course.id'};
1.110 www 3483: if ($cid) {
3484: my $now=time;
3485: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3486: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3487: $env{'course.'.$cid.'.num'}.
1.110 www 3488: ':nohist_expirationdates:'.
3489: &escape($key).'='.$now,
1.620 albertel 3490: $env{'course.'.$cid.'.home'})
1.110 www 3491: }
3492: return 'ok';
1.14 www 3493: }
3494:
1.109 www 3495: # ----------------------------------------------------- Devalidate Spreadsheets
3496:
3497: sub devalidate {
1.325 www 3498: my ($symb,$uname,$udom)=@_;
1.620 albertel 3499: my $cid=$env{'request.course.id'};
1.109 www 3500: if ($cid) {
1.391 matthew 3501: # delete the stored spreadsheets for
3502: # - the student level sheet of this user in course's homespace
3503: # - the assessment level sheet for this resource
3504: # for this user in user's homespace
1.553 albertel 3505: # - current conditional state info
1.325 www 3506: my $key=$uname.':'.$udom.':';
1.109 www 3507: my $status=
1.299 matthew 3508: &del('nohist_calculatedsheets',
1.391 matthew 3509: [$key.'studentcalc:'],
1.620 albertel 3510: $env{'course.'.$cid.'.domain'},
3511: $env{'course.'.$cid.'.num'})
1.133 albertel 3512: .' '.
3513: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3514: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3515: unless ($status eq 'ok ok') {
3516: &logthis('Could not devalidate spreadsheet '.
1.325 www 3517: $uname.' at '.$udom.' for '.
1.109 www 3518: $symb.': '.$status);
1.133 albertel 3519: }
1.553 albertel 3520: &delenv('user.state.'.$cid);
1.109 www 3521: }
3522: }
3523:
1.265 albertel 3524: sub get_scalar {
3525: my ($string,$end) = @_;
3526: my $value;
3527: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3528: $value = $1;
3529: } elsif ($$string =~ s/^([^&]*?)&//) {
3530: $value = $1;
3531: }
3532: return &unescape($value);
3533: }
3534:
3535: sub array2str {
3536: my (@array) = @_;
3537: my $result=&arrayref2str(\@array);
3538: $result=~s/^__ARRAY_REF__//;
3539: $result=~s/__END_ARRAY_REF__$//;
3540: return $result;
3541: }
3542:
1.204 albertel 3543: sub arrayref2str {
3544: my ($arrayref) = @_;
1.265 albertel 3545: my $result='__ARRAY_REF__';
1.204 albertel 3546: foreach my $elem (@$arrayref) {
1.265 albertel 3547: if(ref($elem) eq 'ARRAY') {
3548: $result.=&arrayref2str($elem).'&';
3549: } elsif(ref($elem) eq 'HASH') {
3550: $result.=&hashref2str($elem).'&';
3551: } elsif(ref($elem)) {
3552: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3553: } else {
3554: $result.=&escape($elem).'&';
3555: }
3556: }
3557: $result=~s/\&$//;
1.265 albertel 3558: $result .= '__END_ARRAY_REF__';
1.204 albertel 3559: return $result;
3560: }
3561:
1.168 albertel 3562: sub hash2str {
1.204 albertel 3563: my (%hash) = @_;
3564: my $result=&hashref2str(\%hash);
1.265 albertel 3565: $result=~s/^__HASH_REF__//;
3566: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3567: return $result;
3568: }
3569:
3570: sub hashref2str {
3571: my ($hashref)=@_;
1.265 albertel 3572: my $result='__HASH_REF__';
1.800 albertel 3573: foreach my $key (sort(keys(%$hashref))) {
3574: if (ref($key) eq 'ARRAY') {
3575: $result.=&arrayref2str($key).'=';
3576: } elsif (ref($key) eq 'HASH') {
3577: $result.=&hashref2str($key).'=';
3578: } elsif (ref($key)) {
1.265 albertel 3579: $result.='=';
1.800 albertel 3580: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3581: } else {
1.800 albertel 3582: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3583: }
3584:
1.800 albertel 3585: if(ref($hashref->{$key}) eq 'ARRAY') {
3586: $result.=&arrayref2str($hashref->{$key}).'&';
3587: } elsif(ref($hashref->{$key}) eq 'HASH') {
3588: $result.=&hashref2str($hashref->{$key}).'&';
3589: } elsif(ref($hashref->{$key})) {
1.265 albertel 3590: $result.='&';
1.800 albertel 3591: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3592: } else {
1.800 albertel 3593: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3594: }
3595: }
1.168 albertel 3596: $result=~s/\&$//;
1.265 albertel 3597: $result .= '__END_HASH_REF__';
1.168 albertel 3598: return $result;
3599: }
3600:
3601: sub str2hash {
1.265 albertel 3602: my ($string)=@_;
3603: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3604: return %$hash;
3605: }
3606:
3607: sub str2hashref {
1.168 albertel 3608: my ($string) = @_;
1.265 albertel 3609:
3610: my %hash;
3611:
3612: if($string !~ /^__HASH_REF__/) {
3613: if (! ($string eq '' || !defined($string))) {
3614: $hash{'error'}='Not hash reference';
3615: }
3616: return (\%hash, $string);
3617: }
3618:
3619: $string =~ s/^__HASH_REF__//;
3620:
3621: while($string !~ /^__END_HASH_REF__/) {
3622: #key
3623: my $key='';
3624: if($string =~ /^__HASH_REF__/) {
3625: ($key, $string)=&str2hashref($string);
3626: if(defined($key->{'error'})) {
3627: $hash{'error'}='Bad data';
3628: return (\%hash, $string);
3629: }
3630: } elsif($string =~ /^__ARRAY_REF__/) {
3631: ($key, $string)=&str2arrayref($string);
3632: if($key->[0] eq 'Array reference error') {
3633: $hash{'error'}='Bad data';
3634: return (\%hash, $string);
3635: }
3636: } else {
3637: $string =~ s/^(.*?)=//;
1.267 albertel 3638: $key=&unescape($1);
1.265 albertel 3639: }
3640: $string =~ s/^=//;
3641:
3642: #value
3643: my $value='';
3644: if($string =~ /^__HASH_REF__/) {
3645: ($value, $string)=&str2hashref($string);
3646: if(defined($value->{'error'})) {
3647: $hash{'error'}='Bad data';
3648: return (\%hash, $string);
3649: }
3650: } elsif($string =~ /^__ARRAY_REF__/) {
3651: ($value, $string)=&str2arrayref($string);
3652: if($value->[0] eq 'Array reference error') {
3653: $hash{'error'}='Bad data';
3654: return (\%hash, $string);
3655: }
3656: } else {
3657: $value=&get_scalar(\$string,'__END_HASH_REF__');
3658: }
3659: $string =~ s/^&//;
3660:
3661: $hash{$key}=$value;
1.204 albertel 3662: }
1.265 albertel 3663:
3664: $string =~ s/^__END_HASH_REF__//;
3665:
3666: return (\%hash, $string);
1.204 albertel 3667: }
3668:
3669: sub str2array {
1.265 albertel 3670: my ($string)=@_;
3671: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3672: return @$array;
3673: }
3674:
3675: sub str2arrayref {
1.204 albertel 3676: my ($string) = @_;
1.265 albertel 3677: my @array;
3678:
3679: if($string !~ /^__ARRAY_REF__/) {
3680: if (! ($string eq '' || !defined($string))) {
3681: $array[0]='Array reference error';
3682: }
3683: return (\@array, $string);
3684: }
3685:
3686: $string =~ s/^__ARRAY_REF__//;
3687:
3688: while($string !~ /^__END_ARRAY_REF__/) {
3689: my $value='';
3690: if($string =~ /^__HASH_REF__/) {
3691: ($value, $string)=&str2hashref($string);
3692: if(defined($value->{'error'})) {
3693: $array[0] ='Array reference error';
3694: return (\@array, $string);
3695: }
3696: } elsif($string =~ /^__ARRAY_REF__/) {
3697: ($value, $string)=&str2arrayref($string);
3698: if($value->[0] eq 'Array reference error') {
3699: $array[0] ='Array reference error';
3700: return (\@array, $string);
3701: }
3702: } else {
3703: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3704: }
3705: $string =~ s/^&//;
3706:
3707: push(@array, $value);
1.191 harris41 3708: }
1.265 albertel 3709:
3710: $string =~ s/^__END_ARRAY_REF__//;
3711:
3712: return (\@array, $string);
1.168 albertel 3713: }
3714:
1.167 albertel 3715: # -------------------------------------------------------------------Temp Store
3716:
1.168 albertel 3717: sub tmpreset {
3718: my ($symb,$namespace,$domain,$stuname) = @_;
3719: if (!$symb) {
3720: $symb=&symbread();
1.620 albertel 3721: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3722: }
3723: $symb=escape($symb);
3724:
1.620 albertel 3725: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3726: $namespace=~s/\//\_/g;
3727: $namespace=~s/\W//g;
3728:
1.620 albertel 3729: if (!$domain) { $domain=$env{'user.domain'}; }
3730: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3731: if ($domain eq 'public' && $stuname eq 'public') {
3732: $stuname=$ENV{'REMOTE_ADDR'};
3733: }
1.168 albertel 3734: my $path=$perlvar{'lonDaemons'}.'/tmp';
3735: my %hash;
3736: if (tie(%hash,'GDBM_File',
3737: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3738: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3739: foreach my $key (keys(%hash)) {
1.180 albertel 3740: if ($key=~ /:$symb/) {
1.168 albertel 3741: delete($hash{$key});
3742: }
3743: }
3744: }
3745: }
3746:
1.167 albertel 3747: sub tmpstore {
1.168 albertel 3748: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3749:
3750: if (!$symb) {
3751: $symb=&symbread();
1.620 albertel 3752: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3753: }
3754: $symb=escape($symb);
3755:
3756: if (!$namespace) {
3757: # I don't think we would ever want to store this for a course.
3758: # it seems this will only be used if we don't have a course.
1.620 albertel 3759: #$namespace=$env{'request.course.id'};
1.168 albertel 3760: #if (!$namespace) {
1.620 albertel 3761: $namespace=$env{'request.state'};
1.168 albertel 3762: #}
3763: }
3764: $namespace=~s/\//\_/g;
3765: $namespace=~s/\W//g;
1.620 albertel 3766: if (!$domain) { $domain=$env{'user.domain'}; }
3767: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3768: if ($domain eq 'public' && $stuname eq 'public') {
3769: $stuname=$ENV{'REMOTE_ADDR'};
3770: }
1.168 albertel 3771: my $now=time;
3772: my %hash;
3773: my $path=$perlvar{'lonDaemons'}.'/tmp';
3774: if (tie(%hash,'GDBM_File',
3775: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3776: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3777: $hash{"version:$symb"}++;
3778: my $version=$hash{"version:$symb"};
3779: my $allkeys='';
3780: foreach my $key (keys(%$storehash)) {
3781: $allkeys.=$key.':';
1.591 albertel 3782: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3783: }
3784: $hash{"$version:$symb:timestamp"}=$now;
3785: $allkeys.='timestamp';
3786: $hash{"$version:keys:$symb"}=$allkeys;
3787: if (untie(%hash)) {
3788: return 'ok';
3789: } else {
3790: return "error:$!";
3791: }
3792: } else {
3793: return "error:$!";
3794: }
3795: }
1.167 albertel 3796:
1.168 albertel 3797: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3798:
1.168 albertel 3799: sub tmprestore {
3800: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3801:
1.168 albertel 3802: if (!$symb) {
3803: $symb=&symbread();
1.620 albertel 3804: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3805: }
3806: $symb=escape($symb);
3807:
1.620 albertel 3808: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3809:
1.620 albertel 3810: if (!$domain) { $domain=$env{'user.domain'}; }
3811: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3812: if ($domain eq 'public' && $stuname eq 'public') {
3813: $stuname=$ENV{'REMOTE_ADDR'};
3814: }
1.168 albertel 3815: my %returnhash;
3816: $namespace=~s/\//\_/g;
3817: $namespace=~s/\W//g;
3818: my %hash;
3819: my $path=$perlvar{'lonDaemons'}.'/tmp';
3820: if (tie(%hash,'GDBM_File',
3821: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3822: &GDBM_READER(),0640)) {
1.168 albertel 3823: my $version=$hash{"version:$symb"};
3824: $returnhash{'version'}=$version;
3825: my $scope;
3826: for ($scope=1;$scope<=$version;$scope++) {
3827: my $vkeys=$hash{"$scope:keys:$symb"};
3828: my @keys=split(/:/,$vkeys);
3829: my $key;
3830: $returnhash{"$scope:keys"}=$vkeys;
3831: foreach $key (@keys) {
1.591 albertel 3832: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3833: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3834: }
3835: }
1.168 albertel 3836: if (!(untie(%hash))) {
3837: return "error:$!";
3838: }
3839: } else {
3840: return "error:$!";
3841: }
3842: return %returnhash;
1.167 albertel 3843: }
3844:
1.9 www 3845: # ----------------------------------------------------------------------- Store
3846:
3847: sub store {
1.124 www 3848: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3849: my $home='';
3850:
1.168 albertel 3851: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3852:
1.213 www 3853: $symb=&symbclean($symb);
1.122 albertel 3854: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3855:
1.620 albertel 3856: if (!$domain) { $domain=$env{'user.domain'}; }
3857: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3858:
3859: &devalidate($symb,$stuname,$domain);
1.109 www 3860:
3861: $symb=escape($symb);
1.187 www 3862: if (!$namespace) {
1.620 albertel 3863: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3864: return '';
3865: }
3866: }
1.620 albertel 3867: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3868:
3869: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3870: $$storehash{'host'}=$perlvar{'lonHostID'};
3871:
1.12 www 3872: my $namevalue='';
1.800 albertel 3873: foreach my $key (keys(%$storehash)) {
3874: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3875: }
1.12 www 3876: $namevalue=~s/\&$//;
1.187 www 3877: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3878: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3879: }
3880:
1.47 www 3881: # -------------------------------------------------------------- Critical Store
3882:
3883: sub cstore {
1.124 www 3884: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3885: my $home='';
3886:
1.168 albertel 3887: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3888:
1.213 www 3889: $symb=&symbclean($symb);
1.122 albertel 3890: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3891:
1.620 albertel 3892: if (!$domain) { $domain=$env{'user.domain'}; }
3893: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3894:
3895: &devalidate($symb,$stuname,$domain);
1.109 www 3896:
3897: $symb=escape($symb);
1.187 www 3898: if (!$namespace) {
1.620 albertel 3899: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3900: return '';
3901: }
3902: }
1.620 albertel 3903: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3904:
3905: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3906: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3907:
1.47 www 3908: my $namevalue='';
1.800 albertel 3909: foreach my $key (keys(%$storehash)) {
3910: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3911: }
1.47 www 3912: $namevalue=~s/\&$//;
1.187 www 3913: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3914: return critical
3915: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3916: }
3917:
1.9 www 3918: # --------------------------------------------------------------------- Restore
3919:
3920: sub restore {
1.124 www 3921: my ($symb,$namespace,$domain,$stuname) = @_;
3922: my $home='';
3923:
1.168 albertel 3924: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3925:
1.122 albertel 3926: if (!$symb) {
3927: unless ($symb=escape(&symbread())) { return ''; }
3928: } else {
1.213 www 3929: $symb=&escape(&symbclean($symb));
1.122 albertel 3930: }
1.188 www 3931: if (!$namespace) {
1.620 albertel 3932: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3933: return '';
3934: }
3935: }
1.620 albertel 3936: if (!$domain) { $domain=$env{'user.domain'}; }
3937: if (!$stuname) { $stuname=$env{'user.name'}; }
3938: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3939: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3940:
1.12 www 3941: my %returnhash=();
1.800 albertel 3942: foreach my $line (split(/\&/,$answer)) {
3943: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3944: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3945: }
1.75 www 3946: my $version;
3947: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3948: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3949: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3950: }
1.75 www 3951: }
1.13 www 3952: return %returnhash;
1.34 www 3953: }
3954:
3955: # ---------------------------------------------------------- Course Description
3956:
3957: sub coursedescription {
1.731 albertel 3958: my ($courseid,$args)=@_;
1.34 www 3959: $courseid=~s/^\///;
1.49 www 3960: $courseid=~s/\_/\//g;
1.34 www 3961: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3962: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3963: my $normalid=$cdomain.'_'.$cnum;
3964: # need to always cache even if we get errors otherwise we keep
3965: # trying and trying and trying to get the course description.
3966: my %envhash=();
3967: my %returnhash=();
1.731 albertel 3968:
3969: my $expiretime=600;
3970: if ($env{'request.course.id'} eq $normalid) {
3971: $expiretime=120;
3972: }
3973:
3974: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3975: if (!$args->{'freshen_cache'}
3976: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3977: foreach my $key (keys(%env)) {
3978: next if ($key !~ /^\Q$prefix\E(.*)/);
3979: my ($setting) = $1;
3980: $returnhash{$setting} = $env{$key};
3981: }
3982: return %returnhash;
3983: }
3984:
3985: # get the data agin
3986: if (!$args->{'one_time'}) {
3987: $envhash{'course.'.$normalid.'.last_cache'}=time;
3988: }
1.811 albertel 3989:
1.34 www 3990: if ($chome ne 'no_host') {
1.302 albertel 3991: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3992: if (!exists($returnhash{'con_lost'})) {
3993: $returnhash{'home'}= $chome;
3994: $returnhash{'domain'} = $cdomain;
3995: $returnhash{'num'} = $cnum;
1.741 raeburn 3996: if (!defined($returnhash{'type'})) {
3997: $returnhash{'type'} = 'Course';
3998: }
1.130 albertel 3999: while (my ($name,$value) = each %returnhash) {
1.53 www 4000: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4001: }
1.270 www 4002: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 4003: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 4004: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 4005: $envhash{'course.'.$normalid.'.home'}=$chome;
4006: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4007: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4008: }
4009: }
1.731 albertel 4010: if (!$args->{'one_time'}) {
1.949 raeburn 4011: &appenv(\%envhash);
1.731 albertel 4012: }
1.302 albertel 4013: return %returnhash;
1.461 www 4014: }
4015:
4016: # -------------------------------------------------See if a user is privileged
4017:
4018: sub privileged {
4019: my ($username,$domain)=@_;
4020: my $rolesdump=&reply("dump:$domain:$username:roles",
4021: &homeserver($username,$domain));
1.1033 raeburn 4022: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4023: ($rolesdump =~ /^error:/)) {
4024: return 0;
4025: }
1.461 www 4026: my $now=time;
4027: if ($rolesdump ne '') {
1.800 albertel 4028: foreach my $entry (split(/&/,$rolesdump)) {
4029: if ($entry!~/^rolesdef_/) {
4030: my ($area,$role)=split(/=/,$entry);
1.461 www 4031: $area=~s/\_\w\w$//;
4032: my ($trole,$tend,$tstart)=split(/_/,$role);
4033: if (($trole eq 'dc') || ($trole eq 'su')) {
4034: my $active=1;
4035: if ($tend) {
4036: if ($tend<$now) { $active=0; }
4037: }
4038: if ($tstart) {
4039: if ($tstart>$now) { $active=0; }
4040: }
4041: if ($active) { return 1; }
4042: }
4043: }
4044: }
4045: }
4046: return 0;
1.9 www 4047: }
1.1 albertel 4048:
1.103 harris41 4049: # -------------------------------------------------------- Get user privileges
1.11 www 4050:
4051: sub rolesinit {
4052: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4053: my $now=time;
4054: my %userroles = ('user.login.time' => $now);
1.1056.4.3! raeburn 4055: my $extra = &freeze_escape({'clientcheckrole' => 1});
! 4056: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4057: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1056.4.3! raeburn 4058: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4059: return \%userroles;
4060: }
1.11 www 4061: my %allroles=();
1.678 raeburn 4062: my %allgroups=();
4063: my $group_privs;
1.11 www 4064:
4065: if ($rolesdump ne '') {
1.800 albertel 4066: foreach my $entry (split(/&/,$rolesdump)) {
4067: if ($entry!~/^rolesdef_/) {
4068: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4069: $area=~s/\_\w\w$//;
1.678 raeburn 4070: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4071: if ($role=~/^cr/) {
1.807 albertel 4072: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4073: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4074: ($tend,$tstart)=split('_',$trest);
4075: } else {
4076: $trole=$role;
4077: }
1.678 raeburn 4078: } elsif ($role =~ m|^gr/|) {
4079: ($trole,$tend,$tstart) = split(/_/,$role);
4080: ($trole,$group_privs) = split(/\//,$trole);
4081: $group_privs = &unescape($group_privs);
1.587 albertel 4082: } else {
4083: ($trole,$tend,$tstart)=split(/_/,$role);
4084: }
1.743 albertel 4085: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4086: $username);
4087: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4088: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4089: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4090: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4091: my $spec=$trole.'.'.$area;
4092: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4093: if ($trole =~ /^cr\//) {
1.567 raeburn 4094: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4095: } elsif ($trole eq 'gr') {
4096: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4097: } else {
1.567 raeburn 4098: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4099: }
1.12 www 4100: }
1.662 raeburn 4101: }
1.191 harris41 4102: }
1.743 albertel 4103: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4104: $userroles{'user.adv'} = $adv;
4105: $userroles{'user.author'} = $author;
1.620 albertel 4106: $env{'user.adv'}=$adv;
1.11 www 4107: }
1.743 albertel 4108: return \%userroles;
1.11 www 4109: }
4110:
1.567 raeburn 4111: sub set_arearole {
4112: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4113: # log the associated role with the area
4114: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4115: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4116: }
4117:
4118: sub custom_roleprivs {
4119: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4120: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4121: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4122: if (&hostname($homsvr) ne '') {
1.567 raeburn 4123: my ($rdummy,$roledef)=
4124: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4125: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4126: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4127: if (defined($syspriv)) {
1.1043 raeburn 4128: if ($trest =~ /^$match_community$/) {
4129: $syspriv =~ s/bre\&S//;
4130: }
1.567 raeburn 4131: $$allroles{'cm./'}.=':'.$syspriv;
4132: $$allroles{$spec.'./'}.=':'.$syspriv;
4133: }
4134: if ($tdomain ne '') {
4135: if (defined($dompriv)) {
4136: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4137: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4138: }
4139: if (($trest ne '') && (defined($coursepriv))) {
4140: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4141: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4142: }
4143: }
4144: }
4145: }
4146: }
4147:
1.678 raeburn 4148: sub group_roleprivs {
4149: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4150: my $access = 1;
4151: my $now = time;
4152: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4153: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4154: if ($access) {
1.811 albertel 4155: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4156: $$allgroups{$course}{$group} .=':'.$group_privs;
4157: }
4158: }
1.567 raeburn 4159:
4160: sub standard_roleprivs {
4161: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4162: if (defined($pr{$trole.':s'})) {
4163: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4164: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4165: }
4166: if ($tdomain ne '') {
4167: if (defined($pr{$trole.':d'})) {
4168: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4169: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4170: }
4171: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4172: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4173: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4174: }
4175: }
4176: }
4177:
4178: sub set_userprivs {
1.1056.4.2 raeburn 4179: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4180: my $author=0;
4181: my $adv=0;
1.678 raeburn 4182: my %grouproles = ();
4183: if (keys(%{$allgroups}) > 0) {
1.1056.4.2 raeburn 4184: my @groupkeys;
1.1000 raeburn 4185: foreach my $role (keys(%{$allroles})) {
1.1056.4.2 raeburn 4186: push(@groupkeys,$role);
4187: }
4188: if (ref($groups_roles) eq 'HASH') {
4189: foreach my $key (keys(%{$groups_roles})) {
4190: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4191: push(@groupkeys,$key);
4192: }
4193: }
4194: }
4195: if (@groupkeys > 0) {
4196: foreach my $role (@groupkeys) {
4197: my ($trole,$area,$sec,$extendedarea);
4198: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4199: $trole = $1;
4200: $area = $2;
4201: $sec = $3;
4202: $extendedarea = $area.$sec;
4203: if (exists($$allgroups{$area})) {
4204: foreach my $group (keys(%{$$allgroups{$area}})) {
4205: my $spec = $trole.'.'.$extendedarea;
4206: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4207: $$allgroups{$area}{$group};
1.1056.4.2 raeburn 4208: }
1.678 raeburn 4209: }
4210: }
4211: }
4212: }
4213: }
1.800 albertel 4214: foreach my $group (keys(%grouproles)) {
4215: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4216: }
1.800 albertel 4217: foreach my $role (keys(%{$allroles})) {
4218: my %thesepriv;
1.941 raeburn 4219: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4220: foreach my $item (split(/:/,$$allroles{$role})) {
4221: if ($item ne '') {
4222: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4223: if ($restrictions eq '') {
4224: $thesepriv{$privilege}='F';
4225: } elsif ($thesepriv{$privilege} ne 'F') {
4226: $thesepriv{$privilege}.=$restrictions;
4227: }
4228: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4229: }
4230: }
4231: my $thesestr='';
1.800 albertel 4232: foreach my $priv (keys(%thesepriv)) {
4233: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4234: }
4235: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4236: }
4237: return ($author,$adv);
4238: }
4239:
1.994 raeburn 4240: sub role_status {
1.1002 raeburn 4241: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4242: my @pwhere = ();
4243: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4244: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4245: unless (!defined($$role) || $$role eq '') {
4246: $$where=join('.',@pwhere);
4247: $$trolecode=$$role.'.'.$$where;
4248: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4249: $$tstatus='is';
4250: if ($$tstart && $$tstart>$then) {
4251: $$tstatus='future';
1.1034 raeburn 4252: if ($$tstart<$now) {
4253: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4254: if (($$where ne '') && ($$role ne '')) {
1.1056.4.2 raeburn 4255: my (%allroles,%allgroups,$group_privs,
4256: %groups_roles,@rolecodes);
1.1002 raeburn 4257: my %userroles = (
4258: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4259: );
1.1056.4.2 raeburn 4260: @rolecodes = ('cm');
1.1002 raeburn 4261: my $spec=$$role.'.'.$$where;
4262: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4263: if ($$role =~ /^cr\//) {
4264: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2 raeburn 4265: push(@rolecodes,'cr');
1.1002 raeburn 4266: } elsif ($$role eq 'gr') {
1.1056.4.2 raeburn 4267: push(@rolecodes,$$role);
1.1002 raeburn 4268: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4269: $env{'user.name'});
1.1056.4.2 raeburn 4270: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
4271:
1.1002 raeburn 4272: (undef,my $group_privs) = split(/\//,$trole);
4273: $group_privs = &unescape($group_privs);
4274: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2 raeburn 4275: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4276: if (keys(%course_roles) > 0) {
4277: my ($tnum) = ($trest =~ /^($match_courseid)/);
4278: if ($tdomain ne '' && $tnum ne '') {
4279: foreach my $key (keys(%course_roles)) {
4280: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4281: my $crsrole = $1;
4282: my $crssec = $2;
4283: if ($crsrole =~ /^cr/) {
4284: unless (grep(/^cr$/,@rolecodes)) {
4285: push(@rolecodes,'cr');
4286: }
4287: } else {
4288: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4289: push(@rolecodes,$crsrole);
4290: }
4291: }
4292: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4293: if ($crssec ne '') {
4294: $rolekey .= '/'.$crssec;
4295: }
4296: $rolekey .= './';
4297: $groups_roles{$rolekey} = \@rolecodes;
4298: }
4299: }
4300: }
4301: }
1.1002 raeburn 4302: } else {
1.1056.4.2 raeburn 4303: push(@rolecodes,$$role);
1.1002 raeburn 4304: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4305: }
1.1056.4.2 raeburn 4306: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4307: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4308: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4309: }
4310: }
1.1034 raeburn 4311: $$tstatus = 'is';
1.1002 raeburn 4312: }
1.994 raeburn 4313: }
4314: if ($$tend) {
4315: if ($$tend<$then) {
4316: $$tstatus='expired';
4317: } elsif ($$tend<$now) {
4318: $$tstatus='will_not';
4319: }
4320: }
4321: }
4322: }
4323: }
4324:
4325: sub check_adhoc_privs {
1.1002 raeburn 4326: my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994 raeburn 4327: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4328: if ($env{$cckey}) {
4329: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4330: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4331: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4332: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4333: }
4334: } else {
4335: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4336: }
4337: }
4338:
4339: sub set_adhoc_privileges {
4340: # role can be cc or ca
4341: my ($dcdom,$pickedcourse,$role) = @_;
4342: my $area = '/'.$dcdom.'/'.$pickedcourse;
4343: my $spec = $role.'.'.$area;
4344: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4345: $env{'user.name'});
4346: my %ccrole = ();
4347: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4348: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4349: &appenv(\%userroles,[$role,'cm']);
4350: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4351: &appenv( {'request.role' => $spec,
4352: 'request.role.domain' => $dcdom,
4353: 'request.course.sec' => ''
4354: }
4355: );
4356: my $tadv=0;
4357: if (&allowed('adv') eq 'F') { $tadv=1; }
4358: &appenv({'request.role.adv' => $tadv});
4359: }
4360:
1.12 www 4361: # --------------------------------------------------------------- get interface
4362:
4363: sub get {
1.131 albertel 4364: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4365: my $items='';
1.800 albertel 4366: foreach my $item (@$storearr) {
4367: $items.=&escape($item).'&';
1.191 harris41 4368: }
1.12 www 4369: $items=~s/\&$//;
1.620 albertel 4370: if (!$udomain) { $udomain=$env{'user.domain'}; }
4371: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4372: my $uhome=&homeserver($uname,$udomain);
4373:
1.133 albertel 4374: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4375: my @pairs=split(/\&/,$rep);
1.273 albertel 4376: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4377: return @pairs;
4378: }
1.15 www 4379: my %returnhash=();
1.42 www 4380: my $i=0;
1.800 albertel 4381: foreach my $item (@$storearr) {
4382: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4383: $i++;
1.191 harris41 4384: }
1.15 www 4385: return %returnhash;
1.27 www 4386: }
4387:
4388: # --------------------------------------------------------------- del interface
4389:
4390: sub del {
1.133 albertel 4391: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4392: my $items='';
1.800 albertel 4393: foreach my $item (@$storearr) {
4394: $items.=&escape($item).'&';
1.191 harris41 4395: }
1.984 neumanie 4396:
1.27 www 4397: $items=~s/\&$//;
1.620 albertel 4398: if (!$udomain) { $udomain=$env{'user.domain'}; }
4399: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4400: my $uhome=&homeserver($uname,$udomain);
4401: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4402: }
4403:
4404: # -------------------------------------------------------------- dump interface
4405:
4406: sub dump {
1.755 albertel 4407: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4408: if (!$udomain) { $udomain=$env{'user.domain'}; }
4409: if (!$uname) { $uname=$env{'user.name'}; }
4410: my $uhome=&homeserver($uname,$udomain);
4411: if ($regexp) {
4412: $regexp=&escape($regexp);
4413: } else {
4414: $regexp='.';
4415: }
4416: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4417: my @pairs=split(/\&/,$rep);
4418: my %returnhash=();
4419: foreach my $item (@pairs) {
4420: my ($key,$value)=split(/=/,$item,2);
4421: $key = &unescape($key);
4422: next if ($key =~ /^error: 2 /);
4423: $returnhash{$key}=&thaw_unescape($value);
4424: }
4425: return %returnhash;
1.407 www 4426: }
4427:
1.717 albertel 4428: # --------------------------------------------------------- dumpstore interface
4429:
4430: sub dumpstore {
4431: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4432: if (!$udomain) { $udomain=$env{'user.domain'}; }
4433: if (!$uname) { $uname=$env{'user.name'}; }
4434: my $uhome=&homeserver($uname,$udomain);
4435: if ($regexp) {
4436: $regexp=&escape($regexp);
4437: } else {
4438: $regexp='.';
4439: }
4440: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4441: my @pairs=split(/\&/,$rep);
4442: my %returnhash=();
4443: foreach my $item (@pairs) {
4444: my ($key,$value)=split(/=/,$item,2);
4445: next if ($key =~ /^error: 2 /);
4446: $returnhash{$key}=&thaw_unescape($value);
4447: }
4448: return %returnhash;
1.717 albertel 4449: }
4450:
1.407 www 4451: # -------------------------------------------------------------- keys interface
4452:
4453: sub getkeys {
4454: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4455: if (!$udomain) { $udomain=$env{'user.domain'}; }
4456: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4457: my $uhome=&homeserver($uname,$udomain);
4458: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4459: my @keyarray=();
1.800 albertel 4460: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4461: next if ($key =~ /^error: 2 /);
1.800 albertel 4462: push(@keyarray,&unescape($key));
1.407 www 4463: }
4464: return @keyarray;
1.318 matthew 4465: }
4466:
1.319 matthew 4467: # --------------------------------------------------------------- currentdump
4468: sub currentdump {
1.328 matthew 4469: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4470: $courseid = $env{'request.course.id'} if (! defined($courseid));
4471: $sdom = $env{'user.domain'} if (! defined($sdom));
4472: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4473: my $uhome = &homeserver($sname,$sdom);
4474: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4475: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4476: #
1.318 matthew 4477: my %returnhash=();
1.319 matthew 4478: #
4479: if ($rep eq "unknown_cmd") {
4480: # an old lond will not know currentdump
4481: # Do a dump and make it look like a currentdump
1.822 albertel 4482: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4483: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4484: my %hash = @tmp;
4485: @tmp=();
1.424 matthew 4486: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4487: } else {
4488: my @pairs=split(/\&/,$rep);
1.800 albertel 4489: foreach my $pair (@pairs) {
4490: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4491: my ($symb,$param) = split(/:/,$key);
4492: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4493: &thaw_unescape($value);
1.319 matthew 4494: }
1.191 harris41 4495: }
1.12 www 4496: return %returnhash;
1.424 matthew 4497: }
4498:
4499: sub convert_dump_to_currentdump{
4500: my %hash = %{shift()};
4501: my %returnhash;
4502: # Code ripped from lond, essentially. The only difference
4503: # here is the unescaping done by lonnet::dump(). Conceivably
4504: # we might run in to problems with parameter names =~ /^v\./
4505: while (my ($key,$value) = each(%hash)) {
4506: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4507: $symb = &unescape($symb);
4508: $param = &unescape($param);
1.424 matthew 4509: next if ($v eq 'version' || $symb eq 'keys');
4510: next if (exists($returnhash{$symb}) &&
4511: exists($returnhash{$symb}->{$param}) &&
4512: $returnhash{$symb}->{'v.'.$param} > $v);
4513: $returnhash{$symb}->{$param}=$value;
4514: $returnhash{$symb}->{'v.'.$param}=$v;
4515: }
4516: #
4517: # Remove all of the keys in the hashes which keep track of
4518: # the version of the parameter.
4519: while (my ($symb,$param_hash) = each(%returnhash)) {
4520: # use a foreach because we are going to delete from the hash.
4521: foreach my $key (keys(%$param_hash)) {
4522: delete($param_hash->{$key}) if ($key =~ /^v\./);
4523: }
4524: }
4525: return \%returnhash;
1.12 www 4526: }
4527:
1.627 albertel 4528: # ------------------------------------------------------ critical inc interface
4529:
4530: sub cinc {
4531: return &inc(@_,'critical');
4532: }
4533:
1.449 matthew 4534: # --------------------------------------------------------------- inc interface
4535:
4536: sub inc {
1.627 albertel 4537: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4538: if (!$udomain) { $udomain=$env{'user.domain'}; }
4539: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4540: my $uhome=&homeserver($uname,$udomain);
4541: my $items='';
4542: if (! ref($store)) {
4543: # got a single value, so use that instead
4544: $items = &escape($store).'=&';
4545: } elsif (ref($store) eq 'SCALAR') {
4546: $items = &escape($$store).'=&';
4547: } elsif (ref($store) eq 'ARRAY') {
4548: $items = join('=&',map {&escape($_);} @{$store});
4549: } elsif (ref($store) eq 'HASH') {
4550: while (my($key,$value) = each(%{$store})) {
4551: $items.= &escape($key).'='.&escape($value).'&';
4552: }
4553: }
4554: $items=~s/\&$//;
1.627 albertel 4555: if ($critical) {
4556: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4557: } else {
4558: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4559: }
1.449 matthew 4560: }
4561:
1.12 www 4562: # --------------------------------------------------------------- put interface
4563:
4564: sub put {
1.134 albertel 4565: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4566: if (!$udomain) { $udomain=$env{'user.domain'}; }
4567: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4568: my $uhome=&homeserver($uname,$udomain);
1.12 www 4569: my $items='';
1.800 albertel 4570: foreach my $item (keys(%$storehash)) {
4571: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4572: }
1.12 www 4573: $items=~s/\&$//;
1.134 albertel 4574: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4575: }
4576:
1.631 albertel 4577: # ------------------------------------------------------------ newput interface
4578:
4579: sub newput {
4580: my ($namespace,$storehash,$udomain,$uname)=@_;
4581: if (!$udomain) { $udomain=$env{'user.domain'}; }
4582: if (!$uname) { $uname=$env{'user.name'}; }
4583: my $uhome=&homeserver($uname,$udomain);
4584: my $items='';
4585: foreach my $key (keys(%$storehash)) {
4586: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4587: }
4588: $items=~s/\&$//;
4589: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4590: }
4591:
4592: # --------------------------------------------------------- putstore interface
4593:
1.524 raeburn 4594: sub putstore {
1.715 albertel 4595: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4596: if (!$udomain) { $udomain=$env{'user.domain'}; }
4597: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4598: my $uhome=&homeserver($uname,$udomain);
4599: my $items='';
1.715 albertel 4600: foreach my $key (keys(%$storehash)) {
4601: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4602: }
1.715 albertel 4603: $items=~s/\&$//;
1.716 albertel 4604: my $esc_symb=&escape($symb);
4605: my $esc_v=&escape($version);
1.715 albertel 4606: my $reply =
1.716 albertel 4607: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4608: $uhome);
4609: if ($reply eq 'unknown_cmd') {
1.716 albertel 4610: # gfall back to way things use to be done
1.715 albertel 4611: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4612: $uname);
1.524 raeburn 4613: }
1.715 albertel 4614: return $reply;
4615: }
4616:
4617: sub old_putstore {
1.716 albertel 4618: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4619: if (!$udomain) { $udomain=$env{'user.domain'}; }
4620: if (!$uname) { $uname=$env{'user.name'}; }
4621: my $uhome=&homeserver($uname,$udomain);
4622: my %newstorehash;
1.800 albertel 4623: foreach my $item (keys(%$storehash)) {
4624: my $key = $version.':'.&escape($symb).':'.$item;
4625: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4626: }
4627: my $items='';
4628: my %allitems = ();
1.800 albertel 4629: foreach my $item (keys(%newstorehash)) {
4630: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4631: my $key = $1.':keys:'.$2;
4632: $allitems{$key} .= $3.':';
4633: }
1.800 albertel 4634: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4635: }
1.800 albertel 4636: foreach my $item (keys(%allitems)) {
4637: $allitems{$item} =~ s/\:$//;
4638: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4639: }
4640: $items=~s/\&$//;
4641: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4642: }
4643:
1.47 www 4644: # ------------------------------------------------------ critical put interface
4645:
4646: sub cput {
1.134 albertel 4647: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4648: if (!$udomain) { $udomain=$env{'user.domain'}; }
4649: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4650: my $uhome=&homeserver($uname,$udomain);
1.47 www 4651: my $items='';
1.800 albertel 4652: foreach my $item (keys(%$storehash)) {
4653: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4654: }
1.47 www 4655: $items=~s/\&$//;
1.134 albertel 4656: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4657: }
4658:
4659: # -------------------------------------------------------------- eget interface
4660:
4661: sub eget {
1.133 albertel 4662: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4663: my $items='';
1.800 albertel 4664: foreach my $item (@$storearr) {
4665: $items.=&escape($item).'&';
1.191 harris41 4666: }
1.12 www 4667: $items=~s/\&$//;
1.620 albertel 4668: if (!$udomain) { $udomain=$env{'user.domain'}; }
4669: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4670: my $uhome=&homeserver($uname,$udomain);
4671: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4672: my @pairs=split(/\&/,$rep);
4673: my %returnhash=();
1.42 www 4674: my $i=0;
1.800 albertel 4675: foreach my $item (@$storearr) {
4676: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4677: $i++;
1.191 harris41 4678: }
1.12 www 4679: return %returnhash;
4680: }
4681:
1.667 albertel 4682: # ------------------------------------------------------------ tmpput interface
4683: sub tmpput {
1.802 raeburn 4684: my ($storehash,$server,$context)=@_;
1.667 albertel 4685: my $items='';
1.800 albertel 4686: foreach my $item (keys(%$storehash)) {
4687: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4688: }
4689: $items=~s/\&$//;
1.802 raeburn 4690: if (defined($context)) {
4691: $items .= ':'.&escape($context);
4692: }
1.667 albertel 4693: return &reply("tmpput:$items",$server);
4694: }
4695:
4696: # ------------------------------------------------------------ tmpget interface
4697: sub tmpget {
1.688 albertel 4698: my ($token,$server)=@_;
4699: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4700: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4701: my %returnhash;
4702: foreach my $item (split(/\&/,$rep)) {
4703: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4704: next if ($key =~ /^error: 2 /);
1.667 albertel 4705: $returnhash{&unescape($key)}=&thaw_unescape($value);
4706: }
4707: return %returnhash;
4708: }
4709:
1.688 albertel 4710: # ------------------------------------------------------------ tmpget interface
4711: sub tmpdel {
4712: my ($token,$server)=@_;
4713: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4714: return &reply("tmpdel:$token",$server);
4715: }
4716:
1.765 albertel 4717: # -------------------------------------------------- portfolio access checking
4718:
4719: sub portfolio_access {
1.766 albertel 4720: my ($requrl) = @_;
1.765 albertel 4721: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4722: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4723: if ($result) {
4724: my %setters;
4725: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4726: my ($startblock,$endblock) =
4727: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4728: if ($startblock && $endblock) {
4729: return 'B';
4730: }
4731: } else {
4732: my ($startblock,$endblock) =
4733: &Apache::loncommon::blockcheck(\%setters,'port');
4734: if ($startblock && $endblock) {
4735: return 'B';
4736: }
4737: }
4738: }
1.765 albertel 4739: if ($result eq 'ok') {
1.766 albertel 4740: return 'F';
1.765 albertel 4741: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4742: return 'A';
1.765 albertel 4743: }
1.766 albertel 4744: return '';
1.765 albertel 4745: }
4746:
4747: sub get_portfolio_access {
1.767 albertel 4748: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4749:
4750: if (!ref($access_hash)) {
4751: my $current_perms = &get_portfile_permissions($udom,$unum);
4752: my %access_controls = &get_access_controls($current_perms,$group,
4753: $file_name);
4754: $access_hash = $access_controls{$file_name};
4755: }
4756:
1.765 albertel 4757: my ($public,$guest,@domains,@users,@courses,@groups);
4758: my $now = time;
4759: if (ref($access_hash) eq 'HASH') {
4760: foreach my $key (keys(%{$access_hash})) {
4761: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4762: if ($start > $now) {
4763: next;
4764: }
4765: if ($end && $end<$now) {
4766: next;
4767: }
4768: if ($scope eq 'public') {
4769: $public = $key;
4770: last;
4771: } elsif ($scope eq 'guest') {
4772: $guest = $key;
4773: } elsif ($scope eq 'domains') {
4774: push(@domains,$key);
4775: } elsif ($scope eq 'users') {
4776: push(@users,$key);
4777: } elsif ($scope eq 'course') {
4778: push(@courses,$key);
4779: } elsif ($scope eq 'group') {
4780: push(@groups,$key);
4781: }
4782: }
4783: if ($public) {
4784: return 'ok';
4785: }
4786: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4787: if ($guest) {
4788: return $guest;
4789: }
4790: } else {
4791: if (@domains > 0) {
4792: foreach my $domkey (@domains) {
4793: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4794: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4795: return 'ok';
4796: }
4797: }
4798: }
4799: }
4800: if (@users > 0) {
4801: foreach my $userkey (@users) {
1.865 raeburn 4802: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4803: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4804: if (ref($item) eq 'HASH') {
4805: if (($item->{'uname'} eq $env{'user.name'}) &&
4806: ($item->{'udom'} eq $env{'user.domain'})) {
4807: return 'ok';
4808: }
4809: }
4810: }
4811: }
1.765 albertel 4812: }
4813: }
4814: my %roleshash;
4815: my @courses_and_groups = @courses;
4816: push(@courses_and_groups,@groups);
4817: if (@courses_and_groups > 0) {
4818: my (%allgroups,%allroles);
4819: my ($start,$end,$role,$sec,$group);
4820: foreach my $envkey (%env) {
1.1056.4.1 raeburn 4821: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4822: my $cid = $2.'_'.$3;
4823: if ($1 eq 'gr') {
4824: $group = $4;
4825: $allgroups{$cid}{$group} = $env{$envkey};
4826: } else {
4827: if ($4 eq '') {
4828: $sec = 'none';
4829: } else {
4830: $sec = $4;
4831: }
4832: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4833: }
1.811 albertel 4834: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4835: my $cid = $2.'_'.$3;
4836: if ($4 eq '') {
4837: $sec = 'none';
4838: } else {
4839: $sec = $4;
4840: }
4841: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4842: }
4843: }
4844: if (keys(%allroles) == 0) {
4845: return;
4846: }
4847: foreach my $key (@courses_and_groups) {
4848: my %content = %{$$access_hash{$key}};
4849: my $cnum = $content{'number'};
4850: my $cdom = $content{'domain'};
4851: my $cid = $cdom.'_'.$cnum;
4852: if (!exists($allroles{$cid})) {
4853: next;
4854: }
4855: foreach my $role_id (keys(%{$content{'roles'}})) {
4856: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4857: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4858: my @status = @{$content{'roles'}{$role_id}{'access'}};
4859: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4860: foreach my $role (keys(%{$allroles{$cid}})) {
4861: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4862: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4863: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4864: if (grep/^all$/,@sections) {
4865: return 'ok';
4866: } else {
4867: if (grep/^$sec$/,@sections) {
4868: return 'ok';
4869: }
4870: }
4871: }
4872: }
4873: if (keys(%{$allgroups{$cid}}) == 0) {
4874: if (grep/^none$/,@groups) {
4875: return 'ok';
4876: }
4877: } else {
4878: if (grep/^all$/,@groups) {
4879: return 'ok';
4880: }
4881: foreach my $group (keys(%{$allgroups{$cid}})) {
4882: if (grep/^$group$/,@groups) {
4883: return 'ok';
4884: }
4885: }
4886: }
4887: }
4888: }
4889: }
4890: }
4891: }
4892: if ($guest) {
4893: return $guest;
4894: }
4895: }
4896: }
4897: return;
4898: }
4899:
4900: sub course_group_datechecker {
4901: my ($dates,$now,$status) = @_;
4902: my ($start,$end) = split(/\./,$dates);
4903: if (!$start && !$end) {
4904: return 'ok';
4905: }
4906: if (grep/^active$/,@{$status}) {
4907: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4908: return 'ok';
4909: }
4910: }
4911: if (grep/^previous$/,@{$status}) {
4912: if ($end > $now ) {
4913: return 'ok';
4914: }
4915: }
4916: if (grep/^future$/,@{$status}) {
4917: if ($start > $now) {
4918: return 'ok';
4919: }
4920: }
4921: return;
4922: }
4923:
4924: sub parse_portfolio_url {
4925: my ($url) = @_;
4926:
4927: my ($type,$udom,$unum,$group,$file_name);
4928:
1.823 albertel 4929: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4930: $type = 1;
4931: $udom = $1;
4932: $unum = $2;
4933: $file_name = $3;
1.823 albertel 4934: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4935: $type = 2;
4936: $udom = $1;
4937: $unum = $2;
4938: $group = $3;
4939: $file_name = $3.'/'.$4;
4940: }
4941: if (wantarray) {
4942: return ($type,$udom,$unum,$file_name,$group);
4943: }
4944: return $type;
4945: }
4946:
4947: sub is_portfolio_url {
4948: my ($url) = @_;
4949: return scalar(&parse_portfolio_url($url));
4950: }
4951:
1.798 raeburn 4952: sub is_portfolio_file {
4953: my ($file) = @_;
1.820 raeburn 4954: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4955: return 1;
4956: }
4957: return;
4958: }
4959:
1.976 raeburn 4960: sub usertools_access {
1.985 raeburn 4961: my ($uname,$udom,$tool,$action,$context) = @_;
4962: my ($access,%tools);
4963: if ($context eq '') {
4964: $context = 'tools';
4965: }
4966: if ($context eq 'requestcourses') {
4967: %tools = (
4968: official => 1,
4969: unofficial => 1,
1.1006 raeburn 4970: community => 1,
1.985 raeburn 4971: );
4972: } else {
4973: %tools = (
4974: aboutme => 1,
4975: blog => 1,
4976: portfolio => 1,
4977: );
4978: }
1.976 raeburn 4979: return if (!defined($tools{$tool}));
4980:
4981: if ((!defined($udom)) || (!defined($uname))) {
4982: $udom = $env{'user.domain'};
4983: $uname = $env{'user.name'};
4984: }
4985:
1.978 raeburn 4986: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4987: if ($action ne 'reload') {
1.985 raeburn 4988: if ($context eq 'requestcourses') {
4989: return $env{'environment.canrequest.'.$tool};
4990: } else {
4991: return $env{'environment.availabletools.'.$tool};
4992: }
4993: }
1.976 raeburn 4994: }
4995:
4996: my ($toolstatus,$inststatus);
4997:
1.985 raeburn 4998: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4999: ($action ne 'reload')) {
5000: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5001: $inststatus = $env{'environment.inststatus'};
5002: } else {
1.1025 raeburn 5003: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
1.985 raeburn 5004: $toolstatus = $userenv{$context.'.'.$tool};
1.976 raeburn 5005: $inststatus = $userenv{'inststatus'};
5006: }
5007:
5008: if ($toolstatus ne '') {
5009: if ($toolstatus) {
5010: $access = 1;
5011: } else {
5012: $access = 0;
5013: }
5014: return $access;
5015: }
5016:
5017: my $is_adv = &is_advanced_user($udom,$uname);
5018: my %domdef = &get_domain_defaults($udom);
5019: if (ref($domdef{$tool}) eq 'HASH') {
5020: if ($is_adv) {
5021: if ($domdef{$tool}{'_LC_adv'} ne '') {
5022: if ($domdef{$tool}{'_LC_adv'}) {
5023: $access = 1;
5024: } else {
5025: $access = 0;
5026: }
5027: return $access;
5028: }
5029: }
5030: if ($inststatus ne '') {
5031: my ($hasaccess,$hasnoaccess);
5032: foreach my $affiliation (split(/:/,$inststatus)) {
5033: if ($domdef{$tool}{$affiliation} ne '') {
5034: if ($domdef{$tool}{$affiliation}) {
5035: $hasaccess = 1;
5036: } else {
5037: $hasnoaccess = 1;
5038: }
5039: }
5040: }
5041: if ($hasaccess || $hasnoaccess) {
5042: if ($hasaccess) {
5043: $access = 1;
5044: } elsif ($hasnoaccess) {
5045: $access = 0;
5046: }
5047: return $access;
5048: }
5049: } else {
5050: if ($domdef{$tool}{'default'} ne '') {
5051: if ($domdef{$tool}{'default'}) {
5052: $access = 1;
5053: } elsif ($domdef{$tool}{'default'} == 0) {
5054: $access = 0;
5055: }
5056: return $access;
5057: }
5058: }
5059: } else {
1.985 raeburn 5060: if ($context eq 'tools') {
5061: $access = 1;
5062: } else {
5063: $access = 0;
5064: }
1.976 raeburn 5065: return $access;
5066: }
5067: }
5068:
1.1050 raeburn 5069: sub is_course_owner {
5070: my ($cdom,$cnum,$udom,$uname) = @_;
5071: if (($udom eq '') || ($uname eq '')) {
5072: $udom = $env{'user.domain'};
5073: $uname = $env{'user.name'};
5074: }
5075: unless (($udom eq '') || ($uname eq '')) {
5076: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5077: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5078: return 1;
5079: } else {
5080: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5081: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5082: return 1;
5083: }
5084: }
5085: }
5086: }
5087: return;
5088: }
5089:
1.976 raeburn 5090: sub is_advanced_user {
5091: my ($udom,$uname) = @_;
5092: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5093: my %allroles;
5094: my $is_adv;
5095: foreach my $role (keys(%roleshash)) {
5096: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5097: my $area = '/'.$tdomain.'/'.$trest;
5098: if ($sec ne '') {
5099: $area .= '/'.$sec;
5100: }
5101: if (($area ne '') && ($trole ne '')) {
5102: my $spec=$trole.'.'.$area;
5103: if ($trole =~ /^cr\//) {
5104: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5105: } elsif ($trole ne 'gr') {
5106: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5107: }
5108: }
5109: }
5110: foreach my $role (keys(%allroles)) {
5111: last if ($is_adv);
5112: foreach my $item (split(/:/,$allroles{$role})) {
5113: if ($item ne '') {
5114: my ($privilege,$restrictions)=split(/&/,$item);
5115: if ($privilege eq 'adv') {
5116: $is_adv = 1;
5117: last;
5118: }
5119: }
5120: }
5121: }
5122: return $is_adv;
5123: }
1.798 raeburn 5124:
1.1035 raeburn 5125: sub check_can_request {
1.1036 raeburn 5126: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5127: my $canreq = 0;
5128: my ($types,$typename) = &Apache::loncommon::course_types();
5129: my @options = ('approval','validate','autolimit');
5130: my $optregex = join('|',@options);
5131: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5132: foreach my $type (@{$types}) {
5133: if (&usertools_access($env{'user.name'},
5134: $env{'user.domain'},
5135: $type,undef,'requestcourses')) {
5136: $canreq ++;
1.1036 raeburn 5137: if (ref($request_domains) eq 'HASH') {
5138: push(@{$request_domains->{$type}},$env{'user.domain'});
5139: }
1.1035 raeburn 5140: if ($dom eq $env{'user.domain'}) {
5141: $can_request->{$type} = 1;
5142: }
5143: }
5144: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5145: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5146: if (@curr > 0) {
1.1036 raeburn 5147: foreach my $item (@curr) {
5148: if (ref($request_domains) eq 'HASH') {
5149: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5150: if ($otherdom ne '') {
5151: if (ref($request_domains->{$type}) eq 'ARRAY') {
5152: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5153: push(@{$request_domains->{$type}},$otherdom);
5154: }
5155: } else {
5156: push(@{$request_domains->{$type}},$otherdom);
5157: }
5158: }
5159: }
5160: }
5161: unless($dom eq $env{'user.domain'}) {
5162: $canreq ++;
1.1035 raeburn 5163: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5164: $can_request->{$type} = 1;
5165: }
5166: }
5167: }
5168: }
5169: }
5170: }
5171: return $canreq;
5172: }
5173:
1.341 www 5174: # ---------------------------------------------- Custom access rule evaluation
5175:
5176: sub customaccess {
5177: my ($priv,$uri)=@_;
1.807 albertel 5178: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5179: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5180: $udom = &LONCAPA::clean_domain($udom);
5181: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5182: my $access=0;
1.800 albertel 5183: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5184: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5185: if ($type eq 'user') {
5186: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5187: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5188: if ($tdom) {
5189: if ($tdom ne $env{'user.domain'}) { next; }
5190: }
1.896 albertel 5191: if ($tuname) {
5192: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5193: }
5194: $access=($effect eq 'allow');
5195: last;
5196: }
5197: } else {
5198: if ($role) {
5199: if ($role ne $urole) { next; }
5200: }
5201: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5202: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5203: if ($tdom) {
5204: if ($tdom ne $udom) { next; }
5205: }
5206: if ($tcrs) {
5207: if ($tcrs ne $ucrs) { next; }
5208: }
5209: if ($tsec) {
5210: if ($tsec ne $usec) { next; }
5211: }
5212: $access=($effect eq 'allow');
5213: last;
5214: }
5215: if ($realm eq '' && $role eq '') {
5216: $access=($effect eq 'allow');
5217: }
1.402 bowersj2 5218: }
1.341 www 5219: }
5220: return $access;
5221: }
5222:
1.103 harris41 5223: # ------------------------------------------------- Check for a user privilege
1.12 www 5224:
5225: sub allowed {
1.810 raeburn 5226: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5227: my $ver_orguri=$uri;
1.439 www 5228: $uri=&deversion($uri);
1.152 www 5229: my $orguri=$uri;
1.52 www 5230: $uri=&declutter($uri);
1.809 raeburn 5231:
1.810 raeburn 5232: if ($priv eq 'evb') {
5233: # Evade communication block restrictions for specified role in a course
5234: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5235: return $1;
5236: } else {
5237: return;
5238: }
5239: }
5240:
1.620 albertel 5241: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5242: # Free bre access to adm and meta resources
1.775 albertel 5243: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5244: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5245: && ($priv eq 'bre')) {
1.14 www 5246: return 'F';
1.159 www 5247: }
5248:
1.545 banghart 5249: # Free bre access to user's own portfolio contents
1.714 raeburn 5250: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5251: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5252: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5253: my %setters;
5254: my ($startblock,$endblock) =
5255: &Apache::loncommon::blockcheck(\%setters,'port');
5256: if ($startblock && $endblock) {
5257: return 'B';
5258: } else {
5259: return 'F';
5260: }
1.545 banghart 5261: }
5262:
1.762 raeburn 5263: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5264: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5265: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5266: if (exists($env{'request.course.id'})) {
5267: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5268: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5269: if (($domain eq $cdom) && ($name eq $cnum)) {
5270: my $courseprivid=$env{'request.course.id'};
5271: $courseprivid=~s/\_/\//;
5272: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5273: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5274: return $1;
1.762 raeburn 5275: } else {
5276: if ($env{'request.course.sec'}) {
5277: $courseprivid.='/'.$env{'request.course.sec'};
5278: }
5279: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5280: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5281: return $2;
5282: }
1.714 raeburn 5283: }
5284: }
5285: }
5286: }
5287:
1.159 www 5288: # Free bre to public access
5289:
5290: if ($priv eq 'bre') {
1.238 www 5291: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5292: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5293: return 'F';
5294: }
1.238 www 5295: if ($copyright eq 'priv') {
5296: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5297: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5298: return '';
5299: }
5300: }
5301: if ($copyright eq 'domain') {
5302: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5303: unless (($env{'user.domain'} eq $1) ||
5304: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5305: return '';
5306: }
1.262 matthew 5307: }
1.620 albertel 5308: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5309: # Library role, so allow browsing of resources in this domain.
5310: return 'F';
1.238 www 5311: }
1.341 www 5312: if ($copyright eq 'custom') {
5313: unless (&customaccess($priv,$uri)) { return ''; }
5314: }
1.14 www 5315: }
1.264 matthew 5316: # Domain coordinator is trying to create a course
1.620 albertel 5317: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5318: # uri is the requested domain in this case.
5319: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5320: # a role of dc for the domain in question.
1.620 albertel 5321: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5322: }
1.29 www 5323:
1.52 www 5324: my $thisallowed='';
5325: my $statecond=0;
5326: my $courseprivid='';
5327:
1.1039 raeburn 5328: my $ownaccess;
1.1043 raeburn 5329: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5330: if (($priv eq 'bro') && ($env{'user.author'})) {
5331: if ($uri eq '') {
5332: $ownaccess = 1;
5333: } else {
5334: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5335: my $udom = $env{'user.domain'};
5336: my $uname = $env{'user.name'};
5337: if ($uri =~ m{^\Q$udom\E/?$}) {
5338: $ownaccess = 1;
1.1040 raeburn 5339: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5340: unless ($uri =~ m{\.\./}) {
5341: $ownaccess = 1;
5342: }
5343: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5344: my $now = time;
5345: if ($uri =~ m{^([^/]+)/?$}) {
5346: my $adom = $1;
5347: foreach my $key (keys(%env)) {
1.1042 raeburn 5348: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5349: my ($start,$end) = split('.',$env{$key});
5350: if (($now >= $start) && (!$end || $end < $now)) {
5351: $ownaccess = 1;
5352: last;
5353: }
5354: }
5355: }
5356: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5357: my $adom = $1;
5358: my $aname = $2;
1.1042 raeburn 5359: foreach my $role ('ca','aa') {
5360: if ($env{"user.role.$role./$adom/$aname"}) {
5361: my ($start,$end) =
5362: split('.',$env{"user.role.$role./$adom/$aname"});
5363: if (($now >= $start) && (!$end || $end < $now)) {
5364: $ownaccess = 1;
5365: last;
5366: }
1.1039 raeburn 5367: }
5368: }
5369: }
5370: }
5371: }
5372: }
5373: }
5374:
1.52 www 5375: # Course
5376:
1.620 albertel 5377: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5378: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5379: $thisallowed.=$1;
5380: }
1.52 www 5381: }
1.29 www 5382:
1.52 www 5383: # Domain
5384:
1.620 albertel 5385: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5386: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5387: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5388: $thisallowed.=$1;
5389: }
1.12 www 5390: }
1.52 www 5391:
5392: # Course: uri itself is a course
1.66 www 5393: my $courseuri=$uri;
5394: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5395: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5396:
1.620 albertel 5397: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5398: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5399: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5400: $thisallowed.=$1;
5401: }
1.12 www 5402: }
1.29 www 5403:
1.665 albertel 5404: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5405: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5406: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5407: $thisallowed='';
1.671 raeburn 5408: my ($match)=&is_on_map($uri);
5409: if ($match) {
5410: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5411: =~/\Q$priv\E\&([^\:]*)/) {
5412: $thisallowed.=$1;
5413: }
5414: } else {
1.705 albertel 5415: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5416: if ($refuri) {
5417: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5418: $thisallowed='F';
1.671 raeburn 5419: } else {
5420: $refuri=&declutter($refuri);
5421: my ($match) = &is_on_map($refuri);
5422: if ($match) {
5423: $thisallowed='F';
5424: }
1.669 raeburn 5425: }
1.671 raeburn 5426: }
5427: }
1.314 www 5428: }
1.492 albertel 5429:
1.766 albertel 5430: if ($priv eq 'bre'
5431: && $thisallowed ne 'F'
5432: && $thisallowed ne '2'
5433: && &is_portfolio_url($uri)) {
5434: $thisallowed = &portfolio_access($uri);
5435: }
5436:
1.52 www 5437: # Full access at system, domain or course-wide level? Exit.
1.29 www 5438: if ($thisallowed=~/F/) {
5439: return 'F';
5440: }
5441:
1.52 www 5442: # If this is generating or modifying users, exit with special codes
1.29 www 5443:
1.643 www 5444: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5445: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5446: my ($audom,$auname)=split('/',$uri);
1.643 www 5447: # no author name given, so this just checks on the general right to make a co-author in this domain
5448: unless ($auname) { return $thisallowed; }
5449: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5450: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5451: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5452: ($audom ne $env{'request.role.domain'}))) { return ''; }
5453: }
1.52 www 5454: return $thisallowed;
5455: }
5456: #
1.103 harris41 5457: # Gathered so far: system, domain and course wide privileges
1.52 www 5458: #
5459: # Course: See if uri or referer is an individual resource that is part of
5460: # the course
5461:
1.620 albertel 5462: if ($env{'request.course.id'}) {
1.232 www 5463:
1.620 albertel 5464: $courseprivid=$env{'request.course.id'};
5465: if ($env{'request.course.sec'}) {
5466: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5467: }
5468: $courseprivid=~s/\_/\//;
5469: my $checkreferer=1;
1.232 www 5470: my ($match,$cond)=&is_on_map($uri);
5471: if ($match) {
5472: $statecond=$cond;
1.620 albertel 5473: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5474: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5475: $thisallowed.=$1;
5476: $checkreferer=0;
5477: }
1.29 www 5478: }
1.83 www 5479:
1.148 www 5480: if ($checkreferer) {
1.620 albertel 5481: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5482: unless ($refuri) {
1.800 albertel 5483: foreach my $key (keys(%env)) {
5484: if ($key=~/^httpref\..*\*/) {
5485: my $pattern=$key;
1.156 www 5486: $pattern=~s/^httpref\.\/res\///;
1.148 www 5487: $pattern=~s/\*/\[\^\/\]\+/g;
5488: $pattern=~s/\//\\\//g;
1.152 www 5489: if ($orguri=~/$pattern/) {
1.800 albertel 5490: $refuri=$env{$key};
1.148 www 5491: }
5492: }
1.191 harris41 5493: }
1.148 www 5494: }
1.232 www 5495:
1.148 www 5496: if ($refuri) {
1.152 www 5497: $refuri=&declutter($refuri);
1.232 www 5498: my ($match,$cond)=&is_on_map($refuri);
5499: if ($match) {
5500: my $refstatecond=$cond;
1.620 albertel 5501: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5502: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5503: $thisallowed.=$1;
1.53 www 5504: $uri=$refuri;
5505: $statecond=$refstatecond;
1.52 www 5506: }
5507: }
1.148 www 5508: }
1.29 www 5509: }
1.52 www 5510: }
1.29 www 5511:
1.52 www 5512: #
1.103 harris41 5513: # Gathered now: all privileges that could apply, and condition number
1.52 www 5514: #
5515: #
5516: # Full or no access?
5517: #
1.29 www 5518:
1.52 www 5519: if ($thisallowed=~/F/) {
5520: return 'F';
5521: }
1.29 www 5522:
1.52 www 5523: unless ($thisallowed) {
5524: return '';
5525: }
1.29 www 5526:
1.52 www 5527: # Restrictions exist, deal with them
5528: #
5529: # C:according to course preferences
5530: # R:according to resource settings
5531: # L:unless locked
5532: # X:according to user session state
5533: #
5534:
5535: # Possibly locked functionality, check all courses
1.54 www 5536: # Locks might take effect only after 10 minutes cache expiration for other
5537: # courses, and 2 minutes for current course
1.52 www 5538:
5539: my $envkey;
5540: if ($thisallowed=~/L/) {
1.1000 raeburn 5541: foreach $envkey (keys(%env)) {
1.54 www 5542: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5543: my $courseid=$2;
5544: my $roleid=$1.'.'.$2;
1.92 www 5545: $courseid=~s/^\///;
1.54 www 5546: my $expiretime=600;
1.620 albertel 5547: if ($env{'request.role'} eq $roleid) {
1.54 www 5548: $expiretime=120;
5549: }
5550: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5551: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5552: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5553: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5554: }
1.620 albertel 5555: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5556: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5557: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5558: &log($env{'user.domain'},$env{'user.name'},
5559: $env{'user.home'},
1.57 www 5560: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5561: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5562: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5563: return '';
5564: }
5565: }
1.620 albertel 5566: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5567: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5568: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5569: &log($env{'user.domain'},$env{'user.name'},
5570: $env{'user.home'},
1.57 www 5571: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5572: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5573: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5574: return '';
5575: }
5576: }
5577: }
1.29 www 5578: }
1.52 www 5579: }
5580:
5581: #
5582: # Rest of the restrictions depend on selected course
5583: #
5584:
1.620 albertel 5585: unless ($env{'request.course.id'}) {
1.766 albertel 5586: if ($thisallowed eq 'A') {
5587: return 'A';
1.814 raeburn 5588: } elsif ($thisallowed eq 'B') {
5589: return 'B';
1.766 albertel 5590: } else {
5591: return '1';
5592: }
1.52 www 5593: }
1.29 www 5594:
1.52 www 5595: #
5596: # Now user is definitely in a course
5597: #
1.53 www 5598:
5599:
5600: # Course preferences
5601:
5602: if ($thisallowed=~/C/) {
1.620 albertel 5603: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5604: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5605: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5606: =~/\Q$rolecode\E/) {
1.689 albertel 5607: if ($priv ne 'pch') {
5608: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5609: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5610: $env{'request.course.id'});
5611: }
1.237 www 5612: return '';
5613: }
5614:
1.620 albertel 5615: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5616: =~/\Q$unamedom\E/) {
1.689 albertel 5617: if ($priv ne 'pch') {
5618: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5619: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5620: $env{'request.course.id'});
5621: }
1.54 www 5622: return '';
5623: }
1.53 www 5624: }
5625:
5626: # Resource preferences
5627:
5628: if ($thisallowed=~/R/) {
1.620 albertel 5629: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5630: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5631: if ($priv ne 'pch') {
5632: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5633: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5634: }
5635: return '';
1.54 www 5636: }
1.53 www 5637: }
1.30 www 5638:
1.246 www 5639: # Restricted by state or randomout?
1.30 www 5640:
1.52 www 5641: if ($thisallowed=~/X/) {
1.620 albertel 5642: if ($env{'acc.randomout'}) {
1.579 albertel 5643: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5644: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5645: return '';
5646: }
1.247 www 5647: }
5648: if (&condval($statecond)) {
1.52 www 5649: return '2';
5650: } else {
5651: return '';
5652: }
5653: }
1.30 www 5654:
1.766 albertel 5655: if ($thisallowed eq 'A') {
5656: return 'A';
1.814 raeburn 5657: } elsif ($thisallowed eq 'B') {
5658: return 'B';
1.766 albertel 5659: }
1.52 www 5660: return 'F';
1.232 www 5661: }
5662:
1.710 albertel 5663: sub split_uri_for_cond {
5664: my $uri=&deversion(&declutter(shift));
5665: my @uriparts=split(/\//,$uri);
5666: my $filename=pop(@uriparts);
5667: my $pathname=join('/',@uriparts);
5668: return ($pathname,$filename);
5669: }
1.232 www 5670: # --------------------------------------------------- Is a resource on the map?
5671:
5672: sub is_on_map {
1.710 albertel 5673: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5674: #Trying to find the conditional for the file
1.620 albertel 5675: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5676: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5677: if ($match) {
1.289 bowersj2 5678: return (1,$1);
5679: } else {
1.434 www 5680: return (0,0);
1.289 bowersj2 5681: }
1.12 www 5682: }
5683:
1.427 www 5684: # --------------------------------------------------------- Get symb from alias
5685:
5686: sub get_symb_from_alias {
5687: my $symb=shift;
5688: my ($map,$resid,$url)=&decode_symb($symb);
5689: # Already is a symb
5690: if ($url) { return $symb; }
5691: # Must be an alias
5692: my $aliassymb='';
5693: my %bighash;
1.620 albertel 5694: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5695: &GDBM_READER(),0640)) {
5696: my $rid=$bighash{'mapalias_'.$symb};
5697: if ($rid) {
5698: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5699: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5700: $resid,$bighash{'src_'.$rid});
1.427 www 5701: }
5702: untie %bighash;
5703: }
5704: return $aliassymb;
5705: }
5706:
1.12 www 5707: # ----------------------------------------------------------------- Define Role
5708:
5709: sub definerole {
5710: if (allowed('mcr','/')) {
5711: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5712: foreach my $role (split(':',$sysrole)) {
5713: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5714: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5715: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5716: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5717: return "refused:s:$crole&$cqual";
5718: }
5719: }
1.191 harris41 5720: }
1.800 albertel 5721: foreach my $role (split(':',$domrole)) {
5722: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5723: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5724: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5725: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5726: return "refused:d:$crole&$cqual";
5727: }
5728: }
1.191 harris41 5729: }
1.800 albertel 5730: foreach my $role (split(':',$courole)) {
5731: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5732: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5733: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5734: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5735: return "refused:c:$crole&$cqual";
5736: }
5737: }
1.191 harris41 5738: }
1.620 albertel 5739: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5740: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5741: "rolesdef_$rolename=".
5742: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5743: return reply($command,$env{'user.home'});
1.12 www 5744: } else {
5745: return 'refused';
5746: }
1.105 harris41 5747: }
5748:
5749: # ---------------- Make a metadata query against the network of library servers
5750:
5751: sub metadata_query {
1.244 matthew 5752: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5753: my %rhash;
1.845 albertel 5754: my %libserv = &all_library();
1.244 matthew 5755: my @server_list = (defined($server_array) ? @$server_array
5756: : keys(%libserv) );
5757: for my $server (@server_list) {
1.118 harris41 5758: unless ($custom or $customshow) {
5759: my $reply=&reply("querysend:".&escape($query),$server);
5760: $rhash{$server}=$reply;
5761: }
5762: else {
5763: my $reply=&reply("querysend:".&escape($query).':'.
5764: &escape($custom).':'.&escape($customshow),
5765: $server);
5766: $rhash{$server}=$reply;
5767: }
1.112 harris41 5768: }
1.118 harris41 5769: return \%rhash;
1.240 www 5770: }
5771:
5772: # ----------------------------------------- Send log queries and wait for reply
5773:
5774: sub log_query {
5775: my ($uname,$udom,$query,%filters)=@_;
5776: my $uhome=&homeserver($uname,$udom);
5777: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5778: my $uhost=&hostname($uhome);
1.800 albertel 5779: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5780: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5781: $uhome);
1.479 albertel 5782: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5783: return get_query_reply($queryid);
5784: }
5785:
1.818 raeburn 5786: # -------------------------- Update MySQL table for portfolio file
5787:
5788: sub update_portfolio_table {
1.821 raeburn 5789: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5790: if ($group ne '') {
5791: $file_name =~s /^\Q$group\E//;
5792: }
1.818 raeburn 5793: my $homeserver = &homeserver($uname,$udom);
5794: my $queryid=
1.821 raeburn 5795: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5796: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5797: my $reply = &get_query_reply($queryid);
5798: return $reply;
5799: }
5800:
1.899 raeburn 5801: # -------------------------- Update MySQL allusers table
5802:
5803: sub update_allusers_table {
5804: my ($uname,$udom,$names) = @_;
5805: my $homeserver = &homeserver($uname,$udom);
5806: my $queryid=
5807: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5808: 'lastname='.&escape($names->{'lastname'}).'%%'.
5809: 'firstname='.&escape($names->{'firstname'}).'%%'.
5810: 'middlename='.&escape($names->{'middlename'}).'%%'.
5811: 'generation='.&escape($names->{'generation'}).'%%'.
5812: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5813: 'id='.&escape($names->{'id'}),$homeserver);
5814: my $reply = &get_query_reply($queryid);
5815: return $reply;
5816: }
5817:
1.508 raeburn 5818: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5819:
5820: sub fetch_enrollment_query {
1.511 raeburn 5821: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5822: my $homeserver;
1.547 raeburn 5823: my $maxtries = 1;
1.508 raeburn 5824: if ($context eq 'automated') {
5825: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5826: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5827: } else {
5828: $homeserver = &homeserver($cnum,$dom);
5829: }
1.838 albertel 5830: my $host=&hostname($homeserver);
1.506 raeburn 5831: my $cmd = '';
1.1000 raeburn 5832: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5833: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5834: }
5835: $cmd =~ s/%%$//;
5836: $cmd = &escape($cmd);
5837: my $query = 'fetchenrollment';
1.620 albertel 5838: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5839: unless ($queryid=~/^\Q$host\E\_/) {
5840: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5841: return 'error: '.$queryid;
5842: }
1.506 raeburn 5843: my $reply = &get_query_reply($queryid);
1.547 raeburn 5844: my $tries = 1;
5845: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5846: $reply = &get_query_reply($queryid);
5847: $tries ++;
5848: }
1.526 raeburn 5849: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5850: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5851: } else {
1.901 albertel 5852: my @responses = split(/:/,$reply);
1.515 raeburn 5853: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5854: foreach my $line (@responses) {
5855: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5856: $$replyref{$key} = $value;
5857: }
5858: } else {
1.506 raeburn 5859: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5860: foreach my $line (@responses) {
5861: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5862: $$replyref{$key} = $value;
5863: if ($value > 0) {
1.800 albertel 5864: foreach my $item (@{$$affiliatesref{$key}}) {
5865: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5866: my $destname = $pathname.'/'.$filename;
5867: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5868: if ($xml_classlist =~ /^error/) {
5869: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5870: } else {
1.506 raeburn 5871: if ( open(FILE,">$destname") ) {
5872: print FILE &unescape($xml_classlist);
5873: close(FILE);
1.526 raeburn 5874: } else {
5875: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5876: }
5877: }
5878: }
5879: }
5880: }
5881: }
5882: return 'ok';
5883: }
5884: return 'error';
5885: }
5886:
1.242 www 5887: sub get_query_reply {
5888: my $queryid=shift;
1.240 www 5889: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5890: my $reply='';
5891: for (1..100) {
5892: sleep 2;
5893: if (-e $replyfile.'.end') {
1.448 albertel 5894: if (open(my $fh,$replyfile)) {
1.904 albertel 5895: $reply = join('',<$fh>);
5896: close($fh);
1.240 www 5897: } else { return 'error: reply_file_error'; }
1.242 www 5898: return &unescape($reply);
5899: }
1.240 www 5900: }
1.242 www 5901: return 'timeout:'.$queryid;
1.240 www 5902: }
5903:
5904: sub courselog_query {
1.241 www 5905: #
5906: # possible filters:
5907: # url: url or symb
5908: # username
5909: # domain
5910: # action: view, submit, grade
5911: # start: timestamp
5912: # end: timestamp
5913: #
1.240 www 5914: my (%filters)=@_;
1.620 albertel 5915: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5916: if ($filters{'url'}) {
5917: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5918: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5919: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5920: }
1.620 albertel 5921: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5922: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5923: return &log_query($cname,$cdom,'courselog',%filters);
5924: }
5925:
5926: sub userlog_query {
1.858 raeburn 5927: #
5928: # possible filters:
5929: # action: log check role
5930: # start: timestamp
5931: # end: timestamp
5932: #
1.240 www 5933: my ($uname,$udom,%filters)=@_;
5934: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5935: }
5936:
1.506 raeburn 5937: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5938:
5939: sub auto_run {
1.508 raeburn 5940: my ($cnum,$cdom) = @_;
1.876 raeburn 5941: my $response = 0;
5942: my $settings;
5943: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5944: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5945: $settings = $domconfig{'autoenroll'};
5946: if ($settings->{'run'} eq '1') {
5947: $response = 1;
5948: }
5949: } else {
1.934 raeburn 5950: my $homeserver;
5951: if (&is_course($cdom,$cnum)) {
5952: $homeserver = &homeserver($cnum,$cdom);
5953: } else {
5954: $homeserver = &domain($cdom,'primary');
5955: }
5956: if ($homeserver ne 'no_host') {
5957: $response = &reply('autorun:'.$cdom,$homeserver);
5958: }
1.876 raeburn 5959: }
1.506 raeburn 5960: return $response;
5961: }
1.776 albertel 5962:
1.506 raeburn 5963: sub auto_get_sections {
1.508 raeburn 5964: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 5965: my $homeserver;
5966: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5967: $homeserver = &homeserver($cnum,$cdom);
5968: }
5969: if (!defined($homeserver)) {
5970: if ($cdom =~ /^$match_domain$/) {
5971: $homeserver = &domain($cdom,'primary');
5972: }
5973: }
5974: my @secs;
5975: if (defined($homeserver)) {
5976: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5977: unless ($response eq 'refused') {
5978: @secs = split(/:/,$response);
5979: }
1.506 raeburn 5980: }
5981: return @secs;
5982: }
1.776 albertel 5983:
1.506 raeburn 5984: sub auto_new_course {
1.508 raeburn 5985: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5986: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5987: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5988: return $response;
5989: }
1.776 albertel 5990:
1.506 raeburn 5991: sub auto_validate_courseID {
1.508 raeburn 5992: my ($cnum,$cdom,$inst_course_id) = @_;
5993: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5994: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5995: return $response;
5996: }
1.776 albertel 5997:
1.1007 raeburn 5998: sub auto_validate_instcode {
1.1020 raeburn 5999: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6000: my ($homeserver,$response);
6001: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6002: $homeserver = &homeserver($cnum,$cdom);
6003: }
6004: if (!defined($homeserver)) {
6005: if ($cdom =~ /^$match_domain$/) {
6006: $homeserver = &domain($cdom,'primary');
6007: }
6008: }
1.1056.4.2 raeburn 6009: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6010: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6011: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6012: return ($outcome,$description);
1.1007 raeburn 6013: }
6014:
1.506 raeburn 6015: sub auto_create_password {
1.873 raeburn 6016: my ($cnum,$cdom,$authparam,$udom) = @_;
6017: my ($homeserver,$response);
1.506 raeburn 6018: my $create_passwd = 0;
6019: my $authchk = '';
1.873 raeburn 6020: if ($udom =~ /^$match_domain$/) {
6021: $homeserver = &domain($udom,'primary');
6022: }
6023: if ($homeserver eq '') {
6024: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6025: $homeserver = &homeserver($cnum,$cdom);
6026: }
6027: }
6028: if ($homeserver eq '') {
6029: $authchk = 'nodomain';
1.506 raeburn 6030: } else {
1.873 raeburn 6031: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6032: if ($response eq 'refused') {
6033: $authchk = 'refused';
6034: } else {
1.901 albertel 6035: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6036: }
1.506 raeburn 6037: }
6038: return ($authparam,$create_passwd,$authchk);
6039: }
6040:
1.706 raeburn 6041: sub auto_photo_permission {
6042: my ($cnum,$cdom,$students) = @_;
6043: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6044: my ($outcome,$perm_reqd,$conditions) =
6045: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6046: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6047: return (undef,undef);
6048: }
1.706 raeburn 6049: return ($outcome,$perm_reqd,$conditions);
6050: }
6051:
6052: sub auto_checkphotos {
6053: my ($uname,$udom,$pid) = @_;
6054: my $homeserver = &homeserver($uname,$udom);
6055: my ($result,$resulttype);
6056: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6057: &escape($uname).':'.&escape($pid),
6058: $homeserver));
1.709 albertel 6059: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6060: return (undef,undef);
6061: }
1.706 raeburn 6062: if ($outcome) {
6063: ($result,$resulttype) = split(/:/,$outcome);
6064: }
6065: return ($result,$resulttype);
6066: }
6067:
6068: sub auto_photochoice {
6069: my ($cnum,$cdom) = @_;
6070: my $homeserver = &homeserver($cnum,$cdom);
6071: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6072: &escape($cdom),
6073: $homeserver)));
1.709 albertel 6074: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6075: return (undef,undef);
6076: }
1.706 raeburn 6077: return ($update,$comment);
6078: }
6079:
6080: sub auto_photoupdate {
6081: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6082: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6083: my $host=&hostname($homeserver);
1.706 raeburn 6084: my $cmd = '';
6085: my $maxtries = 1;
1.800 albertel 6086: foreach my $affiliate (keys(%{$affiliatesref})) {
6087: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6088: }
6089: $cmd =~ s/%%$//;
6090: $cmd = &escape($cmd);
6091: my $query = 'institutionalphotos';
6092: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6093: unless ($queryid=~/^\Q$host\E\_/) {
6094: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6095: return 'error: '.$queryid;
6096: }
6097: my $reply = &get_query_reply($queryid);
6098: my $tries = 1;
6099: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6100: $reply = &get_query_reply($queryid);
6101: $tries ++;
6102: }
6103: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6104: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6105: } else {
6106: my @responses = split(/:/,$reply);
6107: my $outcome = shift(@responses);
6108: foreach my $item (@responses) {
6109: my ($key,$value) = split(/=/,$item);
6110: $$photo{$key} = $value;
6111: }
6112: return $outcome;
6113: }
6114: return 'error';
6115: }
6116:
1.521 raeburn 6117: sub auto_instcode_format {
1.793 albertel 6118: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6119: $cat_order) = @_;
1.521 raeburn 6120: my $courses = '';
1.772 raeburn 6121: my @homeservers;
1.521 raeburn 6122: if ($caller eq 'global') {
1.841 albertel 6123: my %servers = &get_servers($codedom,'library');
6124: foreach my $tryserver (keys(%servers)) {
6125: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6126: push(@homeservers,$tryserver);
6127: }
1.584 raeburn 6128: }
1.1022 raeburn 6129: } elsif ($caller eq 'requests') {
6130: if ($codedom =~ /^$match_domain$/) {
6131: my $chome = &domain($codedom,'primary');
6132: unless ($chome eq 'no_host') {
6133: push(@homeservers,$chome);
6134: }
6135: }
1.521 raeburn 6136: } else {
1.772 raeburn 6137: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6138: }
1.793 albertel 6139: foreach my $code (keys(%{$instcodes})) {
6140: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6141: }
6142: chop($courses);
1.772 raeburn 6143: my $ok_response = 0;
6144: my $response;
6145: while (@homeservers > 0 && $ok_response == 0) {
6146: my $server = shift(@homeservers);
6147: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6148: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6149: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6150: split(/:/,$response);
1.772 raeburn 6151: %{$codes} = (%{$codes},&str2hash($codes_str));
6152: push(@{$codetitles},&str2array($codetitles_str));
6153: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6154: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6155: $ok_response = 1;
6156: }
6157: }
6158: if ($ok_response) {
1.521 raeburn 6159: return 'ok';
1.772 raeburn 6160: } else {
6161: return $response;
1.521 raeburn 6162: }
6163: }
6164:
1.792 raeburn 6165: sub auto_instcode_defaults {
6166: my ($domain,$returnhash,$code_order) = @_;
6167: my @homeservers;
1.841 albertel 6168:
6169: my %servers = &get_servers($domain,'library');
6170: foreach my $tryserver (keys(%servers)) {
6171: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6172: push(@homeservers,$tryserver);
6173: }
1.792 raeburn 6174: }
1.841 albertel 6175:
1.792 raeburn 6176: my $response;
1.841 albertel 6177: foreach my $server (@homeservers) {
1.792 raeburn 6178: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6179: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6180:
6181: foreach my $pair (split(/\&/,$response)) {
6182: my ($name,$value)=split(/\=/,$pair);
6183: if ($name eq 'code_order') {
6184: @{$code_order} = split(/\&/,&unescape($value));
6185: } else {
6186: $returnhash->{&unescape($name)}=&unescape($value);
6187: }
6188: }
6189: return 'ok';
1.792 raeburn 6190: }
1.841 albertel 6191:
6192: return $response;
1.1003 raeburn 6193: }
6194:
6195: sub auto_possible_instcodes {
1.1007 raeburn 6196: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6197: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6198: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6199: return;
6200: }
1.1003 raeburn 6201: my (@homeservers,$uhome);
6202: if (defined(&domain($domain,'primary'))) {
6203: $uhome=&domain($domain,'primary');
6204: push(@homeservers,&domain($domain,'primary'));
6205: } else {
6206: my %servers = &get_servers($domain,'library');
6207: foreach my $tryserver (keys(%servers)) {
6208: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6209: push(@homeservers,$tryserver);
6210: }
6211: }
6212: }
6213: my $response;
6214: foreach my $server (@homeservers) {
6215: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6216: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6217: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6218: split(':',$response);
6219: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6220: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6221: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6222: my ($name,$value)=split('=',$item);
6223: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6224: }
6225: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6226: my ($name,$value)=split('=',$item);
6227: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6228: }
6229: return 'ok';
6230: }
6231: return $response;
6232: }
1.792 raeburn 6233:
1.1010 raeburn 6234: sub auto_courserequest_checks {
6235: my ($dom) = @_;
1.1020 raeburn 6236: my ($homeserver,%validations);
6237: if ($dom =~ /^$match_domain$/) {
6238: $homeserver = &domain($dom,'primary');
6239: }
6240: unless ($homeserver eq 'no_host') {
6241: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6242: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6243: my @items = split(/&/,$response);
6244: foreach my $item (@items) {
6245: my ($key,$value) = split('=',$item);
6246: $validations{&unescape($key)} = &thaw_unescape($value);
6247: }
6248: }
6249: }
1.1010 raeburn 6250: return %validations;
6251: }
6252:
1.1020 raeburn 6253: sub auto_courserequest_validation {
6254: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6255: my ($homeserver,$response);
6256: if ($dom =~ /^$match_domain$/) {
6257: $homeserver = &domain($dom,'primary');
6258: }
6259: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6260:
1.1020 raeburn 6261: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6262: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6263: ':'.&escape($instcode).':'.&escape($instseclist),
6264: $homeserver));
6265: }
6266: return $response;
6267: }
6268:
1.777 albertel 6269: sub auto_validate_class_sec {
1.918 raeburn 6270: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6271: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6272: my $ownerlist;
6273: if (ref($owners) eq 'ARRAY') {
6274: $ownerlist = join(',',@{$owners});
6275: } else {
6276: $ownerlist = $owners;
6277: }
1.773 raeburn 6278: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6279: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6280: return $response;
6281: }
6282:
1.679 raeburn 6283: # ------------------------------------------------------- Course Group routines
6284:
6285: sub get_coursegroups {
1.809 raeburn 6286: my ($cdom,$cnum,$group,$namespace) = @_;
6287: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6288: }
6289:
1.679 raeburn 6290: sub modify_coursegroup {
6291: my ($cdom,$cnum,$groupsettings) = @_;
6292: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6293: }
6294:
1.809 raeburn 6295: sub toggle_coursegroup_status {
6296: my ($cdom,$cnum,$group,$action) = @_;
6297: my ($from_namespace,$to_namespace);
6298: if ($action eq 'delete') {
6299: $from_namespace = 'coursegroups';
6300: $to_namespace = 'deleted_groups';
6301: } else {
6302: $from_namespace = 'deleted_groups';
6303: $to_namespace = 'coursegroups';
6304: }
6305: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6306: if (my $tmp = &error(%curr_group)) {
6307: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6308: return ('read error',$tmp);
6309: } else {
6310: my %savedsettings = %curr_group;
1.809 raeburn 6311: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6312: my $deloutcome;
6313: if ($result eq 'ok') {
1.809 raeburn 6314: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6315: } else {
6316: return ('write error',$result);
6317: }
6318: if ($deloutcome eq 'ok') {
6319: return 'ok';
6320: } else {
6321: return ('delete error',$deloutcome);
6322: }
6323: }
6324: }
6325:
1.679 raeburn 6326: sub modify_group_roles {
1.957 raeburn 6327: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6328: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6329: my $role = 'gr/'.&escape($userprivs);
6330: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6331: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6332: if ($result eq 'ok') {
6333: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6334: }
1.679 raeburn 6335: return $result;
6336: }
6337:
6338: sub modify_coursegroup_membership {
6339: my ($cdom,$cnum,$membership) = @_;
6340: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6341: return $result;
6342: }
6343:
1.682 raeburn 6344: sub get_active_groups {
6345: my ($udom,$uname,$cdom,$cnum) = @_;
6346: my $now = time;
6347: my %groups = ();
6348: foreach my $key (keys(%env)) {
1.811 albertel 6349: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6350: my ($start,$end) = split(/\./,$env{$key});
6351: if (($end!=0) && ($end<$now)) { next; }
6352: if (($start!=0) && ($start>$now)) { next; }
6353: if ($1 eq $cdom && $2 eq $cnum) {
6354: $groups{$3} = $env{$key} ;
6355: }
6356: }
6357: }
6358: return %groups;
6359: }
6360:
1.683 raeburn 6361: sub get_group_membership {
6362: my ($cdom,$cnum,$group) = @_;
6363: return(&dump('groupmembership',$cdom,$cnum,$group));
6364: }
6365:
6366: sub get_users_groups {
6367: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6368: my @usersgroups;
1.683 raeburn 6369: my $cachetime=1800;
6370:
6371: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6372: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6373: if (defined($cached)) {
1.734 albertel 6374: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6375: } else {
6376: $grouplist = '';
1.816 raeburn 6377: my $courseurl = &courseid_to_courseurl($courseid);
6378: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 6379: my $access_end = $env{'course.'.$courseid.
6380: '.default_enrollment_end_date'};
6381: my $now = time;
6382: foreach my $key (keys(%roleshash)) {
6383: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6384: my $group = $1;
6385: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6386: my $start = $2;
6387: my $end = $1;
6388: if ($start == -1) { next; } # deleted from group
6389: if (($start!=0) && ($start>$now)) { next; }
6390: if (($end!=0) && ($end<$now)) {
6391: if ($access_end && $access_end < $now) {
6392: if ($access_end - $end < 86400) {
6393: push(@usersgroups,$group);
1.733 raeburn 6394: }
6395: }
1.817 raeburn 6396: next;
1.733 raeburn 6397: }
1.817 raeburn 6398: push(@usersgroups,$group);
1.683 raeburn 6399: }
6400: }
6401: }
1.817 raeburn 6402: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6403: $grouplist = join(':',@usersgroups);
6404: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6405: }
1.733 raeburn 6406: return @usersgroups;
1.683 raeburn 6407: }
6408:
6409: sub devalidate_getgroups_cache {
6410: my ($udom,$uname,$cdom,$cnum)=@_;
6411: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6412:
1.683 raeburn 6413: my $hashid="$udom:$uname:$courseid";
6414: &devalidate_cache_new('getgroups',$hashid);
6415: }
6416:
1.12 www 6417: # ------------------------------------------------------------------ Plain Text
6418:
6419: sub plaintext {
1.988 raeburn 6420: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6421: if ($short =~ m{^cr/}) {
1.758 albertel 6422: return (split('/',$short))[-1];
6423: }
1.742 raeburn 6424: if (!defined($cid)) {
6425: $cid = $env{'request.course.id'};
6426: }
6427: my %rolenames = (
1.1008 raeburn 6428: Course => 'std',
6429: Community => 'alt1',
1.742 raeburn 6430: );
1.1037 raeburn 6431: if ($cid ne '') {
6432: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6433: unless ($forcedefault) {
6434: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6435: &Apache::lonlocal::mt_escape(\$roletext);
6436: return &Apache::lonlocal::mt($roletext);
6437: }
6438: }
6439: }
6440: if ((defined($type)) && (defined($rolenames{$type})) &&
6441: (defined($rolenames{$type})) &&
6442: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6443: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6444: } elsif ($cid ne '') {
6445: my $crstype = $env{'course.'.$cid.'.type'};
6446: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6447: (defined($prp{$short}{$rolenames{$crstype}}))) {
6448: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6449: }
1.742 raeburn 6450: }
1.1037 raeburn 6451: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6452: }
6453:
6454: # ----------------------------------------------------------------- Assign Role
6455:
6456: sub assignrole {
1.957 raeburn 6457: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6458: $context)=@_;
1.21 www 6459: my $mrole;
6460: if ($role =~ /^cr\//) {
1.393 www 6461: my $cwosec=$url;
1.811 albertel 6462: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6463: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6464: my $refused = 1;
6465: if ($context eq 'requestcourses') {
6466: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6467: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6468: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6469: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6470: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6471: if ($crsenv{'internal.courseowner'} eq
6472: $env{'user.name'}.':'.$env{'user.domain'}) {
6473: $refused = '';
6474: }
6475: }
6476: }
6477: }
6478: }
6479: if ($refused) {
6480: &logthis('Refused custom assignrole: '.
6481: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6482: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6483: return 'refused';
6484: }
1.104 www 6485: }
1.21 www 6486: $mrole='cr';
1.678 raeburn 6487: } elsif ($role =~ /^gr\//) {
6488: my $cwogrp=$url;
1.811 albertel 6489: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6490: unless (&allowed('mdg',$cwogrp)) {
6491: &logthis('Refused group assignrole: '.
6492: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6493: $env{'user.name'}.' at '.$env{'user.domain'});
6494: return 'refused';
6495: }
6496: $mrole='gr';
1.21 www 6497: } else {
1.82 www 6498: my $cwosec=$url;
1.811 albertel 6499: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6500: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6501: my $refused;
6502: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6503: if (!(&allowed('c'.$role,$url))) {
6504: $refused = 1;
6505: }
6506: } else {
6507: $refused = 1;
6508: }
1.947 raeburn 6509: if ($refused) {
1.1045 raeburn 6510: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6511: if (!$selfenroll && $context eq 'course') {
6512: my %crsenv;
6513: if ($role eq 'cc' || $role eq 'co') {
6514: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6515: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6516: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6517: if ($crsenv{'internal.courseowner'} eq
6518: $env{'user.name'}.':'.$env{'user.domain'}) {
6519: $refused = '';
6520: }
6521: }
6522: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6523: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6524: if ($crsenv{'internal.courseowner'} eq
6525: $env{'user.name'}.':'.$env{'user.domain'}) {
6526: $refused = '';
6527: }
6528: }
6529: }
6530: }
6531: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6532: $refused = '';
1.1017 raeburn 6533: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6534: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6535: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6536: my $wrongcc;
6537: if ($cnum =~ /^$match_community$/) {
6538: $wrongcc = 1 if ($role eq 'cc');
6539: } else {
6540: $wrongcc = 1 if ($role eq 'co');
6541: }
6542: unless ($wrongcc) {
6543: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6544: if ($crsenv{'internal.courseowner'} eq
6545: $env{'user.name'}.':'.$env{'user.domain'}) {
6546: $refused = '';
6547: }
1.1017 raeburn 6548: }
6549: }
6550: }
6551: if ($refused) {
1.947 raeburn 6552: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6553: ' '.$role.' '.$end.' '.$start.' by '.
6554: $env{'user.name'}.' at '.$env{'user.domain'});
6555: return 'refused';
6556: }
1.932 raeburn 6557: }
1.104 www 6558: }
1.21 www 6559: $mrole=$role;
6560: }
1.620 albertel 6561: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6562: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6563: if ($end) { $command.='_'.$end; }
1.21 www 6564: if ($start) {
6565: if ($end) {
1.81 www 6566: $command.='_'.$start;
1.21 www 6567: } else {
1.81 www 6568: $command.='_0_'.$start;
1.21 www 6569: }
6570: }
1.739 raeburn 6571: my $origstart = $start;
6572: my $origend = $end;
1.957 raeburn 6573: my $delflag;
1.357 www 6574: # actually delete
6575: if ($deleteflag) {
1.373 www 6576: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6577: # modify command to delete the role
1.620 albertel 6578: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6579: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6580: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6581: # set start and finish to negative values for userrolelog
6582: $start=-1;
6583: $end=-1;
1.957 raeburn 6584: $delflag = 1;
1.357 www 6585: }
6586: }
6587: # send command
1.349 www 6588: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6589: # log new user role if status is ok
1.349 www 6590: if ($answer eq 'ok') {
1.663 raeburn 6591: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6592: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6593: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6594: unless ($role =~ /^gr/) {
6595: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6596: $origstart,$selfenroll,$context);
1.739 raeburn 6597: }
1.1053 raeburn 6598: if ($role eq 'cc') {
6599: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6600: }
1.349 www 6601: }
6602: return $answer;
1.169 harris41 6603: }
6604:
1.1053 raeburn 6605: sub autoupdate_coowners {
6606: my ($url,$end,$start,$uname,$udom) = @_;
6607: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6608: if (($cdom ne '') && ($cnum ne '')) {
6609: my $now = time;
6610: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6611: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6612: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6613: my $instcode = $coursehash{'internal.coursecode'};
6614: if ($instcode ne '') {
1.1056 raeburn 6615: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6616: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6617: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6618: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6619: if ($result eq 'valid') {
6620: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6621: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6622: push(@newcoowners,$coowner);
6623: }
6624: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6625: push(@newcoowners,$uname.':'.$udom);
6626: }
6627: @newcoowners = sort(@newcoowners);
6628: } else {
6629: push(@newcoowners,$uname.':'.$udom);
6630: }
6631: } else {
6632: if ($coursehash{'internal.co-owners'}) {
6633: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6634: unless ($coowner eq $uname.':'.$udom) {
6635: push(@newcoowners,$coowner);
6636: }
6637: }
6638: unless (@newcoowners > 0) {
6639: $delcoowners = 1;
6640: $coowners = '';
6641: }
6642: }
6643: }
6644: if (@newcoowners || $delcoowners) {
6645: &store_coowners($cdom,$cnum,$coursehash{'home'},
6646: $delcoowners,@newcoowners);
6647: }
6648: }
6649: }
6650: }
6651: }
6652: }
6653: }
6654:
6655: sub store_coowners {
6656: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6657: my $cid = $cdom.'_'.$cnum;
6658: my ($coowners,$delresult,$putresult);
6659: if (@newcoowners) {
6660: $coowners = join(',',@newcoowners);
6661: my %coownershash = (
6662: 'internal.co-owners' => $coowners,
6663: );
6664: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6665: if ($putresult eq 'ok') {
6666: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6667: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6668: }
6669: }
6670: }
6671: if ($delcoowners) {
6672: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6673: if ($delresult eq 'ok') {
6674: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6675: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6676: }
6677: }
6678: }
6679: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6680: my %crsinfo =
6681: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6682: if (ref($crsinfo{$cid}) eq 'HASH') {
6683: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6684: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6685: }
6686: }
6687: }
6688:
1.169 harris41 6689: # -------------------------------------------------- Modify user authentication
1.197 www 6690: # Overrides without validation
6691:
1.169 harris41 6692: sub modifyuserauth {
6693: my ($udom,$uname,$umode,$upass)=@_;
6694: my $uhome=&homeserver($uname,$udom);
1.197 www 6695: unless (&allowed('mau',$udom)) { return 'refused'; }
6696: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6697: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6698: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6699: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6700: &escape($upass),$uhome);
1.620 albertel 6701: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6702: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6703: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6704: &log($udom,,$uname,$uhome,
1.620 albertel 6705: 'Authentication changed by '.$env{'user.domain'}.', '.
6706: $env{'user.name'}.', '.$umode.
1.197 www 6707: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6708: unless ($reply eq 'ok') {
1.197 www 6709: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6710: return 'error: '.$reply;
6711: }
1.170 harris41 6712: return 'ok';
1.80 www 6713: }
6714:
1.81 www 6715: # --------------------------------------------------------------- Modify a user
1.80 www 6716:
1.81 www 6717: sub modifyuser {
1.206 matthew 6718: my ($udom, $uname, $uid,
6719: $umode, $upass, $first,
6720: $middle, $last, $gene,
1.1056.4.1 raeburn 6721: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6722: $udom= &LONCAPA::clean_domain($udom);
6723: $uname=&LONCAPA::clean_username($uname);
1.1056.4.1 raeburn 6724: my $showcandelete = 'none';
6725: if (ref($candelete) eq 'ARRAY') {
6726: if (@{$candelete} > 0) {
6727: $showcandelete = join(', ',@{$candelete});
6728: }
6729: }
1.81 www 6730: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6731: $umode.', '.$first.', '.$middle.', '.
1.1056.4.1 raeburn 6732: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6733: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6734: ' desiredhome not specified').
1.620 albertel 6735: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6736: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6737: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 6738: # ----------------------------------------------------------------- Create User
1.406 albertel 6739: if (($uhome eq 'no_host') &&
6740: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6741: my $unhome='';
1.844 albertel 6742: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6743: $unhome = $desiredhome;
1.620 albertel 6744: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6745: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6746: } else { # load balancing routine for determining $unhome
1.81 www 6747: my $loadm=10000000;
1.841 albertel 6748: my %servers = &get_servers($udom,'library');
6749: foreach my $tryserver (keys(%servers)) {
6750: my $answer=reply('load',$tryserver);
6751: if (($answer=~/\d+/) && ($answer<$loadm)) {
6752: $loadm=$answer;
6753: $unhome=$tryserver;
6754: }
1.80 www 6755: }
6756: }
6757: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6758: return 'error: unable to find a home server for '.$uname.
6759: ' in domain '.$udom;
1.80 www 6760: }
6761: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6762: &escape($upass),$unhome);
6763: unless ($reply eq 'ok') {
6764: return 'error: '.$reply;
6765: }
1.230 stredwic 6766: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6767: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6768: return 'error: unable verify users home machine.';
1.80 www 6769: }
1.209 matthew 6770: } # End of creation of new user
1.80 www 6771: # ---------------------------------------------------------------------- Add ID
6772: if ($uid) {
6773: $uid=~tr/A-Z/a-z/;
6774: my %uidhash=&idrget($udom,$uname);
1.196 www 6775: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6776: && (!$forceid)) {
1.80 www 6777: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6778: return 'error: user id "'.$uid.'" does not match '.
6779: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6780: }
6781: } else {
6782: &idput($udom,($uname => $uid));
6783: }
6784: }
6785: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6786: my @tmp=&get('environment',
1.899 raeburn 6787: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6788: 'permanentemail','inststatus'],
1.134 albertel 6789: $udom,$uname);
1.313 matthew 6790: my %names;
6791: if ($tmp[0] =~ m/^error:.*/) {
6792: %names=();
6793: } else {
6794: %names = @tmp;
6795: }
1.1056.4.1 raeburn 6796: # If name, email and/or uid are blank (e.g., because an uploaded file
6797: # of users did not contain them), do not overwrite existing values
6798: # unless field is in $candelete array ref.
6799: #
6800:
6801: my @fields = ('firstname','middlename','lastname','generation',
6802: 'permanentemail','id');
6803: my %newvalues;
6804: if (ref($candelete) eq 'ARRAY') {
6805: foreach my $field (@fields) {
6806: if (grep(/^\Q$field\E$/,@{$candelete})) {
6807: if ($field eq 'firstname') {
6808: $names{$field} = $first;
6809: } elsif ($field eq 'middlename') {
6810: $names{$field} = $middle;
6811: } elsif ($field eq 'lastname') {
6812: $names{$field} = $last;
6813: } elsif ($field eq 'generation') {
6814: $names{$field} = $gene;
6815: } elsif ($field eq 'permanentemail') {
6816: $names{$field} = $email;
6817: } elsif ($field eq 'id') {
6818: $names{$field} = $uid;
6819: }
6820: }
6821: }
6822: }
1.388 www 6823: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6824: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6825: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6826: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6827: if ($email) {
6828: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6829: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6830: }
1.899 raeburn 6831: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6832: if (defined($inststatus)) {
6833: $names{'inststatus'} = '';
6834: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6835: if (ref($usertypes) eq 'HASH') {
6836: my @okstatuses;
6837: foreach my $item (split(/:/,$inststatus)) {
6838: if (defined($usertypes->{$item})) {
6839: push(@okstatuses,$item);
6840: }
6841: }
6842: if (@okstatuses) {
6843: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6844: }
6845: }
6846: }
1.134 albertel 6847: my $reply = &put('environment', \%names, $udom,$uname);
6848: if ($reply ne 'ok') { return 'error: '.$reply; }
1.899 raeburn 6849: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680 www 6850: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963 raeburn 6851: my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
6852: $umode.', '.$first.', '.$middle.', '.
6853: $last.', '.$gene.', '.$email.', '.$inststatus;
6854: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6855: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6856: } else {
6857: $logmsg .= ' during self creation';
6858: }
6859: &logthis($logmsg);
1.134 albertel 6860: return 'ok';
1.80 www 6861: }
6862:
1.81 www 6863: # -------------------------------------------------------------- Modify student
1.80 www 6864:
1.81 www 6865: sub modifystudent {
6866: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6867: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6868: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6869: if (!$cid) {
1.620 albertel 6870: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6871: return 'not_in_class';
6872: }
1.80 www 6873: }
6874: # --------------------------------------------------------------- Make the user
1.81 www 6875: my $reply=&modifyuser
1.209 matthew 6876: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6877: $desiredhome,$email,$inststatus);
1.80 www 6878: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6879: # This will cause &modify_student_enrollment to get the uid from the
6880: # students environment
6881: $uid = undef if (!$forceid);
1.455 albertel 6882: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 6883: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 6884: return $reply;
6885: }
6886:
6887: sub modify_student_enrollment {
1.957 raeburn 6888: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 6889: my ($cdom,$cnum,$chome);
6890: if (!$cid) {
1.620 albertel 6891: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6892: return 'not_in_class';
6893: }
1.620 albertel 6894: $cdom=$env{'course.'.$cid.'.domain'};
6895: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 6896: } else {
6897: ($cdom,$cnum)=split(/_/,$cid);
6898: }
1.620 albertel 6899: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 6900: if (!$chome) {
1.457 raeburn 6901: $chome=&homeserver($cnum,$cdom);
1.297 matthew 6902: }
1.455 albertel 6903: if (!$chome) { return 'unknown_course'; }
1.297 matthew 6904: # Make sure the user exists
1.81 www 6905: my $uhome=&homeserver($uname,$udom);
6906: if (($uhome eq '') || ($uhome eq 'no_host')) {
6907: return 'error: no such user';
6908: }
1.297 matthew 6909: # Get student data if we were not given enough information
6910: if (!defined($first) || $first eq '' ||
6911: !defined($last) || $last eq '' ||
6912: !defined($uid) || $uid eq '' ||
6913: !defined($middle) || $middle eq '' ||
6914: !defined($gene) || $gene eq '') {
1.294 matthew 6915: # They did not supply us with enough data to enroll the student, so
6916: # we need to pick up more information.
1.297 matthew 6917: my %tmp = &get('environment',
1.294 matthew 6918: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 6919: ,$udom,$uname);
6920:
1.800 albertel 6921: #foreach my $key (keys(%tmp)) {
6922: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 6923: #}
1.294 matthew 6924: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6925: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6926: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 6927: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 6928: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6929: }
1.556 albertel 6930: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 6931: my $reply=cput('classlist',
6932: {"$uname:$udom" =>
1.515 raeburn 6933: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 6934: $cdom,$cnum);
1.81 www 6935: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6936: return 'error: '.$reply;
1.652 albertel 6937: } else {
6938: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 6939: }
1.297 matthew 6940: # Add student role to user
1.83 www 6941: my $uurl='/'.$cid;
1.81 www 6942: $uurl=~s/\_/\//g;
6943: if ($usec) {
6944: $uurl.='/'.$usec;
6945: }
1.957 raeburn 6946: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 6947: }
6948:
1.556 albertel 6949: sub format_name {
6950: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6951: my $name;
6952: if ($first ne 'lastname') {
6953: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6954: } else {
6955: if ($lastname=~/\S/) {
6956: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6957: $name=~s/\s+,/,/;
6958: } else {
6959: $name.= $firstname.' '.$middlename.' '.$generation;
6960: }
6961: }
6962: $name=~s/^\s+//;
6963: $name=~s/\s+$//;
6964: $name=~s/\s+/ /g;
6965: return $name;
6966: }
6967:
1.84 www 6968: # ------------------------------------------------- Write to course preferences
6969:
6970: sub writecoursepref {
6971: my ($courseid,%prefs)=@_;
6972: $courseid=~s/^\///;
6973: $courseid=~s/\_/\//g;
6974: my ($cdomain,$cnum)=split(/\//,$courseid);
6975: my $chome=homeserver($cnum,$cdomain);
6976: if (($chome eq '') || ($chome eq 'no_host')) {
6977: return 'error: no such course';
6978: }
6979: my $cstring='';
1.800 albertel 6980: foreach my $pref (keys(%prefs)) {
6981: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 6982: }
1.84 www 6983: $cstring=~s/\&$//;
6984: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6985: }
6986:
6987: # ---------------------------------------------------------- Make/modify course
6988:
6989: sub createcourse {
1.741 raeburn 6990: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 6991: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 6992: $url=&declutter($url);
6993: my $cid='';
1.1028 raeburn 6994: if ($context eq 'requestcourses') {
6995: my $can_create = 0;
6996: my ($ownername,$ownerdom) = split(':',$course_owner);
6997: if ($udom eq $ownerdom) {
6998: if (&usertools_access($ownername,$ownerdom,$category,undef,
6999: $context)) {
7000: $can_create = 1;
7001: }
7002: } else {
7003: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7004: $category);
7005: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7006: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7007: if (@curr > 0) {
7008: my @options = qw(approval validate autolimit);
7009: my $optregex = join('|',@options);
7010: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7011: $can_create = 1;
7012: }
7013: }
7014: }
7015: }
7016: if ($can_create) {
7017: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7018: unless (&allowed('ccc',$udom)) {
7019: return 'refused';
7020: }
1.1017 raeburn 7021: }
7022: } else {
7023: return 'refused';
7024: }
1.1028 raeburn 7025: } elsif (!&allowed('ccc',$udom)) {
7026: return 'refused';
1.84 www 7027: }
1.1011 raeburn 7028: # --------------------------------------------------------------- Get Unique ID
7029: my $uname;
7030: if ($cnum =~ /^$match_courseid$/) {
7031: my $chome=&homeserver($cnum,$udom,'true');
7032: if (($chome eq '') || ($chome eq 'no_host')) {
7033: $uname = $cnum;
7034: } else {
1.1038 raeburn 7035: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7036: }
7037: } else {
1.1038 raeburn 7038: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7039: }
7040: return $uname if ($uname =~ /^error/);
7041: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7042: if (!defined($course_server)) {
7043: if (defined(&domain($udom,'primary'))) {
7044: $course_server = &domain($udom,'primary');
7045: } else {
7046: $course_server = $env{'user.home'};
7047: }
7048: }
7049: my %host_servers =
7050: &Apache::lonnet::get_servers($udom,'library');
7051: unless ($host_servers{$course_server}) {
7052: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7053: }
1.84 www 7054: # ------------------------------------------------------------- Make the course
7055: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7056: $course_server);
1.84 www 7057: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7058: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7059: if (($uhome eq '') || ($uhome eq 'no_host')) {
7060: return 'error: no such course';
7061: }
1.271 www 7062: # ----------------------------------------------------------------- Course made
1.516 raeburn 7063: # log existence
1.1029 raeburn 7064: my $now = time;
1.918 raeburn 7065: my $newcourse = {
7066: $udom.'_'.$uname => {
1.921 raeburn 7067: description => $description,
7068: inst_code => $inst_code,
7069: owner => $course_owner,
7070: type => $crstype,
1.1029 raeburn 7071: creator => $env{'user.name'}.':'.
7072: $env{'user.domain'},
7073: created => $now,
7074: context => $context,
1.918 raeburn 7075: },
7076: };
1.921 raeburn 7077: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7078: # set toplevel url
1.271 www 7079: my $topurl=$url;
7080: unless ($nonstandard) {
7081: # ------------------------------------------ For standard courses, make top url
7082: my $mapurl=&clutter($url);
1.278 www 7083: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7084: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7085: <map>
7086: <resource id="1" type="start"></resource>
7087: <resource id="2" src="$mapurl"></resource>
7088: <resource id="3" type="finish"></resource>
7089: <link index="1" from="1" to="2"></link>
7090: <link index="2" from="2" to="3"></link>
7091: </map>
7092: ENDINITMAP
7093: $topurl=&declutter(
1.638 albertel 7094: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7095: );
7096: }
7097: # ----------------------------------------------------------- Write preferences
1.84 www 7098: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7099: ('description' => $description,
7100: 'url' => $topurl,
7101: 'internal.creator' => $env{'user.name'}.':'.
7102: $env{'user.domain'},
7103: 'internal.created' => $now,
7104: 'internal.creationcontext' => $context)
7105: );
1.84 www 7106: return '/'.$udom.'/'.$uname;
7107: }
7108:
1.1011 raeburn 7109: # ------------------------------------------------------------------- Create ID
7110: sub generate_coursenum {
1.1038 raeburn 7111: my ($udom,$crstype) = @_;
1.1011 raeburn 7112: my $domdesc = &domain($udom);
7113: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7114: my $first;
7115: if ($crstype eq 'Community') {
7116: $first = '0';
7117: } else {
7118: $first = int(1+rand(9));
7119: }
7120: my $uname=$first.
1.1011 raeburn 7121: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7122: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7123: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7124: # ----------------------------------------------- Make sure that does not exist
7125: my $uhome=&homeserver($uname,$udom,'true');
7126: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7127: if ($crstype eq 'Community') {
7128: $first = '0';
7129: } else {
7130: $first = int(1+rand(9));
7131: }
7132: $uname=$first.
1.1011 raeburn 7133: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7134: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7135: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7136: $uhome=&homeserver($uname,$udom,'true');
7137: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7138: return 'error: unable to generate unique course-ID';
7139: }
7140: }
7141: return $uname;
7142: }
7143:
1.813 albertel 7144: sub is_course {
7145: my ($cdom,$cnum) = @_;
7146: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7147: undef,'.');
1.813 albertel 7148: if (exists($courses{$cdom.'_'.$cnum})) {
7149: return 1;
7150: }
7151: return 0;
7152: }
7153:
1.1015 raeburn 7154: sub store_userdata {
7155: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7156: my $result;
1.1016 raeburn 7157: if ($datakey ne '') {
1.1013 raeburn 7158: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7159: if ($udom eq '' || $uname eq '') {
7160: $udom = $env{'user.domain'};
7161: $uname = $env{'user.name'};
7162: }
7163: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7164: if (($uhome eq '') || ($uhome eq 'no_host')) {
7165: $result = 'error: no_host';
7166: } else {
7167: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7168: $storehash->{'host'} = $perlvar{'lonHostID'};
7169:
7170: my $namevalue='';
7171: foreach my $key (keys(%{$storehash})) {
7172: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7173: }
7174: $namevalue=~s/\&$//;
7175: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 raeburn 7176: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 7177: }
7178: } else {
7179: $result = 'error: data to store was not a hash reference';
7180: }
7181: } else {
7182: $result= 'error: invalid requestkey';
7183: }
7184: return $result;
7185: }
7186:
1.21 www 7187: # ---------------------------------------------------------- Assign Custom Role
7188:
7189: sub assigncustomrole {
1.957 raeburn 7190: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7191: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7192: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7193: }
7194:
7195: # ----------------------------------------------------------------- Revoke Role
7196:
7197: sub revokerole {
1.957 raeburn 7198: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7199: my $now=time;
1.965 raeburn 7200: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7201: }
7202:
7203: # ---------------------------------------------------------- Revoke Custom Role
7204:
7205: sub revokecustomrole {
1.957 raeburn 7206: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7207: my $now=time;
1.357 www 7208: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7209: $deleteflag,$selfenroll,$context);
1.17 www 7210: }
7211:
1.533 banghart 7212: # ------------------------------------------------------------ Disk usage
1.535 albertel 7213: sub diskusage {
1.955 raeburn 7214: my ($udom,$uname,$directorypath,$getpropath)=@_;
7215: $directorypath =~ s/\/$//;
7216: my $listing=&reply('du2:'.&escape($directorypath).':'
7217: .&escape($getpropath).':'.&escape($uname).':'
7218: .&escape($udom),homeserver($uname,$udom));
7219: if ($listing eq 'unknown_cmd') {
7220: if ($getpropath) {
7221: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7222: }
7223: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7224: }
1.514 albertel 7225: return $listing;
1.512 banghart 7226: }
7227:
1.566 banghart 7228: sub is_locked {
7229: my ($file_name, $domain, $user) = @_;
7230: my @check;
7231: my $is_locked;
7232: push @check, $file_name;
1.613 albertel 7233: my %locked = &get('file_permissions',\@check,
1.620 albertel 7234: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7235: my ($tmp)=keys(%locked);
7236: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7237:
1.566 banghart 7238: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7239: $is_locked = 'false';
7240: foreach my $entry (@{$locked{$file_name}}) {
7241: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7242: $is_locked = 'true';
7243: last;
1.745 raeburn 7244: }
7245: }
1.566 banghart 7246: } else {
7247: $is_locked = 'false';
7248: }
7249: }
7250:
1.759 albertel 7251: sub declutter_portfile {
7252: my ($file) = @_;
1.833 albertel 7253: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7254: return $file;
7255: }
7256:
1.559 banghart 7257: # ------------------------------------------------------------- Mark as Read Only
7258:
7259: sub mark_as_readonly {
7260: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7261: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7262: my ($tmp)=keys(%current_permissions);
7263: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7264: foreach my $file (@{$files}) {
1.759 albertel 7265: $file = &declutter_portfile($file);
1.561 banghart 7266: push(@{$current_permissions{$file}},$what);
1.559 banghart 7267: }
1.613 albertel 7268: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7269: return;
7270: }
7271:
1.572 banghart 7272: # ------------------------------------------------------------Save Selected Files
7273:
7274: sub save_selected_files {
7275: my ($user, $path, @files) = @_;
7276: my $filename = $user."savedfiles";
1.573 banghart 7277: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7278: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7279: foreach my $file (@files) {
1.620 albertel 7280: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7281: }
7282: foreach my $file (@other_files) {
1.574 banghart 7283: print (OUT $file."\n");
1.572 banghart 7284: }
1.574 banghart 7285: close (OUT);
1.572 banghart 7286: return 'ok';
7287: }
7288:
1.574 banghart 7289: sub clear_selected_files {
7290: my ($user) = @_;
7291: my $filename = $user."savedfiles";
7292: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7293: print (OUT undef);
7294: close (OUT);
7295: return ("ok");
7296: }
7297:
1.572 banghart 7298: sub files_in_path {
7299: my ($user, $path) = @_;
7300: my $filename = $user."savedfiles";
7301: my %return_files;
1.574 banghart 7302: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7303: while (my $line_in = <IN>) {
1.574 banghart 7304: chomp ($line_in);
7305: my @paths_and_file = split (m!/!, $line_in);
7306: my $file_part = pop (@paths_and_file);
7307: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7308: $path_part.='/';
7309: my $path_and_file = $path_part.$file_part;
7310: if ($path_part eq $path) {
7311: $return_files{$file_part}= 'selected';
7312: }
7313: }
1.574 banghart 7314: close (IN);
7315: return (\%return_files);
1.572 banghart 7316: }
7317:
7318: # called in portfolio select mode, to show files selected NOT in current directory
7319: sub files_not_in_path {
7320: my ($user, $path) = @_;
7321: my $filename = $user."savedfiles";
7322: my @return_files;
7323: my $path_part;
1.800 albertel 7324: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7325: while (my $line = <IN>) {
1.572 banghart 7326: #ok, I know it's clunky, but I want it to work
1.800 albertel 7327: my @paths_and_file = split(m|/|, $line);
7328: my $file_part = pop(@paths_and_file);
7329: chomp($file_part);
7330: my $path_part = join('/', @paths_and_file);
1.572 banghart 7331: $path_part .= '/';
7332: my $path_and_file = $path_part.$file_part;
7333: if ($path_part ne $path) {
1.800 albertel 7334: push(@return_files, ($path_and_file));
1.572 banghart 7335: }
7336: }
1.800 albertel 7337: close(OUT);
1.574 banghart 7338: return (@return_files);
1.572 banghart 7339: }
7340:
1.745 raeburn 7341: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7342:
1.745 raeburn 7343: sub get_portfile_permissions {
7344: my ($domain,$user) = @_;
1.613 albertel 7345: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7346: my ($tmp)=keys(%current_permissions);
7347: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7348: return \%current_permissions;
7349: }
7350:
7351: #---------------------------------------------Get portfolio file access controls
7352:
1.749 raeburn 7353: sub get_access_controls {
1.745 raeburn 7354: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7355: my %access;
7356: my $real_file = $file;
7357: $file =~ s/\.meta$//;
1.745 raeburn 7358: if (defined($file)) {
1.749 raeburn 7359: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7360: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7361: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7362: }
7363: }
1.745 raeburn 7364: } else {
1.749 raeburn 7365: foreach my $key (keys(%{$current_permissions})) {
7366: if ($key =~ /\0accesscontrol$/) {
7367: if (defined($group)) {
7368: if ($key !~ m-^\Q$group\E/-) {
7369: next;
7370: }
7371: }
7372: my ($fullpath) = split(/\0/,$key);
7373: if (ref($$current_permissions{$key}) eq 'HASH') {
7374: foreach my $control (keys(%{$$current_permissions{$key}})) {
7375: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7376: }
7377: }
7378: }
7379: }
7380: }
7381: return %access;
7382: }
7383:
7384: sub modify_access_controls {
7385: my ($file_name,$changes,$domain,$user)=@_;
7386: my ($outcome,$deloutcome);
7387: my %store_permissions;
7388: my %new_values;
7389: my %new_control;
7390: my %translation;
7391: my @deletions = ();
7392: my $now = time;
7393: if (exists($$changes{'activate'})) {
7394: if (ref($$changes{'activate'}) eq 'HASH') {
7395: my @newitems = sort(keys(%{$$changes{'activate'}}));
7396: my $numnew = scalar(@newitems);
7397: for (my $i=0; $i<$numnew; $i++) {
7398: my $newkey = $newitems[$i];
7399: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7400: if ($newkey =~ /^\d+:/) {
7401: $newkey =~ s/^(\d+)/$newid/;
7402: $translation{$1} = $newid;
7403: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7404: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7405: $translation{$1} = $newid;
7406: }
1.749 raeburn 7407: $new_values{$file_name."\0".$newkey} =
7408: $$changes{'activate'}{$newitems[$i]};
7409: $new_control{$newkey} = $now;
7410: }
7411: }
7412: }
7413: my %todelete;
7414: my %changed_items;
7415: foreach my $action ('delete','update') {
7416: if (exists($$changes{$action})) {
7417: if (ref($$changes{$action}) eq 'HASH') {
7418: foreach my $key (keys(%{$$changes{$action}})) {
7419: my ($itemnum) = ($key =~ /^([^:]+):/);
7420: if ($action eq 'delete') {
7421: $todelete{$itemnum} = 1;
7422: } else {
7423: $changed_items{$itemnum} = $key;
7424: }
7425: }
1.745 raeburn 7426: }
7427: }
1.749 raeburn 7428: }
7429: # get lock on access controls for file.
7430: my $lockhash = {
7431: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7432: ':'.$env{'user.domain'},
7433: };
7434: my $tries = 0;
7435: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7436:
7437: while (($gotlock ne 'ok') && $tries <3) {
7438: $tries ++;
7439: sleep 1;
7440: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7441: }
7442: if ($gotlock eq 'ok') {
7443: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7444: my ($tmp)=keys(%curr_permissions);
7445: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7446: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7447: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7448: if (ref($curr_controls) eq 'HASH') {
7449: foreach my $control_item (keys(%{$curr_controls})) {
7450: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7451: if (defined($todelete{$itemnum})) {
7452: push(@deletions,$file_name."\0".$control_item);
7453: } else {
7454: if (defined($changed_items{$itemnum})) {
7455: $new_control{$changed_items{$itemnum}} = $now;
7456: push(@deletions,$file_name."\0".$control_item);
7457: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7458: } else {
7459: $new_control{$control_item} = $$curr_controls{$control_item};
7460: }
7461: }
1.745 raeburn 7462: }
7463: }
7464: }
1.970 raeburn 7465: my ($group);
7466: if (&is_course($domain,$user)) {
7467: ($group,my $file) = split(/\//,$file_name,2);
7468: }
1.749 raeburn 7469: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7470: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7471: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7472: # remove lock
7473: my @del_lock = ($file_name."\0".'locked_access_records');
7474: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7475: my $sqlresult =
1.970 raeburn 7476: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7477: $group);
1.749 raeburn 7478: } else {
7479: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7480: }
1.749 raeburn 7481: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7482: }
7483:
1.827 raeburn 7484: sub make_public_indefinitely {
7485: my ($requrl) = @_;
7486: my $now = time;
7487: my $action = 'activate';
7488: my $aclnum = 0;
7489: if (&is_portfolio_url($requrl)) {
7490: my (undef,$udom,$unum,$file_name,$group) =
7491: &parse_portfolio_url($requrl);
7492: my $current_perms = &get_portfile_permissions($udom,$unum);
7493: my %access_controls = &get_access_controls($current_perms,
7494: $group,$file_name);
7495: foreach my $key (keys(%{$access_controls{$file_name}})) {
7496: my ($num,$scope,$end,$start) =
7497: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7498: if ($scope eq 'public') {
7499: if ($start <= $now && $end == 0) {
7500: $action = 'none';
7501: } else {
7502: $action = 'update';
7503: $aclnum = $num;
7504: }
7505: last;
7506: }
7507: }
7508: if ($action eq 'none') {
7509: return 'ok';
7510: } else {
7511: my %changes;
7512: my $newend = 0;
7513: my $newstart = $now;
7514: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7515: $changes{$action}{$newkey} = {
7516: type => 'public',
7517: time => {
7518: start => $newstart,
7519: end => $newend,
7520: },
7521: };
7522: my ($outcome,$deloutcome,$new_values,$translation) =
7523: &modify_access_controls($file_name,\%changes,$udom,$unum);
7524: return $outcome;
7525: }
7526: } else {
7527: return 'invalid';
7528: }
7529: }
7530:
1.745 raeburn 7531: #------------------------------------------------------Get Marked as Read Only
7532:
7533: sub get_marked_as_readonly {
7534: my ($domain,$user,$what,$group) = @_;
7535: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7536: my @readonly_files;
1.629 banghart 7537: my $cmp1=$what;
7538: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7539: while (my ($file_name,$value) = each(%{$current_permissions})) {
7540: if (defined($group)) {
7541: if ($file_name !~ m-^\Q$group\E/-) {
7542: next;
7543: }
7544: }
1.561 banghart 7545: if (ref($value) eq "ARRAY"){
7546: foreach my $stored_what (@{$value}) {
1.629 banghart 7547: my $cmp2=$stored_what;
1.759 albertel 7548: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7549: $cmp2=join('',@{$stored_what});
1.745 raeburn 7550: }
1.629 banghart 7551: if ($cmp1 eq $cmp2) {
1.561 banghart 7552: push(@readonly_files, $file_name);
1.745 raeburn 7553: last;
1.563 banghart 7554: } elsif (!defined($what)) {
7555: push(@readonly_files, $file_name);
1.745 raeburn 7556: last;
1.561 banghart 7557: }
7558: }
1.745 raeburn 7559: }
1.561 banghart 7560: }
7561: return @readonly_files;
7562: }
1.577 banghart 7563: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7564:
1.577 banghart 7565: sub get_marked_as_readonly_hash {
1.745 raeburn 7566: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7567: my %readonly_files;
1.745 raeburn 7568: while (my ($file_name,$value) = each(%{$current_permissions})) {
7569: if (defined($group)) {
7570: if ($file_name !~ m-^\Q$group\E/-) {
7571: next;
7572: }
7573: }
1.577 banghart 7574: if (ref($value) eq "ARRAY"){
7575: foreach my $stored_what (@{$value}) {
1.745 raeburn 7576: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7577: foreach my $lock_descriptor(@{$stored_what}) {
7578: if ($lock_descriptor eq 'graded') {
7579: $readonly_files{$file_name} = 'graded';
7580: } elsif ($lock_descriptor eq 'handback') {
7581: $readonly_files{$file_name} = 'handback';
7582: } else {
7583: if (!exists($readonly_files{$file_name})) {
7584: $readonly_files{$file_name} = 'locked';
7585: }
7586: }
1.745 raeburn 7587: }
1.750 banghart 7588: }
1.577 banghart 7589: }
7590: }
7591: }
7592: return %readonly_files;
7593: }
1.559 banghart 7594: # ------------------------------------------------------------ Unmark as Read Only
7595:
7596: sub unmark_as_readonly {
1.629 banghart 7597: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7598: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7599: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7600: $file_name = &declutter_portfile($file_name);
1.634 albertel 7601: my $symb_crs = $what;
7602: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7603: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7604: my ($tmp)=keys(%current_permissions);
7605: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7606: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7607: foreach my $file (@readonly_files) {
1.759 albertel 7608: my $clean_file = &declutter_portfile($file);
7609: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7610: my $current_locks = $current_permissions{$file};
1.563 banghart 7611: my @new_locks;
7612: my @del_keys;
7613: if (ref($current_locks) eq "ARRAY"){
7614: foreach my $locker (@{$current_locks}) {
1.632 albertel 7615: my $compare=$locker;
1.749 raeburn 7616: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7617: $compare=join('',@{$locker});
1.746 raeburn 7618: if ($compare ne $symb_crs) {
7619: push(@new_locks, $locker);
7620: }
1.563 banghart 7621: }
7622: }
1.650 albertel 7623: if (scalar(@new_locks) > 0) {
1.563 banghart 7624: $current_permissions{$file} = \@new_locks;
7625: } else {
7626: push(@del_keys, $file);
1.613 albertel 7627: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7628: delete($current_permissions{$file});
1.563 banghart 7629: }
7630: }
1.561 banghart 7631: }
1.613 albertel 7632: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7633: return;
7634: }
1.512 banghart 7635:
1.17 www 7636: # ------------------------------------------------------------ Directory lister
7637:
7638: sub dirlist {
1.955 raeburn 7639: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7640: $uri=~s/^\///;
7641: $uri=~s/\/$//;
1.253 stredwic 7642: my ($udom, $uname);
1.955 raeburn 7643: if ($getuserdir) {
1.253 stredwic 7644: $udom = $userdomain;
7645: $uname = $username;
1.955 raeburn 7646: } else {
7647: (undef,$udom,$uname)=split(/\//,$uri);
7648: if(defined($userdomain)) {
7649: $udom = $userdomain;
7650: }
7651: if(defined($username)) {
7652: $uname = $username;
7653: }
1.253 stredwic 7654: }
1.955 raeburn 7655: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7656:
1.955 raeburn 7657: $dirRoot = $perlvar{'lonDocRoot'};
7658: if (defined($getpropath)) {
7659: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7660: $dirRoot =~ s/\/$//;
1.955 raeburn 7661: } elsif (defined($getuserdir)) {
7662: my $subdir=$uname.'__';
7663: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7664: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7665: ."/$udom/$subdir/$uname";
7666: } elsif (defined($alternateRoot)) {
7667: $dirRoot = $alternateRoot;
1.751 banghart 7668: }
1.253 stredwic 7669:
7670: if($udom) {
7671: if($uname) {
1.955 raeburn 7672: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7673: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7674: .':'.&escape($uname).':'.&escape($udom),
7675: &homeserver($uname,$udom));
7676: if ($listing eq 'unknown_cmd') {
7677: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7678: &homeserver($uname,$udom));
7679: } else {
7680: @listing_results = map { &unescape($_); } split(/:/,$listing);
7681: }
1.605 matthew 7682: if ($listing eq 'unknown_cmd') {
1.800 albertel 7683: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7684: &homeserver($uname,$udom));
1.605 matthew 7685: @listing_results = split(/:/,$listing);
7686: } else {
7687: @listing_results = map { &unescape($_); } split(/:/,$listing);
7688: }
7689: return @listing_results;
1.955 raeburn 7690: } elsif(!$alternateRoot) {
1.800 albertel 7691: my %allusers;
1.841 albertel 7692: my %servers = &get_servers($udom,'library');
1.955 raeburn 7693: foreach my $tryserver (keys(%servers)) {
7694: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7695: &escape($udom),$tryserver);
7696: if ($listing eq 'unknown_cmd') {
7697: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7698: $udom, $tryserver);
7699: } else {
7700: @listing_results = map { &unescape($_); } split(/:/,$listing);
7701: }
1.841 albertel 7702: if ($listing eq 'unknown_cmd') {
7703: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7704: $udom, $tryserver);
7705: @listing_results = split(/:/,$listing);
7706: } else {
7707: @listing_results =
7708: map { &unescape($_); } split(/:/,$listing);
7709: }
7710: if ($listing_results[0] ne 'no_such_dir' &&
7711: $listing_results[0] ne 'empty' &&
7712: $listing_results[0] ne 'con_lost') {
7713: foreach my $line (@listing_results) {
7714: my ($entry) = split(/&/,$line,2);
7715: $allusers{$entry} = 1;
7716: }
7717: }
1.253 stredwic 7718: }
7719: my $alluserstr='';
1.800 albertel 7720: foreach my $user (sort(keys(%allusers))) {
7721: $alluserstr.=$user.'&user:';
1.253 stredwic 7722: }
7723: $alluserstr=~s/:$//;
7724: return split(/:/,$alluserstr);
7725: } else {
1.800 albertel 7726: return ('missing user name');
1.253 stredwic 7727: }
1.955 raeburn 7728: } elsif(!defined($getpropath)) {
1.841 albertel 7729: my @all_domains = sort(&all_domains());
1.955 raeburn 7730: foreach my $domain (@all_domains) {
7731: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7732: }
7733: return @all_domains;
7734: } else {
1.800 albertel 7735: return ('missing domain');
1.275 stredwic 7736: }
7737: }
7738:
7739: # --------------------------------------------- GetFileTimestamp
7740: # This function utilizes dirlist and returns the date stamp for
7741: # when it was last modified. It will also return an error of -1
7742: # if an error occurs
7743:
7744: sub GetFileTimestamp {
1.955 raeburn 7745: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7746: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7747: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7748: my ($fileStat) =
7749: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7750: undef,$getuserdir);
1.275 stredwic 7751: my @stats = split('&', $fileStat);
7752: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7753: # @stats contains first the filename, then the stat output
7754: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7755: } else {
7756: return -1;
1.253 stredwic 7757: }
1.26 www 7758: }
7759:
1.712 albertel 7760: sub stat_file {
7761: my ($uri) = @_;
1.787 albertel 7762: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7763:
1.955 raeburn 7764: my ($udom,$uname,$file);
1.712 albertel 7765: if ($uri =~ m-^/(uploaded|editupload)/-) {
7766: ($udom,$uname,$file) =
1.811 albertel 7767: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7768: $file = 'userfiles/'.$file;
7769: }
7770: if ($uri =~ m-^/res/-) {
7771: ($udom,$uname) =
1.807 albertel 7772: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7773: $file = $uri;
7774: }
7775:
7776: if (!$udom || !$uname || !$file) {
7777: # unable to handle the uri
7778: return ();
7779: }
1.956 raeburn 7780: my $getpropath;
7781: if ($file =~ /^userfiles\//) {
7782: $getpropath = 1;
7783: }
1.955 raeburn 7784: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7785: my @stats = split('&', $result);
1.721 banghart 7786:
1.712 albertel 7787: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7788: shift(@stats); #filename is first
7789: return @stats;
7790: }
7791: return ();
7792: }
7793:
1.26 www 7794: # -------------------------------------------------------- Value of a Condition
7795:
1.713 albertel 7796: # gets the value of a specific preevaluated condition
7797: # stored in the string $env{user.state.<cid>}
7798: # or looks up a condition reference in the bighash and if if hasn't
7799: # already been evaluated recurses into docondval to get the value of
7800: # the condition, then memoizing it to
7801: # $env{user.state.<cid>.<condition>}
1.40 www 7802: sub directcondval {
7803: my $number=shift;
1.620 albertel 7804: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7805: &Apache::lonuserstate::evalstate();
7806: }
1.713 albertel 7807: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7808: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7809: } elsif ($number =~ /^_/) {
7810: my $sub_condition;
7811: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7812: &GDBM_READER(),0640)) {
7813: $sub_condition=$bighash{'conditions'.$number};
7814: untie(%bighash);
7815: }
7816: my $value = &docondval($sub_condition);
1.949 raeburn 7817: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7818: return $value;
7819: }
1.620 albertel 7820: if ($env{'user.state.'.$env{'request.course.id'}}) {
7821: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7822: } else {
7823: return 2;
7824: }
7825: }
7826:
1.713 albertel 7827: # get the collection of conditions for this resource
1.26 www 7828: sub condval {
7829: my $condidx=shift;
1.54 www 7830: my $allpathcond='';
1.713 albertel 7831: foreach my $cond (split(/\|/,$condidx)) {
7832: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7833: $allpathcond.=
7834: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7835: }
1.191 harris41 7836: }
1.54 www 7837: $allpathcond=~s/\|$//;
1.713 albertel 7838: return &docondval($allpathcond);
7839: }
7840:
7841: #evaluates an expression of conditions
7842: sub docondval {
7843: my ($allpathcond) = @_;
7844: my $result=0;
7845: if ($env{'request.course.id'}
7846: && defined($allpathcond)) {
7847: my $operand='|';
7848: my @stack;
7849: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7850: if ($chunk eq '(') {
7851: push @stack,($operand,$result);
7852: } elsif ($chunk eq ')') {
7853: my $before=pop @stack;
7854: if (pop @stack eq '&') {
7855: $result=$result>$before?$before:$result;
7856: } else {
7857: $result=$result>$before?$result:$before;
7858: }
7859: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7860: $operand=$chunk;
7861: } else {
7862: my $new=directcondval($chunk);
7863: if ($operand eq '&') {
7864: $result=$result>$new?$new:$result;
7865: } else {
7866: $result=$result>$new?$result:$new;
7867: }
7868: }
7869: }
1.26 www 7870: }
7871: return $result;
1.421 albertel 7872: }
7873:
7874: # ---------------------------------------------------- Devalidate courseresdata
7875:
7876: sub devalidatecourseresdata {
7877: my ($coursenum,$coursedomain)=@_;
7878: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7879: &devalidate_cache_new('courseres',$hashid);
1.28 www 7880: }
7881:
1.763 www 7882:
1.200 www 7883: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 7884: #
7885: # Parameters:
7886: # $coursenum - Number of the course.
7887: # $coursedomain - Domain at which the course was created.
7888: # Returns:
7889: # A hash of the course parameters along (I think) with timestamps
7890: # and version info.
1.877 foxr 7891:
1.624 albertel 7892: sub get_courseresdata {
7893: my ($coursenum,$coursedomain)=@_;
1.200 www 7894: my $coursehom=&homeserver($coursenum,$coursedomain);
7895: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7896: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 7897: my %dumpreply;
1.417 albertel 7898: unless (defined($cached)) {
1.624 albertel 7899: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 7900: $result=\%dumpreply;
1.251 albertel 7901: my ($tmp) = keys(%dumpreply);
7902: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 7903: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 7904: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7905: return $tmp;
1.416 albertel 7906: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 7907: $result=undef;
1.599 albertel 7908: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 7909: }
7910: }
1.624 albertel 7911: return $result;
7912: }
7913:
1.633 albertel 7914: sub devalidateuserresdata {
7915: my ($uname,$udom)=@_;
7916: my $hashid="$udom:$uname";
7917: &devalidate_cache_new('userres',$hashid);
7918: }
7919:
1.624 albertel 7920: sub get_userresdata {
7921: my ($uname,$udom)=@_;
7922: #most student don\'t have any data set, check if there is some data
7923: if (&EXT_cache_status($udom,$uname)) { return undef; }
7924:
7925: my $hashid="$udom:$uname";
7926: my ($result,$cached)=&is_cached_new('userres',$hashid);
7927: if (!defined($cached)) {
7928: my %resourcedata=&dump('resourcedata',$udom,$uname);
7929: $result=\%resourcedata;
7930: &do_cache_new('userres',$hashid,$result,600);
7931: }
7932: my ($tmp)=keys(%$result);
7933: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7934: return $result;
7935: }
7936: #error 2 occurs when the .db doesn't exist
7937: if ($tmp!~/error: 2 /) {
1.672 albertel 7938: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 7939: " Trying to get resource data for ".
7940: $uname." at ".$udom.": ".
7941: $tmp."</font>");
7942: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 7943: #&EXT_cache_set($udom,$uname);
7944: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 7945: undef($tmp); # not really an error so don't send it back
1.624 albertel 7946: }
7947: return $tmp;
7948: }
1.879 foxr 7949: #----------------------------------------------- resdata - return resource data
7950: # Purpose:
7951: # Return resource data for either users or for a course.
7952: # Parameters:
7953: # $name - Course/user name.
7954: # $domain - Name of the domain the user/course is registered on.
7955: # $type - Type of thing $name is (must be 'course' or 'user'
7956: # @which - Array of names of resources desired.
7957: # Returns:
7958: # The value of the first reasource in @which that is found in the
7959: # resource hash.
7960: # Exceptional Conditions:
7961: # If the $type passed in is not valid (not the string 'course' or
7962: # 'user', an undefined reference is returned.
7963: # If none of the resources are found, an undef is returned
1.624 albertel 7964: sub resdata {
7965: my ($name,$domain,$type,@which)=@_;
7966: my $result;
7967: if ($type eq 'course') {
7968: $result=&get_courseresdata($name,$domain);
7969: } elsif ($type eq 'user') {
7970: $result=&get_userresdata($name,$domain);
7971: }
7972: if (!ref($result)) { return $result; }
1.251 albertel 7973: foreach my $item (@which) {
1.927 albertel 7974: if (defined($result->{$item->[0]})) {
7975: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 7976: }
1.250 albertel 7977: }
1.291 albertel 7978: return undef;
1.200 www 7979: }
7980:
1.379 matthew 7981: #
7982: # EXT resource caching routines
7983: #
7984:
7985: sub clear_EXT_cache_status {
1.383 albertel 7986: &delenv('cache.EXT.');
1.379 matthew 7987: }
7988:
7989: sub EXT_cache_status {
7990: my ($target_domain,$target_user) = @_;
1.383 albertel 7991: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 7992: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 7993: # We know already the user has no data
7994: return 1;
7995: } else {
7996: return 0;
7997: }
7998: }
7999:
8000: sub EXT_cache_set {
8001: my ($target_domain,$target_user) = @_;
1.383 albertel 8002: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8003: #&appenv({$cachename => time});
1.379 matthew 8004: }
8005:
1.28 www 8006: # --------------------------------------------------------- Value of a Variable
1.58 www 8007: sub EXT {
1.715 albertel 8008:
1.395 albertel 8009: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8010: unless ($varname) { return ''; }
1.218 albertel 8011: #get real user name/domain, courseid and symb
8012: my $courseid;
1.359 albertel 8013: my $publicuser;
1.427 www 8014: if ($symbparm) {
8015: $symbparm=&get_symb_from_alias($symbparm);
8016: }
1.218 albertel 8017: if (!($uname && $udom)) {
1.790 albertel 8018: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8019: if (!$symbparm) { $symbparm=$cursymb; }
8020: } else {
1.620 albertel 8021: $courseid=$env{'request.course.id'};
1.218 albertel 8022: }
1.48 www 8023: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8024: my $rest;
1.320 albertel 8025: if (defined($therest[0])) {
1.48 www 8026: $rest=join('.',@therest);
8027: } else {
8028: $rest='';
8029: }
1.320 albertel 8030:
1.57 www 8031: my $qualifierrest=$qualifier;
8032: if ($rest) { $qualifierrest.='.'.$rest; }
8033: my $spacequalifierrest=$space;
8034: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8035: if ($realm eq 'user') {
1.48 www 8036: # --------------------------------------------------------------- user.resource
8037: if ($space eq 'resource') {
1.651 albertel 8038: if ( (defined($Apache::lonhomework::parsing_a_problem)
8039: || defined($Apache::lonhomework::parsing_a_task))
8040: &&
1.744 albertel 8041: ($symbparm eq &symbread()) ) {
8042: # if we are in the middle of processing the resource the
8043: # get the value we are planning on committing
8044: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8045: return $Apache::lonhomework::results{$qualifierrest};
8046: } else {
8047: return $Apache::lonhomework::history{$qualifierrest};
8048: }
1.335 albertel 8049: } else {
1.359 albertel 8050: my %restored;
1.620 albertel 8051: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8052: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8053: } else {
8054: %restored=&restore($symbparm,$courseid,$udom,$uname);
8055: }
1.335 albertel 8056: return $restored{$qualifierrest};
8057: }
1.48 www 8058: # ----------------------------------------------------------------- user.access
8059: } elsif ($space eq 'access') {
1.218 albertel 8060: # FIXME - not supporting calls for a specific user
1.48 www 8061: return &allowed($qualifier,$rest);
8062: # ------------------------------------------ user.preferences, user.environment
8063: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8064: if (($uname eq $env{'user.name'}) &&
8065: ($udom eq $env{'user.domain'})) {
8066: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8067: } else {
1.359 albertel 8068: my %returnhash;
8069: if (!$publicuser) {
8070: %returnhash=&userenvironment($udom,$uname,
8071: $qualifierrest);
8072: }
1.218 albertel 8073: return $returnhash{$qualifierrest};
8074: }
1.48 www 8075: # ----------------------------------------------------------------- user.course
8076: } elsif ($space eq 'course') {
1.218 albertel 8077: # FIXME - not supporting calls for a specific user
1.620 albertel 8078: return $env{join('.',('request.course',$qualifier))};
1.48 www 8079: # ------------------------------------------------------------------- user.role
8080: } elsif ($space eq 'role') {
1.218 albertel 8081: # FIXME - not supporting calls for a specific user
1.620 albertel 8082: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8083: if ($qualifier eq 'value') {
8084: return $role;
8085: } elsif ($qualifier eq 'extent') {
8086: return $where;
8087: }
8088: # ----------------------------------------------------------------- user.domain
8089: } elsif ($space eq 'domain') {
1.218 albertel 8090: return $udom;
1.48 www 8091: # ------------------------------------------------------------------- user.name
8092: } elsif ($space eq 'name') {
1.218 albertel 8093: return $uname;
1.48 www 8094: # ---------------------------------------------------- Any other user namespace
1.29 www 8095: } else {
1.359 albertel 8096: my %reply;
8097: if (!$publicuser) {
8098: %reply=&get($space,[$qualifierrest],$udom,$uname);
8099: }
8100: return $reply{$qualifierrest};
1.48 www 8101: }
1.236 www 8102: } elsif ($realm eq 'query') {
8103: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8104: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8105: [$spacequalifierrest]);
1.620 albertel 8106: return $env{'form.'.$spacequalifierrest};
1.236 www 8107: } elsif ($realm eq 'request') {
1.48 www 8108: # ------------------------------------------------------------- request.browser
8109: if ($space eq 'browser') {
1.430 www 8110: if ($qualifier eq 'textremote') {
1.676 albertel 8111: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8112: return 1;
8113: } else {
8114: return 0;
8115: }
8116: } else {
1.620 albertel 8117: return $env{'browser.'.$qualifier};
1.430 www 8118: }
1.57 www 8119: # ------------------------------------------------------------ request.filename
8120: } else {
1.620 albertel 8121: return $env{'request.'.$spacequalifierrest};
1.29 www 8122: }
1.28 www 8123: } elsif ($realm eq 'course') {
1.48 www 8124: # ---------------------------------------------------------- course.description
1.620 albertel 8125: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8126: } elsif ($realm eq 'resource') {
1.165 www 8127:
1.620 albertel 8128: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8129: if (!$symbparm) { $symbparm=&symbread(); }
8130: }
1.693 albertel 8131:
8132: if ($space eq 'title') {
8133: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8134: return &gettitle($symbparm);
8135: }
8136:
8137: if ($space eq 'map') {
8138: my ($map) = &decode_symb($symbparm);
8139: return &symbread($map);
8140: }
1.905 albertel 8141: if ($space eq 'filename') {
8142: if ($symbparm) {
8143: return &clutter((&decode_symb($symbparm))[2]);
8144: }
8145: return &hreflocation('',$env{'request.filename'});
8146: }
1.693 albertel 8147:
8148: my ($section, $group, @groups);
1.593 albertel 8149: my ($courselevelm,$courselevel);
1.539 albertel 8150: if ($symbparm && defined($courseid) &&
1.620 albertel 8151: $courseid eq $env{'request.course.id'}) {
1.165 www 8152:
1.218 albertel 8153: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8154:
1.60 www 8155: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8156: my $symbp=$symbparm;
1.735 albertel 8157: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8158:
8159: my $symbparm=$symbp.'.'.$spacequalifierrest;
8160: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8161:
1.620 albertel 8162: if (($env{'user.name'} eq $uname) &&
8163: ($env{'user.domain'} eq $udom)) {
8164: $section=$env{'request.course.sec'};
1.733 raeburn 8165: @groups = split(/:/,$env{'request.course.groups'});
8166: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8167: } else {
1.539 albertel 8168: if (! defined($usection)) {
1.551 albertel 8169: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8170: } else {
8171: $section = $usection;
8172: }
1.733 raeburn 8173: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8174: }
8175:
8176: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8177: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8178: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8179:
1.593 albertel 8180: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8181: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8182: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8183:
1.60 www 8184: # ----------------------------------------------------------- first, check user
1.624 albertel 8185:
8186: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8187: ([$courselevelr,'resource'],
8188: [$courselevelm,'map' ],
8189: [$courselevel, 'course' ]));
1.931 albertel 8190: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8191:
1.594 albertel 8192: # ------------------------------------------------ second, check some of course
1.684 raeburn 8193: my $coursereply;
1.691 raeburn 8194: if (@groups > 0) {
8195: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8196: $mapparm,$spacequalifierrest);
1.927 albertel 8197: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8198: }
1.96 www 8199:
1.684 raeburn 8200: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8201: $env{'course.'.$courseid.'.domain'},
8202: 'course',
8203: ([$seclevelr, 'resource'],
8204: [$seclevelm, 'map' ],
8205: [$seclevel, 'course' ],
8206: [$courselevelr,'resource']));
8207: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8208:
1.60 www 8209: # ------------------------------------------------------ third, check map parms
1.218 albertel 8210: my %parmhash=();
8211: my $thisparm='';
8212: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8213: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8214: &GDBM_READER(),0640)) {
1.218 albertel 8215: $thisparm=$parmhash{$symbparm};
8216: untie(%parmhash);
8217: }
1.927 albertel 8218: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8219: }
1.594 albertel 8220: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8221:
1.218 albertel 8222: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8223: my $filename;
8224: if (!$symbparm) { $symbparm=&symbread(); }
8225: if ($symbparm) {
1.409 www 8226: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8227: } else {
1.620 albertel 8228: $filename=$env{'request.filename'};
1.282 albertel 8229: }
8230: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8231: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8232: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8233: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8234:
1.927 albertel 8235: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8236: if ($symbparm && defined($courseid) &&
1.620 albertel 8237: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8238: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8239: $env{'course.'.$courseid.'.domain'},
8240: 'course',
1.927 albertel 8241: ([$courselevelm,'map' ],
8242: [$courselevel, 'course']));
8243: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8244: }
1.145 www 8245: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8246: unless ($space eq '0') {
1.336 albertel 8247: my @parts=split(/_/,$space);
8248: my $id=pop(@parts);
8249: my $part=join('_',@parts);
8250: if ($part eq '') { $part='0'; }
1.927 albertel 8251: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8252: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8253: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8254: }
1.395 albertel 8255: if ($recurse) { return undef; }
8256: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8257: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8258: # ---------------------------------------------------- Any other user namespace
8259: } elsif ($realm eq 'environment') {
8260: # ----------------------------------------------------------------- environment
1.620 albertel 8261: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8262: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8263: } else {
1.770 albertel 8264: if ($uname eq 'anonymous' && $udom eq '') {
8265: return '';
8266: }
1.219 albertel 8267: my %returnhash=&userenvironment($udom,$uname,
8268: $spacequalifierrest);
8269: return $returnhash{$spacequalifierrest};
8270: }
1.28 www 8271: } elsif ($realm eq 'system') {
1.48 www 8272: # ----------------------------------------------------------------- system.time
8273: if ($space eq 'time') {
8274: return time;
8275: }
1.696 albertel 8276: } elsif ($realm eq 'server') {
8277: # ----------------------------------------------------------------- system.time
8278: if ($space eq 'name') {
8279: return $ENV{'SERVER_NAME'};
8280: }
1.28 www 8281: }
1.48 www 8282: return '';
1.61 www 8283: }
8284:
1.927 albertel 8285: sub get_reply {
8286: my ($reply_value) = @_;
1.940 raeburn 8287: if (ref($reply_value) eq 'ARRAY') {
8288: if (wantarray) {
8289: return @$reply_value;
8290: }
8291: return $reply_value->[0];
8292: } else {
8293: return $reply_value;
1.927 albertel 8294: }
8295: }
8296:
1.691 raeburn 8297: sub check_group_parms {
8298: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8299: my @groupitems = ();
8300: my $resultitem;
1.927 albertel 8301: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8302: foreach my $group (@{$groups}) {
8303: foreach my $level (@levels) {
1.927 albertel 8304: my $item = $courseid.'.['.$group.'].'.$level->[0];
8305: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8306: }
8307: }
8308: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8309: $env{'course.'.$courseid.'.domain'},
8310: 'course',@groupitems);
8311: return $coursereply;
8312: }
8313:
8314: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8315: my ($courseid,@groups) = @_;
8316: @groups = sort(@groups);
1.691 raeburn 8317: return @groups;
8318: }
8319:
1.395 albertel 8320: sub packages_tab_default {
8321: my ($uri,$varname)=@_;
8322: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8323:
8324: my (@extension,@specifics,$do_default);
8325: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8326: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8327: if ($pack_type eq 'default') {
8328: $do_default=1;
8329: } elsif ($pack_type eq 'extension') {
8330: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8331: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8332: # only look at packages defaults for packages that this id is
1.738 albertel 8333: push(@specifics,[$package,$pack_type,$pack_part]);
8334: }
8335: }
8336: # first look for a package that matches the requested part id
8337: foreach my $package (@specifics) {
8338: my (undef,$pack_type,$pack_part)=@{$package};
8339: next if ($pack_part ne $part);
8340: if (defined($packagetab{"$pack_type&$name&default"})) {
8341: return $packagetab{"$pack_type&$name&default"};
8342: }
8343: }
8344: # look for any possible matching non extension_ package
8345: foreach my $package (@specifics) {
8346: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8347: if (defined($packagetab{"$pack_type&$name&default"})) {
8348: return $packagetab{"$pack_type&$name&default"};
8349: }
1.585 albertel 8350: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8351: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8352: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8353: }
8354: }
1.738 albertel 8355: # look for any posible extension_ match
8356: foreach my $package (@extension) {
8357: my ($package,$pack_type)=@{$package};
8358: if (defined($packagetab{"$pack_type&$name&default"})) {
8359: return $packagetab{"$pack_type&$name&default"};
8360: }
8361: if (defined($packagetab{$package."&$name&default"})) {
8362: return $packagetab{$package."&$name&default"};
8363: }
8364: }
8365: # look for a global default setting
8366: if ($do_default && defined($packagetab{"default&$name&default"})) {
8367: return $packagetab{"default&$name&default"};
8368: }
1.395 albertel 8369: return undef;
8370: }
8371:
1.334 albertel 8372: sub add_prefix_and_part {
8373: my ($prefix,$part)=@_;
8374: my $keyroot;
8375: if (defined($prefix) && $prefix !~ /^__/) {
8376: # prefix that has a part already
8377: $keyroot=$prefix;
8378: } elsif (defined($prefix)) {
8379: # prefix that is missing a part
8380: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8381: } else {
8382: # no prefix at all
8383: if (defined($part)) { $keyroot='_'.$part; }
8384: }
8385: return $keyroot;
8386: }
8387:
1.71 www 8388: # ---------------------------------------------------------------- Get metadata
8389:
1.599 albertel 8390: my %metaentry;
1.71 www 8391: sub metadata {
1.176 www 8392: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8393: $uri=&declutter($uri);
1.288 albertel 8394: # if it is a non metadata possible uri return quickly
1.529 albertel 8395: if (($uri eq '') ||
8396: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8397: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 8398: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
8399: return undef;
8400: }
8401: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8402: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8403: return undef;
1.288 albertel 8404: }
1.73 www 8405: my $filename=$uri;
8406: $uri=~s/\.meta$//;
1.172 www 8407: #
8408: # Is the metadata already cached?
1.177 www 8409: # Look at timestamp of caching
1.172 www 8410: # Everything is cached by the main uri, libraries are never directly cached
8411: #
1.428 albertel 8412: if (!defined($liburi)) {
1.599 albertel 8413: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8414: if (defined($cached)) { return $result->{':'.$what}; }
8415: }
8416: {
1.172 www 8417: #
8418: # Is this a recursive call for a library?
8419: #
1.599 albertel 8420: # if (! exists($metacache{$uri})) {
8421: # $metacache{$uri}={};
8422: # }
1.924 albertel 8423: my $cachetime = 60*60;
1.171 www 8424: if ($liburi) {
8425: $liburi=&declutter($liburi);
8426: $filename=$liburi;
1.401 bowersj2 8427: } else {
1.599 albertel 8428: &devalidate_cache_new('meta',$uri);
8429: undef(%metaentry);
1.401 bowersj2 8430: }
1.140 www 8431: my %metathesekeys=();
1.73 www 8432: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8433: my $metastring;
1.924 albertel 8434: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8435: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8436: $metastring =
1.929 albertel 8437: &Apache::lonnet::ssi_body($which,
1.924 albertel 8438: ('grade_target' => 'meta'));
8439: $cachetime = 1; # only want this cached in the child not long term
8440: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8441: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8442: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8443: $metastring=&getfile($file);
1.489 albertel 8444: }
1.208 albertel 8445: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8446: my $token;
1.140 www 8447: undef %metathesekeys;
1.71 www 8448: while ($token=$parser->get_token) {
1.339 albertel 8449: if ($token->[0] eq 'S') {
8450: if (defined($token->[2]->{'package'})) {
1.172 www 8451: #
8452: # This is a package - get package info
8453: #
1.339 albertel 8454: my $package=$token->[2]->{'package'};
8455: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8456: if (defined($token->[2]->{'id'})) {
8457: $keyroot.='_'.$token->[2]->{'id'};
8458: }
1.599 albertel 8459: if ($metaentry{':packages'}) {
8460: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8461: } else {
1.599 albertel 8462: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8463: }
1.736 albertel 8464: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8465: my $part=$keyroot;
8466: $part=~s/^\_//;
1.736 albertel 8467: if ($pack_entry=~/^\Q$package\E\&/ ||
8468: $pack_entry=~/^\Q$package\E_0\&/) {
8469: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8470: # ignore package.tab specified default values
8471: # here &package_tab_default() will fetch those
8472: if ($subp eq 'default') { next; }
1.736 albertel 8473: my $value=$packagetab{$pack_entry};
1.432 albertel 8474: my $unikey;
8475: if ($pack =~ /_0$/) {
8476: $unikey='parameter_0_'.$name;
8477: $part=0;
8478: } else {
8479: $unikey='parameter'.$keyroot.'_'.$name;
8480: }
1.339 albertel 8481: if ($subp eq 'display') {
8482: $value.=' [Part: '.$part.']';
8483: }
1.599 albertel 8484: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8485: $metathesekeys{$unikey}=1;
1.599 albertel 8486: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8487: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8488: }
1.599 albertel 8489: if (defined($metaentry{':'.$unikey.'.default'})) {
8490: $metaentry{':'.$unikey}=
8491: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8492: }
1.339 albertel 8493: }
8494: }
8495: } else {
1.172 www 8496: #
8497: # This is not a package - some other kind of start tag
1.339 albertel 8498: #
8499: my $entry=$token->[1];
8500: my $unikey;
8501: if ($entry eq 'import') {
8502: $unikey='';
8503: } else {
8504: $unikey=$entry;
8505: }
8506: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8507:
8508: if (defined($token->[2]->{'id'})) {
8509: $unikey.='_'.$token->[2]->{'id'};
8510: }
1.175 www 8511:
1.339 albertel 8512: if ($entry eq 'import') {
1.175 www 8513: #
8514: # Importing a library here
1.339 albertel 8515: #
8516: if ($depthcount<20) {
8517: my $location=$parser->get_text('/import');
8518: my $dir=$filename;
8519: $dir=~s|[^/]*$||;
8520: $location=&filelocation($dir,$location);
1.736 albertel 8521: my $metadata =
8522: &metadata($uri,'keys', $location,$unikey,
8523: $depthcount+1);
8524: foreach my $meta (split(',',$metadata)) {
8525: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8526: $metathesekeys{$meta}=1;
1.339 albertel 8527: }
8528: }
8529: } else {
8530:
8531: if (defined($token->[2]->{'name'})) {
8532: $unikey.='_'.$token->[2]->{'name'};
8533: }
8534: $metathesekeys{$unikey}=1;
1.736 albertel 8535: foreach my $param (@{$token->[3]}) {
8536: $metaentry{':'.$unikey.'.'.$param} =
8537: $token->[2]->{$param};
1.339 albertel 8538: }
8539: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8540: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8541: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8542: # only ws inside the tag, and not in default, so use default
8543: # as value
1.599 albertel 8544: $metaentry{':'.$unikey}=$default;
1.908 albertel 8545: } elsif ( $internaltext =~ /\S/ ) {
8546: # something interesting inside the tag
8547: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8548: } else {
1.908 albertel 8549: # no interesting values, don't set a default
1.339 albertel 8550: }
1.172 www 8551: # end of not-a-package not-a-library import
1.339 albertel 8552: }
1.172 www 8553: # end of not-a-package start tag
1.339 albertel 8554: }
1.172 www 8555: # the next is the end of "start tag"
1.339 albertel 8556: }
8557: }
1.483 albertel 8558: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8559: $extension = lc($extension);
8560: if ($extension eq 'htm') { $extension='html'; }
8561:
1.737 albertel 8562: foreach my $key (keys(%packagetab)) {
1.483 albertel 8563: #no specific packages #how's our extension
8564: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8565: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8566: \%metathesekeys);
8567: }
1.883 albertel 8568:
8569: if (!exists($metaentry{':packages'})
8570: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8571: foreach my $key (keys(%packagetab)) {
1.483 albertel 8572: #no specific packages well let's get default then
8573: if ($key!~/^default&/) { next; }
1.488 albertel 8574: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8575: \%metathesekeys);
8576: }
8577: }
1.338 www 8578: # are there custom rights to evaluate
1.599 albertel 8579: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8580:
1.338 www 8581: #
8582: # Importing a rights file here
1.339 albertel 8583: #
8584: unless ($depthcount) {
1.599 albertel 8585: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8586: my $dir=$filename;
8587: $dir=~s|[^/]*$||;
8588: $location=&filelocation($dir,$location);
1.736 albertel 8589: my $rights_metadata =
8590: &metadata($uri,'keys',$location,'_rights',
8591: $depthcount+1);
8592: foreach my $rights (split(',',$rights_metadata)) {
8593: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8594: $metathesekeys{$rights}=1;
1.339 albertel 8595: }
8596: }
8597: }
1.737 albertel 8598: # uniqifiy package listing
8599: my %seen;
8600: my @uniq_packages =
8601: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8602: $metaentry{':packages'} = join(',',@uniq_packages);
8603:
8604: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8605: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8606: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8607: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8608: # this is the end of "was not already recently cached
1.71 www 8609: }
1.599 albertel 8610: return $metaentry{':'.$what};
1.261 albertel 8611: }
8612:
1.488 albertel 8613: sub metadata_create_package_def {
1.483 albertel 8614: my ($uri,$key,$package,$metathesekeys)=@_;
8615: my ($pack,$name,$subp)=split(/\&/,$key);
8616: if ($subp eq 'default') { next; }
8617:
1.599 albertel 8618: if (defined($metaentry{':packages'})) {
8619: $metaentry{':packages'}.=','.$package;
1.483 albertel 8620: } else {
1.599 albertel 8621: $metaentry{':packages'}=$package;
1.483 albertel 8622: }
8623: my $value=$packagetab{$key};
8624: my $unikey;
8625: $unikey='parameter_0_'.$name;
1.599 albertel 8626: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8627: $$metathesekeys{$unikey}=1;
1.599 albertel 8628: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8629: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8630: }
1.599 albertel 8631: if (defined($metaentry{':'.$unikey.'.default'})) {
8632: $metaentry{':'.$unikey}=
8633: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8634: }
8635: }
8636:
1.261 albertel 8637: sub metadata_generate_part0 {
8638: my ($metadata,$metacache,$uri) = @_;
8639: my %allnames;
1.737 albertel 8640: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8641: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8642: my $part=$$metacache{':'.$metakey.'.part'};
8643: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8644: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8645: $allnames{$name}=$part;
8646: }
8647: }
8648: }
8649: foreach my $name (keys(%allnames)) {
8650: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8651: my $key=":parameter_0_$name";
1.261 albertel 8652: $$metacache{"$key.part"}='0';
8653: $$metacache{"$key.name"}=$name;
1.428 albertel 8654: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8655: $allnames{$name}.'_'.$name.
8656: '.type'};
1.428 albertel 8657: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8658: '.display'};
1.644 www 8659: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8660: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8661: $$metacache{"$key.display"}=$olddis;
8662: }
1.71 www 8663: }
8664:
1.764 albertel 8665: # ------------------------------------------------------ Devalidate title cache
8666:
8667: sub devalidate_title_cache {
8668: my ($url)=@_;
8669: if (!$env{'request.course.id'}) { return; }
8670: my $symb=&symbread($url);
8671: if (!$symb) { return; }
8672: my $key=$env{'request.course.id'}."\0".$symb;
8673: &devalidate_cache_new('title',$key);
8674: }
8675:
1.1014 droeschl 8676: # ------------------------------------------------- Get the title of a course
8677:
8678: sub current_course_title {
8679: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8680: }
1.301 www 8681: # ------------------------------------------------- Get the title of a resource
8682:
8683: sub gettitle {
8684: my $urlsymb=shift;
8685: my $symb=&symbread($urlsymb);
1.534 albertel 8686: if ($symb) {
1.620 albertel 8687: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8688: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8689: if (defined($cached)) {
8690: return $result;
8691: }
1.534 albertel 8692: my ($map,$resid,$url)=&decode_symb($symb);
8693: my $title='';
1.907 albertel 8694: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8695: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8696: } else {
8697: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8698: &GDBM_READER(),0640)) {
8699: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8700: $title=$bighash{'title_'.$mapid.'.'.$resid};
8701: untie(%bighash);
8702: }
1.534 albertel 8703: }
8704: $title=~s/\&colon\;/\:/gs;
8705: if ($title) {
1.599 albertel 8706: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8707: }
8708: $urlsymb=$url;
8709: }
8710: my $title=&metadata($urlsymb,'title');
8711: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8712: return $title;
1.301 www 8713: }
1.613 albertel 8714:
1.614 albertel 8715: sub get_slot {
8716: my ($which,$cnum,$cdom)=@_;
8717: if (!$cnum || !$cdom) {
1.790 albertel 8718: (undef,my $courseid)=&whichuser();
1.620 albertel 8719: $cdom=$env{'course.'.$courseid.'.domain'};
8720: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8721: }
1.703 albertel 8722: my $key=join("\0",'slots',$cdom,$cnum,$which);
8723: my %slotinfo;
8724: if (exists($remembered{$key})) {
8725: $slotinfo{$which} = $remembered{$key};
8726: } else {
8727: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8728: &Apache::lonhomework::showhash(%slotinfo);
8729: my ($tmp)=keys(%slotinfo);
8730: if ($tmp=~/^error:/) { return (); }
8731: $remembered{$key} = $slotinfo{$which};
8732: }
1.616 albertel 8733: if (ref($slotinfo{$which}) eq 'HASH') {
8734: return %{$slotinfo{$which}};
8735: }
8736: return $slotinfo{$which};
1.614 albertel 8737: }
1.31 www 8738: # ------------------------------------------------- Update symbolic store links
8739:
8740: sub symblist {
8741: my ($mapname,%newhash)=@_;
1.438 www 8742: $mapname=&deversion(&declutter($mapname));
1.31 www 8743: my %hash;
1.620 albertel 8744: if (($env{'request.course.fn'}) && (%newhash)) {
8745: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8746: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8747: foreach my $url (keys(%newhash)) {
1.711 albertel 8748: next if ($url eq 'last_known'
8749: && $env{'form.no_update_last_known'});
8750: $hash{declutter($url)}=&encode_symb($mapname,
8751: $newhash{$url}->[1],
8752: $newhash{$url}->[0]);
1.191 harris41 8753: }
1.31 www 8754: if (untie(%hash)) {
8755: return 'ok';
8756: }
8757: }
8758: }
8759: return 'error';
1.212 www 8760: }
8761:
8762: # --------------------------------------------------------------- Verify a symb
8763:
8764: sub symbverify {
1.510 www 8765: my ($symb,$thisurl)=@_;
8766: my $thisfn=$thisurl;
1.439 www 8767: $thisfn=&declutter($thisfn);
1.215 www 8768: # direct jump to resource in page or to a sequence - will construct own symbs
8769: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8770: # check URL part
1.409 www 8771: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8772:
1.431 www 8773: unless ($url eq $thisfn) { return 0; }
1.213 www 8774:
1.216 www 8775: $symb=&symbclean($symb);
1.510 www 8776: $thisurl=&deversion($thisurl);
1.439 www 8777: $thisfn=&deversion($thisfn);
1.213 www 8778:
8779: my %bighash;
8780: my $okay=0;
1.431 www 8781:
1.620 albertel 8782: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8783: &GDBM_READER(),0640)) {
1.1032 raeburn 8784: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8785: $thisurl =~ s/\?.+$//;
8786: }
1.510 www 8787: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8788: unless ($ids) {
1.510 www 8789: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8790: }
8791: if ($ids) {
8792: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8793: foreach my $id (split(/\,/,$ids)) {
8794: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 8795: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8796: $symb =~ s/\?.+$//;
8797: }
1.216 www 8798: if (
8799: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8800: eq $symb) {
1.620 albertel 8801: if (($env{'request.role.adv'}) ||
1.800 albertel 8802: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8803: $okay=1;
8804: }
8805: }
1.216 www 8806: }
8807: }
1.213 www 8808: untie(%bighash);
8809: }
8810: return $okay;
1.31 www 8811: }
8812:
1.210 www 8813: # --------------------------------------------------------------- Clean-up symb
8814:
8815: sub symbclean {
8816: my $symb=shift;
1.568 albertel 8817: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8818: # remove version from map
8819: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8820:
1.210 www 8821: # remove version from URL
8822: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8823:
1.507 www 8824: # remove wrapper
8825:
1.510 www 8826: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8827: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8828: return $symb;
1.409 www 8829: }
8830:
8831: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8832:
8833: sub encode_symb {
8834: my ($map,$resid,$url)=@_;
8835: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8836: }
1.409 www 8837:
8838: sub decode_symb {
1.568 albertel 8839: my $symb=shift;
8840: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8841: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 8842: return (&fixversion($map),$resid,&fixversion($url));
8843: }
8844:
8845: sub fixversion {
8846: my $fn=shift;
1.609 banghart 8847: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 8848: my %bighash;
8849: my $uri=&clutter($fn);
1.620 albertel 8850: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 8851: # is this cached?
1.599 albertel 8852: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 8853: if (defined($cached)) { return $result; }
8854: # unfortunately not cached, or expired
1.620 albertel 8855: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 8856: &GDBM_READER(),0640)) {
8857: if ($bighash{'version_'.$uri}) {
8858: my $version=$bighash{'version_'.$uri};
1.444 www 8859: unless (($version eq 'mostrecent') ||
8860: ($version==&getversion($uri))) {
1.440 www 8861: $uri=~s/\.(\w+)$/\.$version\.$1/;
8862: }
8863: }
8864: untie %bighash;
1.413 www 8865: }
1.599 albertel 8866: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 8867: }
8868:
8869: sub deversion {
8870: my $url=shift;
8871: $url=~s/\.\d+\.(\w+)$/\.$1/;
8872: return $url;
1.210 www 8873: }
8874:
1.31 www 8875: # ------------------------------------------------------ Return symb list entry
8876:
8877: sub symbread {
1.249 www 8878: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 8879: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 8880: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 8881: # no filename provided? try from environment
1.44 www 8882: unless ($thisfn) {
1.620 albertel 8883: if ($env{'request.symb'}) {
8884: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 8885: }
1.620 albertel 8886: $thisfn=$env{'request.filename'};
1.44 www 8887: }
1.569 albertel 8888: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 8889: # is that filename actually a symb? Verify, clean, and return
8890: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 8891: if (&symbverify($thisfn,$1)) {
1.620 albertel 8892: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 8893: }
1.242 www 8894: }
1.44 www 8895: $thisfn=declutter($thisfn);
1.31 www 8896: my %hash;
1.37 www 8897: my %bighash;
8898: my $syval='';
1.620 albertel 8899: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 8900: my $targetfn = $thisfn;
1.609 banghart 8901: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 8902: $targetfn = 'adm/wrapper/'.$thisfn;
8903: }
1.687 albertel 8904: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8905: $targetfn=$1;
8906: }
1.620 albertel 8907: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8908: &GDBM_READER(),0640)) {
1.481 raeburn 8909: $syval=$hash{$targetfn};
1.37 www 8910: untie(%hash);
8911: }
8912: # ---------------------------------------------------------- There was an entry
8913: if ($syval) {
1.601 albertel 8914: #unless ($syval=~/\_\d+$/) {
1.620 albertel 8915: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 8916: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8917: #return $env{$cache_str}='';
1.601 albertel 8918: #}
8919: #$syval.=$1;
8920: #}
1.37 www 8921: } else {
8922: # ------------------------------------------------------- Was not in symb table
1.620 albertel 8923: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8924: &GDBM_READER(),0640)) {
1.37 www 8925: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 8926: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 8927: unless ($ids) {
8928: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 8929: }
8930: unless ($ids) {
8931: # alias?
8932: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 8933: }
1.37 www 8934: if ($ids) {
8935: # ------------------------------------------------------------------- Has ID(s)
8936: my @possibilities=split(/\,/,$ids);
1.39 www 8937: if ($#possibilities==0) {
8938: # ----------------------------------------------- There is only one possibility
1.37 www 8939: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 8940: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8941: $resid,$thisfn);
1.249 www 8942: } elsif (!$donotrecurse) {
1.39 www 8943: # ------------------------------------------ There is more than one possibility
8944: my $realpossible=0;
1.800 albertel 8945: foreach my $id (@possibilities) {
8946: my $file=$bighash{'src_'.$id};
1.39 www 8947: if (&allowed('bre',$file)) {
1.800 albertel 8948: my ($mapid,$resid)=split(/\./,$id);
1.39 www 8949: if ($bighash{'map_type_'.$mapid} ne 'page') {
8950: $realpossible++;
1.626 albertel 8951: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8952: $resid,$thisfn);
1.39 www 8953: }
8954: }
1.191 harris41 8955: }
1.39 www 8956: if ($realpossible!=1) { $syval=''; }
1.249 www 8957: } else {
8958: $syval='';
1.37 www 8959: }
8960: }
8961: untie(%bighash)
1.481 raeburn 8962: }
1.31 www 8963: }
1.62 www 8964: if ($syval) {
1.620 albertel 8965: return $env{$cache_str}=$syval;
1.62 www 8966: }
1.31 www 8967: }
1.949 raeburn 8968: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8969: return $env{$cache_str}='';
1.31 www 8970: }
8971:
8972: # ---------------------------------------------------------- Return random seed
8973:
1.32 www 8974: sub numval {
8975: my $txt=shift;
8976: $txt=~tr/A-J/0-9/;
8977: $txt=~tr/a-j/0-9/;
8978: $txt=~tr/K-T/0-9/;
8979: $txt=~tr/k-t/0-9/;
8980: $txt=~tr/U-Z/0-5/;
8981: $txt=~tr/u-z/0-5/;
8982: $txt=~s/\D//g;
1.564 albertel 8983: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 8984: return int($txt);
1.368 albertel 8985: }
8986:
1.484 albertel 8987: sub numval2 {
8988: my $txt=shift;
8989: $txt=~tr/A-J/0-9/;
8990: $txt=~tr/a-j/0-9/;
8991: $txt=~tr/K-T/0-9/;
8992: $txt=~tr/k-t/0-9/;
8993: $txt=~tr/U-Z/0-5/;
8994: $txt=~tr/u-z/0-5/;
8995: $txt=~s/\D//g;
8996: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8997: my $total;
8998: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 8999: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9000: return int($total);
9001: }
9002:
1.575 albertel 9003: sub numval3 {
9004: use integer;
9005: my $txt=shift;
9006: $txt=~tr/A-J/0-9/;
9007: $txt=~tr/a-j/0-9/;
9008: $txt=~tr/K-T/0-9/;
9009: $txt=~tr/k-t/0-9/;
9010: $txt=~tr/U-Z/0-5/;
9011: $txt=~tr/u-z/0-5/;
9012: $txt=~s/\D//g;
9013: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9014: my $total;
9015: foreach my $val (@txts) { $total+=$val; }
9016: if ($_64bit) { $total=(($total<<32)>>32); }
9017: return $total;
9018: }
9019:
1.675 albertel 9020: sub digest {
9021: my ($data)=@_;
9022: my $digest=&Digest::MD5::md5($data);
9023: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9024: my ($e,$f);
9025: {
9026: use integer;
9027: $e=($a+$b);
9028: $f=($c+$d);
9029: if ($_64bit) {
9030: $e=(($e<<32)>>32);
9031: $f=(($f<<32)>>32);
9032: }
9033: }
9034: if (wantarray) {
9035: return ($e,$f);
9036: } else {
9037: my $g;
9038: {
9039: use integer;
9040: $g=($e+$f);
9041: if ($_64bit) {
9042: $g=(($g<<32)>>32);
9043: }
9044: }
9045: return $g;
9046: }
9047: }
9048:
1.368 albertel 9049: sub latest_rnd_algorithm_id {
1.675 albertel 9050: return '64bit5';
1.366 albertel 9051: }
1.32 www 9052:
1.503 albertel 9053: sub get_rand_alg {
9054: my ($courseid)=@_;
1.790 albertel 9055: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9056: if ($courseid) {
1.620 albertel 9057: return $env{"course.$courseid.rndseed"};
1.503 albertel 9058: }
9059: return &latest_rnd_algorithm_id();
9060: }
9061:
1.562 albertel 9062: sub validCODE {
9063: my ($CODE)=@_;
9064: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9065: return 0;
9066: }
9067:
1.491 albertel 9068: sub getCODE {
1.620 albertel 9069: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9070: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9071: defined($Apache::lonhomework::parsing_a_task) ) &&
9072: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9073: return $Apache::lonhomework::history{'resource.CODE'};
9074: }
9075: return undef;
9076: }
9077:
1.31 www 9078: sub rndseed {
1.155 albertel 9079: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9080: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9081: if (!defined($symb)) {
1.366 albertel 9082: unless ($symb=$wsymb) { return time; }
9083: }
9084: if (!$courseid) { $courseid=$wcourseid; }
9085: if (!$domain) { $domain=$wdomain; }
9086: if (!$username) { $username=$wusername }
1.503 albertel 9087: my $which=&get_rand_alg();
1.803 albertel 9088:
1.491 albertel 9089: if (defined(&getCODE())) {
1.675 albertel 9090: if ($which eq '64bit5') {
9091: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9092: } elsif ($which eq '64bit4') {
1.575 albertel 9093: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9094: } else {
9095: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9096: }
1.675 albertel 9097: } elsif ($which eq '64bit5') {
9098: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9099: } elsif ($which eq '64bit4') {
9100: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9101: } elsif ($which eq '64bit3') {
9102: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9103: } elsif ($which eq '64bit2') {
9104: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9105: } elsif ($which eq '64bit') {
9106: return &rndseed_64bit($symb,$courseid,$domain,$username);
9107: }
9108: return &rndseed_32bit($symb,$courseid,$domain,$username);
9109: }
9110:
9111: sub rndseed_32bit {
9112: my ($symb,$courseid,$domain,$username)=@_;
9113: {
9114: use integer;
9115: my $symbchck=unpack("%32C*",$symb) << 27;
9116: my $symbseed=numval($symb) << 22;
9117: my $namechck=unpack("%32C*",$username) << 17;
9118: my $nameseed=numval($username) << 12;
9119: my $domainseed=unpack("%32C*",$domain) << 7;
9120: my $courseseed=unpack("%32C*",$courseid);
9121: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9122: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9123: #&logthis("rndseed :$num:$symb");
1.564 albertel 9124: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9125: return $num;
9126: }
9127: }
9128:
9129: sub rndseed_64bit {
9130: my ($symb,$courseid,$domain,$username)=@_;
9131: {
9132: use integer;
9133: my $symbchck=unpack("%32S*",$symb) << 21;
9134: my $symbseed=numval($symb) << 10;
9135: my $namechck=unpack("%32S*",$username);
9136:
9137: my $nameseed=numval($username) << 21;
9138: my $domainseed=unpack("%32S*",$domain) << 10;
9139: my $courseseed=unpack("%32S*",$courseid);
9140:
9141: my $num1=$symbchck+$symbseed+$namechck;
9142: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9143: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9144: #&logthis("rndseed :$num:$symb");
1.564 albertel 9145: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9146: return "$num1,$num2";
1.155 albertel 9147: }
1.366 albertel 9148: }
9149:
1.443 albertel 9150: sub rndseed_64bit2 {
9151: my ($symb,$courseid,$domain,$username)=@_;
9152: {
9153: use integer;
9154: # strings need to be an even # of cahracters long, it it is odd the
9155: # last characters gets thrown away
9156: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9157: my $symbseed=numval($symb) << 10;
9158: my $namechck=unpack("%32S*",$username.' ');
9159:
9160: my $nameseed=numval($username) << 21;
1.501 albertel 9161: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9162: my $courseseed=unpack("%32S*",$courseid.' ');
9163:
9164: my $num1=$symbchck+$symbseed+$namechck;
9165: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9166: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9167: #&logthis("rndseed :$num:$symb");
1.803 albertel 9168: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9169: return "$num1,$num2";
9170: }
9171: }
9172:
9173: sub rndseed_64bit3 {
9174: my ($symb,$courseid,$domain,$username)=@_;
9175: {
9176: use integer;
9177: # strings need to be an even # of cahracters long, it it is odd the
9178: # last characters gets thrown away
9179: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9180: my $symbseed=numval2($symb) << 10;
9181: my $namechck=unpack("%32S*",$username.' ');
9182:
9183: my $nameseed=numval2($username) << 21;
1.443 albertel 9184: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9185: my $courseseed=unpack("%32S*",$courseid.' ');
9186:
9187: my $num1=$symbchck+$symbseed+$namechck;
9188: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9189: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9190: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9191: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9192:
1.503 albertel 9193: return "$num1:$num2";
1.443 albertel 9194: }
9195: }
9196:
1.575 albertel 9197: sub rndseed_64bit4 {
9198: my ($symb,$courseid,$domain,$username)=@_;
9199: {
9200: use integer;
9201: # strings need to be an even # of cahracters long, it it is odd the
9202: # last characters gets thrown away
9203: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9204: my $symbseed=numval3($symb) << 10;
9205: my $namechck=unpack("%32S*",$username.' ');
9206:
9207: my $nameseed=numval3($username) << 21;
9208: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9209: my $courseseed=unpack("%32S*",$courseid.' ');
9210:
9211: my $num1=$symbchck+$symbseed+$namechck;
9212: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9213: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9214: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9215: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9216:
9217: return "$num1:$num2";
9218: }
9219: }
9220:
1.675 albertel 9221: sub rndseed_64bit5 {
9222: my ($symb,$courseid,$domain,$username)=@_;
9223: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9224: return "$num1:$num2";
9225: }
9226:
1.366 albertel 9227: sub rndseed_CODE_64bit {
9228: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9229: {
1.366 albertel 9230: use integer;
1.443 albertel 9231: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9232: my $symbseed=numval2($symb);
1.491 albertel 9233: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9234: my $CODEseed=numval(&getCODE());
1.443 albertel 9235: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9236: my $num1=$symbseed+$CODEchck;
9237: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9238: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9239: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9240: if ($_64bit) { $num1=(($num1<<32)>>32); }
9241: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9242: return "$num1:$num2";
1.366 albertel 9243: }
9244: }
9245:
1.575 albertel 9246: sub rndseed_CODE_64bit4 {
9247: my ($symb,$courseid,$domain,$username)=@_;
9248: {
9249: use integer;
9250: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9251: my $symbseed=numval3($symb);
9252: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9253: my $CODEseed=numval3(&getCODE());
9254: my $courseseed=unpack("%32S*",$courseid.' ');
9255: my $num1=$symbseed+$CODEchck;
9256: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9257: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9258: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9259: if ($_64bit) { $num1=(($num1<<32)>>32); }
9260: if ($_64bit) { $num2=(($num2<<32)>>32); }
9261: return "$num1:$num2";
9262: }
9263: }
9264:
1.675 albertel 9265: sub rndseed_CODE_64bit5 {
9266: my ($symb,$courseid,$domain,$username)=@_;
9267: my $code = &getCODE();
9268: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9269: return "$num1:$num2";
9270: }
9271:
1.366 albertel 9272: sub setup_random_from_rndseed {
9273: my ($rndseed)=@_;
1.503 albertel 9274: if ($rndseed =~/([,:])/) {
9275: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9276: &Math::Random::random_set_seed(abs($num1),abs($num2));
9277: } else {
9278: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9279: }
1.36 albertel 9280: }
9281:
1.474 albertel 9282: sub latest_receipt_algorithm_id {
1.835 albertel 9283: return 'receipt3';
1.474 albertel 9284: }
9285:
1.480 www 9286: sub recunique {
9287: my $fucourseid=shift;
9288: my $unique;
1.835 albertel 9289: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9290: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9291: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9292: } else {
9293: $unique=$perlvar{'lonReceipt'};
9294: }
9295: return unpack("%32C*",$unique);
9296: }
9297:
9298: sub recprefix {
9299: my $fucourseid=shift;
9300: my $prefix;
1.835 albertel 9301: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9302: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9303: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9304: } else {
9305: $prefix=$perlvar{'lonHostID'};
9306: }
9307: return unpack("%32C*",$prefix);
9308: }
9309:
1.76 www 9310: sub ireceipt {
1.474 albertel 9311: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9312:
9313: my $return =&recprefix($fucourseid).'-';
9314:
9315: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9316: $env{'request.state'} eq 'construct') {
9317: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9318: return $return;
9319: }
9320:
1.76 www 9321: my $cuname=unpack("%32C*",$funame);
9322: my $cudom=unpack("%32C*",$fudom);
9323: my $cucourseid=unpack("%32C*",$fucourseid);
9324: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9325: my $cunique=&recunique($fucourseid);
1.474 albertel 9326: my $cpart=unpack("%32S*",$part);
1.835 albertel 9327: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9328:
1.790 albertel 9329: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9330:
9331: $return.= ($cunique%$cuname+
9332: $cunique%$cudom+
9333: $cusymb%$cuname+
9334: $cusymb%$cudom+
9335: $cucourseid%$cuname+
9336: $cucourseid%$cudom+
9337: $cpart%$cuname+
9338: $cpart%$cudom);
9339: } else {
9340: $return.= ($cunique%$cuname+
9341: $cunique%$cudom+
9342: $cusymb%$cuname+
9343: $cusymb%$cudom+
9344: $cucourseid%$cuname+
9345: $cucourseid%$cudom);
9346: }
9347: return $return;
1.76 www 9348: }
9349:
9350: sub receipt {
1.474 albertel 9351: my ($part)=@_;
1.790 albertel 9352: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9353: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9354: }
1.260 ng 9355:
1.790 albertel 9356: sub whichuser {
9357: my ($passedsymb)=@_;
9358: my ($symb,$courseid,$domain,$name,$publicuser);
9359: if (defined($env{'form.grade_symb'})) {
9360: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9361: my $allowed=&allowed('vgr',$tmp_courseid);
9362: if (!$allowed &&
9363: exists($env{'request.course.sec'}) &&
9364: $env{'request.course.sec'} !~ /^\s*$/) {
9365: $allowed=&allowed('vgr',$tmp_courseid.
9366: '/'.$env{'request.course.sec'});
9367: }
9368: if ($allowed) {
9369: ($symb)=&get_env_multiple('form.grade_symb');
9370: $courseid=$tmp_courseid;
9371: ($domain)=&get_env_multiple('form.grade_domain');
9372: ($name)=&get_env_multiple('form.grade_username');
9373: return ($symb,$courseid,$domain,$name,$publicuser);
9374: }
9375: }
9376: if (!$passedsymb) {
9377: $symb=&symbread();
9378: } else {
9379: $symb=$passedsymb;
9380: }
9381: $courseid=$env{'request.course.id'};
9382: $domain=$env{'user.domain'};
9383: $name=$env{'user.name'};
9384: if ($name eq 'public' && $domain eq 'public') {
9385: if (!defined($env{'form.username'})) {
9386: $env{'form.username'}.=time.rand(10000000);
9387: }
9388: $name.=$env{'form.username'};
9389: }
9390: return ($symb,$courseid,$domain,$name,$publicuser);
9391:
9392: }
9393:
1.36 albertel 9394: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9395: # returns either the contents of the file or
9396: # -1 if the file doesn't exist
1.481 raeburn 9397: #
9398: # if the target is a file that was uploaded via DOCS,
9399: # a check will be made to see if a current copy exists on the local server,
9400: # if it does this will be served, otherwise a copy will be retrieved from
9401: # the home server for the course and stored in /home/httpd/html/userfiles on
9402: # the local server.
1.472 albertel 9403:
1.36 albertel 9404: sub getfile {
1.538 albertel 9405: my ($file) = @_;
1.609 banghart 9406: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9407: &repcopy($file);
9408: return &readfile($file);
9409: }
9410:
9411: sub repcopy_userfile {
9412: my ($file)=@_;
1.609 banghart 9413: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9414: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9415: my ($cdom,$cnum,$filename) =
1.811 albertel 9416: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9417: my $uri="/uploaded/$cdom/$cnum/$filename";
9418: if (-e "$file") {
1.828 www 9419: # we already have a local copy, check it out
1.538 albertel 9420: my @fileinfo = stat($file);
1.828 www 9421: my $rtncode;
9422: my $info;
1.538 albertel 9423: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9424: if ($lwpresp ne 'ok') {
1.828 www 9425: # there is no such file anymore, even though we had a local copy
1.482 albertel 9426: if ($rtncode eq '404') {
1.538 albertel 9427: unlink($file);
1.482 albertel 9428: }
9429: return -1;
9430: }
9431: if ($info < $fileinfo[9]) {
1.828 www 9432: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9433: return 'ok';
1.828 www 9434: } else {
9435: # the file is outdated, get rid of it
9436: unlink($file);
1.482 albertel 9437: }
1.828 www 9438: }
9439: # one way or the other, at this point, we don't have the file
9440: # construct the correct path for the file
9441: my @parts = ($cdom,$cnum);
9442: if ($filename =~ m|^(.+)/[^/]+$|) {
9443: push @parts, split(/\//,$1);
9444: }
9445: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9446: foreach my $part (@parts) {
9447: $path .= '/'.$part;
9448: if (!-e $path) {
9449: mkdir($path,0770);
1.482 albertel 9450: }
9451: }
1.828 www 9452: # now the path exists for sure
9453: # get a user agent
9454: my $ua=new LWP::UserAgent;
9455: my $transferfile=$file.'.in.transfer';
9456: # FIXME: this should flock
9457: if (-e $transferfile) { return 'ok'; }
9458: my $request;
9459: $uri=~s/^\///;
1.980 raeburn 9460: my $homeserver = &homeserver($cnum,$cdom);
9461: my $protocol = $protocol{$homeserver};
9462: $protocol = 'http' if ($protocol ne 'https');
9463: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9464: my $response=$ua->request($request,$transferfile);
9465: # did it work?
9466: if ($response->is_error()) {
9467: unlink($transferfile);
9468: &logthis("Userfile repcopy failed for $uri");
9469: return -1;
9470: }
9471: # worked, rename the transfer file
9472: rename($transferfile,$file);
1.607 raeburn 9473: return 'ok';
1.481 raeburn 9474: }
9475:
1.517 albertel 9476: sub tokenwrapper {
9477: my $uri=shift;
1.980 raeburn 9478: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9479: $uri=~s|^/||;
1.620 albertel 9480: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9481: my $token=$1;
1.552 albertel 9482: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9483: if ($udom && $uname && $file) {
9484: $file=~s|(\?\.*)*$||;
1.949 raeburn 9485: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9486: my $homeserver = &homeserver($uname,$udom);
9487: my $protocol = $protocol{$homeserver};
9488: $protocol = 'http' if ($protocol ne 'https');
9489: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9490: (($uri=~/\?/)?'&':'?').'token='.$token.
9491: '&tokenissued='.$perlvar{'lonHostID'};
9492: } else {
9493: return '/adm/notfound.html';
9494: }
9495: }
9496:
1.828 www 9497: # call with reqtype HEAD: get last modification time
9498: # call with reqtype GET: get the file contents
9499: # Do not call this with reqtype GET for large files! It loads everything into memory
9500: #
1.481 raeburn 9501: sub getuploaded {
9502: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9503: $uri=~s/^\///;
1.980 raeburn 9504: my $homeserver = &homeserver($cnum,$cdom);
9505: my $protocol = $protocol{$homeserver};
9506: $protocol = 'http' if ($protocol ne 'https');
9507: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9508: my $ua=new LWP::UserAgent;
9509: my $request=new HTTP::Request($reqtype,$uri);
9510: my $response=$ua->request($request);
9511: $$rtncode = $response->code;
1.482 albertel 9512: if (! $response->is_success()) {
9513: return 'failed';
9514: }
9515: if ($reqtype eq 'HEAD') {
1.486 www 9516: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9517: } elsif ($reqtype eq 'GET') {
9518: $$info = $response->content;
1.472 albertel 9519: }
1.482 albertel 9520: return 'ok';
1.36 albertel 9521: }
9522:
1.481 raeburn 9523: sub readfile {
9524: my $file = shift;
9525: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9526: my $fh;
9527: open($fh,"<$file");
9528: my $a='';
1.800 albertel 9529: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9530: return $a;
9531: }
9532:
1.36 albertel 9533: sub filelocation {
1.590 banghart 9534: my ($dir,$file) = @_;
9535: my $location;
9536: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9537:
9538: if ($file =~ m-^/adm/-) {
9539: $file=~s-^/adm/wrapper/-/-;
9540: $file=~s-^/adm/coursedocs/showdoc/-/-;
9541: }
1.882 albertel 9542:
1.590 banghart 9543: if ($file=~m:^/~:) { # is a contruction space reference
9544: $location = $file;
9545: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9546: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9547: # is a correct contruction space reference
9548: $location = $file;
1.956 raeburn 9549: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9550: $location = $file;
1.609 banghart 9551: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9552: my ($udom,$uname,$filename)=
1.811 albertel 9553: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9554: my $home=&homeserver($uname,$udom);
9555: my $is_me=0;
9556: my @ids=¤t_machine_ids();
9557: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9558: if ($is_me) {
1.955 raeburn 9559: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9560: } else {
9561: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9562: $udom.'/'.$uname.'/'.$filename;
9563: }
1.882 albertel 9564: } elsif ($file =~ m-^/adm/-) {
9565: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9566: } else {
9567: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9568: $file=~s:^/res/:/:;
9569: if ( !( $file =~ m:^/:) ) {
9570: $location = $dir. '/'.$file;
9571: } else {
9572: $location = '/home/httpd/html/res'.$file;
9573: }
1.59 albertel 9574: }
1.590 banghart 9575: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9576: while ($location=~m{/\.\./}) {
9577: if ($location =~ m{/[^/]+/\.\./}) {
9578: $location=~ s{/[^/]+/\.\./}{/}g;
9579: } else {
9580: $location=~ s{/\.\./}{/}g;
9581: }
9582: } #remove dir/..
1.590 banghart 9583: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9584: return $location;
1.46 www 9585: }
1.36 albertel 9586:
1.46 www 9587: sub hreflocation {
9588: my ($dir,$file)=@_;
1.980 raeburn 9589: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9590: $file=filelocation($dir,$file);
1.700 albertel 9591: } elsif ($file=~m-^/adm/-) {
9592: $file=~s-^/adm/wrapper/-/-;
9593: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9594: }
9595: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9596: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9597: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9598: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9599: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9600: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9601: -/uploaded/$1/$2/-x;
1.46 www 9602: }
1.913 albertel 9603: if ($file=~ m{^/userfiles/}) {
9604: $file =~ s{^/userfiles/}{/uploaded/};
9605: }
1.462 albertel 9606: return $file;
1.465 albertel 9607: }
9608:
9609: sub current_machine_domains {
1.853 albertel 9610: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9611: }
9612:
9613: sub machine_domains {
9614: my ($hostname) = @_;
1.465 albertel 9615: my @domains;
1.838 albertel 9616: my %hostname = &all_hostnames();
1.465 albertel 9617: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9618: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9619: if ($hostname eq $name) {
1.844 albertel 9620: push(@domains,&host_domain($id));
1.465 albertel 9621: }
9622: }
9623: return @domains;
9624: }
9625:
9626: sub current_machine_ids {
1.853 albertel 9627: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9628: }
9629:
9630: sub machine_ids {
9631: my ($hostname) = @_;
9632: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9633: my @ids;
1.888 albertel 9634: my %name_to_host = &all_names();
1.889 albertel 9635: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9636: return @{ $name_to_host{$hostname} };
9637: }
9638: return;
1.31 www 9639: }
9640:
1.824 raeburn 9641: sub additional_machine_domains {
9642: my @domains;
9643: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9644: while( my $line = <$fh>) {
9645: $line =~ s/\s//g;
9646: push(@domains,$line);
9647: }
9648: return @domains;
9649: }
9650:
9651: sub default_login_domain {
9652: my $domain = $perlvar{'lonDefDomain'};
9653: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9654: foreach my $posdom (¤t_machine_domains(),
9655: &additional_machine_domains()) {
9656: if (lc($posdom) eq lc($testdomain)) {
9657: $domain=$posdom;
9658: last;
9659: }
9660: }
9661: return $domain;
9662: }
9663:
1.31 www 9664: # ------------------------------------------------------------- Declutters URLs
9665:
9666: sub declutter {
9667: my $thisfn=shift;
1.569 albertel 9668: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9669: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9670: $thisfn=~s/^\///;
1.697 albertel 9671: $thisfn=~s|^adm/wrapper/||;
9672: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9673: $thisfn=~s/^res\///;
1.1032 raeburn 9674: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9675: $thisfn=~s/\?.+$//;
9676: }
1.268 www 9677: return $thisfn;
9678: }
9679:
9680: # ------------------------------------------------------------- Clutter up URLs
9681:
9682: sub clutter {
9683: my $thisfn='/'.&declutter(shift);
1.887 albertel 9684: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9685: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9686: $thisfn='/res'.$thisfn;
9687: }
1.1031 raeburn 9688: if ($thisfn !~m|^/adm|) {
9689: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9690: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9691: } else {
9692: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9693: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9694: if ($embstyle eq 'ssi'
9695: || ($embstyle eq 'hdn')
9696: || ($embstyle eq 'rat')
9697: || ($embstyle eq 'prv')
9698: || ($embstyle eq 'ign')) {
9699: #do nothing with these
9700: } elsif (($embstyle eq 'img')
1.695 albertel 9701: || ($embstyle eq 'emb')
9702: || ($embstyle eq 'wrp')) {
9703: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9704: } elsif ($embstyle eq 'unk'
9705: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9706: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9707: } else {
1.718 www 9708: # &logthis("Got a blank emb style");
1.695 albertel 9709: }
1.694 albertel 9710: }
9711: }
1.31 www 9712: return $thisfn;
1.12 www 9713: }
9714:
1.787 albertel 9715: sub clutter_with_no_wrapper {
9716: my $uri = &clutter(shift);
9717: if ($uri =~ m-^/adm/-) {
9718: $uri =~ s-^/adm/wrapper/-/-;
9719: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9720: }
9721: return $uri;
9722: }
9723:
1.557 albertel 9724: sub freeze_escape {
9725: my ($value)=@_;
9726: if (ref($value)) {
9727: $value=&nfreeze($value);
9728: return '__FROZEN__'.&escape($value);
9729: }
9730: return &escape($value);
9731: }
9732:
1.11 www 9733:
1.557 albertel 9734: sub thaw_unescape {
9735: my ($value)=@_;
9736: if ($value =~ /^__FROZEN__/) {
9737: substr($value,0,10,undef);
9738: $value=&unescape($value);
9739: return &thaw($value);
9740: }
9741: return &unescape($value);
9742: }
9743:
1.436 albertel 9744: sub correct_line_ends {
9745: my ($result)=@_;
9746: $$result =~s/\r\n/\n/mg;
9747: $$result =~s/\r/\n/mg;
1.415 albertel 9748: }
1.1 albertel 9749: # ================================================================ Main Program
9750:
1.184 www 9751: sub goodbye {
1.204 albertel 9752: &logthis("Starting Shut down");
1.443 albertel 9753: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9754: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9755: #converted
1.599 albertel 9756: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9757: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9758: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9759: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9760: #1.1 only
1.870 albertel 9761: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9762: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9763: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9764: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9765: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9766: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9767: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9768: &flushcourselogs();
9769: &logthis("Shutting down");
9770: }
9771:
1.852 albertel 9772: sub get_dns {
1.869 albertel 9773: my ($url,$func,$ignore_cache) = @_;
9774: if (!$ignore_cache) {
9775: my ($content,$cached)=
9776: &Apache::lonnet::is_cached_new('dns',$url);
9777: if ($cached) {
9778: &$func($content);
9779: return;
9780: }
9781: }
9782:
9783: my %alldns;
1.852 albertel 9784: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9785: foreach my $dns (<$config>) {
9786: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9787: my $line = $1;
9788: my ($host,$protocol) = split(/:/,$line);
9789: if ($protocol ne 'https') {
9790: $protocol = 'http';
9791: }
9792: $alldns{$host} = $protocol;
1.869 albertel 9793: }
9794: while (%alldns) {
9795: my ($dns) = keys(%alldns);
1.852 albertel 9796: my $ua=new LWP::UserAgent;
1.979 raeburn 9797: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9798: my $response=$ua->request($request);
1.979 raeburn 9799: delete($alldns{$dns});
1.852 albertel 9800: next if ($response->is_error());
9801: my @content = split("\n",$response->content);
1.869 albertel 9802: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9803: &$func(\@content);
1.869 albertel 9804: return;
1.852 albertel 9805: }
9806: close($config);
1.871 albertel 9807: my $which = (split('/',$url))[3];
9808: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9809: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9810: my @content = <$config>;
9811: &$func(\@content);
9812: return;
1.852 albertel 9813: }
1.327 albertel 9814: # ------------------------------------------------------------ Read domain file
9815: {
1.852 albertel 9816: my $loaded;
1.846 albertel 9817: my %domain;
9818:
1.852 albertel 9819: sub parse_domain_tab {
9820: my ($lines) = @_;
9821: foreach my $line (@$lines) {
9822: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9823:
1.846 albertel 9824: chomp($line);
1.852 albertel 9825: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9826: my %this_domain;
9827: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9828: 'lang_def', 'city', 'longi', 'lati',
9829: 'primary') {
9830: $this_domain{$field} = shift(@elements);
9831: }
9832: $domain{$name} = \%this_domain;
1.852 albertel 9833: }
9834: }
1.864 albertel 9835:
9836: sub reset_domain_info {
9837: undef($loaded);
9838: undef(%domain);
9839: }
9840:
1.852 albertel 9841: sub load_domain_tab {
1.869 albertel 9842: my ($ignore_cache) = @_;
9843: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 9844: my $fh;
9845: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9846: my @lines = <$fh>;
9847: &parse_domain_tab(\@lines);
1.448 albertel 9848: }
1.852 albertel 9849: close($fh);
9850: $loaded = 1;
1.327 albertel 9851: }
1.846 albertel 9852:
9853: sub domain {
1.852 albertel 9854: &load_domain_tab() if (!$loaded);
9855:
1.846 albertel 9856: my ($name,$what) = @_;
9857: return if ( !exists($domain{$name}) );
9858:
9859: if (!$what) {
9860: return $domain{$name}{'description'};
9861: }
9862: return $domain{$name}{$what};
9863: }
1.974 raeburn 9864:
9865: sub domain_info {
9866: &load_domain_tab() if (!$loaded);
9867: return %domain;
9868: }
9869:
1.327 albertel 9870: }
9871:
9872:
1.1 albertel 9873: # ------------------------------------------------------------- Read hosts file
9874: {
1.838 albertel 9875: my %hostname;
1.844 albertel 9876: my %hostdom;
1.845 albertel 9877: my %libserv;
1.852 albertel 9878: my $loaded;
1.888 albertel 9879: my %name_to_host;
1.852 albertel 9880:
9881: sub parse_hosts_tab {
9882: my ($file) = @_;
9883: foreach my $configline (@$file) {
9884: next if ($configline =~ /^(\#|\s*$ )/x);
9885: next if ($configline =~ /^\^/);
9886: chomp($configline);
1.968 raeburn 9887: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852 albertel 9888: $name=~s/\s//g;
9889: if ($id && $domain && $role && $name) {
9890: $hostname{$id}=$name;
1.888 albertel 9891: push(@{$name_to_host{$name}}, $id);
1.852 albertel 9892: $hostdom{$id}=$domain;
9893: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 9894: if (defined($protocol)) {
9895: if ($protocol eq 'https') {
9896: $protocol{$id} = $protocol;
9897: } else {
9898: $protocol{$id} = 'http';
9899: }
1.968 raeburn 9900: } else {
1.969 raeburn 9901: $protocol{$id} = 'http';
1.968 raeburn 9902: }
1.852 albertel 9903: }
9904: }
9905: }
1.864 albertel 9906:
9907: sub reset_hosts_info {
1.897 albertel 9908: &purge_remembered();
1.864 albertel 9909: &reset_domain_info();
9910: &reset_hosts_ip_info();
1.892 albertel 9911: undef(%name_to_host);
1.864 albertel 9912: undef(%hostname);
9913: undef(%hostdom);
9914: undef(%libserv);
9915: undef($loaded);
9916: }
1.1 albertel 9917:
1.852 albertel 9918: sub load_hosts_tab {
1.869 albertel 9919: my ($ignore_cache) = @_;
9920: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 9921: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9922: my @config = <$config>;
9923: &parse_hosts_tab(\@config);
9924: close($config);
9925: $loaded=1;
1.1 albertel 9926: }
1.852 albertel 9927:
1.838 albertel 9928: sub hostname {
1.852 albertel 9929: &load_hosts_tab() if (!$loaded);
9930:
1.838 albertel 9931: my ($lonid) = @_;
9932: return $hostname{$lonid};
9933: }
1.845 albertel 9934:
1.838 albertel 9935: sub all_hostnames {
1.852 albertel 9936: &load_hosts_tab() if (!$loaded);
9937:
1.838 albertel 9938: return %hostname;
9939: }
1.845 albertel 9940:
1.888 albertel 9941: sub all_names {
9942: &load_hosts_tab() if (!$loaded);
9943:
9944: return %name_to_host;
9945: }
9946:
1.974 raeburn 9947: sub all_host_domain {
9948: &load_hosts_tab() if (!$loaded);
9949: return %hostdom;
9950: }
9951:
1.845 albertel 9952: sub is_library {
1.852 albertel 9953: &load_hosts_tab() if (!$loaded);
9954:
1.845 albertel 9955: return exists($libserv{$_[0]});
9956: }
9957:
9958: sub all_library {
1.852 albertel 9959: &load_hosts_tab() if (!$loaded);
9960:
1.845 albertel 9961: return %libserv;
9962: }
9963:
1.1056.4.2 raeburn 9964: sub unique_library {
9965: #2x reverse removes all hostnames that appear more than once
9966: my %unique = reverse &all_library();
9967: return reverse %unique;
9968: }
9969:
1.841 albertel 9970: sub get_servers {
1.852 albertel 9971: &load_hosts_tab() if (!$loaded);
9972:
1.841 albertel 9973: my ($domain,$type) = @_;
9974: my %possible_hosts = ($type eq 'library') ? %libserv
9975: : %hostname;
9976: my %result;
1.842 albertel 9977: if (ref($domain) eq 'ARRAY') {
9978: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 9979: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 9980: $result{$host} = $hostname;
9981: }
9982: }
9983: } else {
9984: while ( my ($host,$hostname) = each(%possible_hosts)) {
9985: if ($hostdom{$host} eq $domain) {
9986: $result{$host} = $hostname;
9987: }
1.841 albertel 9988: }
9989: }
9990: return %result;
9991: }
1.845 albertel 9992:
1.1056.4.2 raeburn 9993: sub get_unique_servers {
9994: my %unique = reverse &get_servers(@_);
9995: return reverse %unique;
9996: }
9997:
1.844 albertel 9998: sub host_domain {
1.852 albertel 9999: &load_hosts_tab() if (!$loaded);
10000:
1.844 albertel 10001: my ($lonid) = @_;
10002: return $hostdom{$lonid};
10003: }
10004:
1.841 albertel 10005: sub all_domains {
1.852 albertel 10006: &load_hosts_tab() if (!$loaded);
10007:
1.841 albertel 10008: my %seen;
10009: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10010: return @uniq;
10011: }
1.1056.4.3! raeburn 10012:
! 10013: sub internet_dom {
! 10014: &load_hosts_tab() if (!$loaded);
! 10015:
! 10016: my ($lonid) = @_;
! 10017: return $internetdom{$lonid};
! 10018: }
! 10019:
1.1 albertel 10020: }
10021:
1.847 albertel 10022: {
10023: my %iphost;
1.856 albertel 10024: my %name_to_ip;
10025: my %lonid_to_ip;
1.869 albertel 10026:
1.847 albertel 10027: sub get_hosts_from_ip {
10028: my ($ip) = @_;
10029: my %iphosts = &get_iphost();
10030: if (ref($iphosts{$ip})) {
10031: return @{$iphosts{$ip}};
10032: }
10033: return;
1.839 albertel 10034: }
1.864 albertel 10035:
10036: sub reset_hosts_ip_info {
10037: undef(%iphost);
10038: undef(%name_to_ip);
10039: undef(%lonid_to_ip);
10040: }
1.856 albertel 10041:
10042: sub get_host_ip {
10043: my ($lonid) = @_;
10044: if (exists($lonid_to_ip{$lonid})) {
10045: return $lonid_to_ip{$lonid};
10046: }
10047: my $name=&hostname($lonid);
10048: my $ip = gethostbyname($name);
10049: return if (!$ip || length($ip) ne 4);
10050: $ip=inet_ntoa($ip);
10051: $name_to_ip{$name} = $ip;
10052: $lonid_to_ip{$lonid} = $ip;
10053: return $ip;
10054: }
1.847 albertel 10055:
10056: sub get_iphost {
1.869 albertel 10057: my ($ignore_cache) = @_;
1.894 albertel 10058:
1.869 albertel 10059: if (!$ignore_cache) {
10060: if (%iphost) {
10061: return %iphost;
10062: }
10063: my ($ip_info,$cached)=
10064: &Apache::lonnet::is_cached_new('iphost','iphost');
10065: if ($cached) {
10066: %iphost = %{$ip_info->[0]};
10067: %name_to_ip = %{$ip_info->[1]};
10068: %lonid_to_ip = %{$ip_info->[2]};
10069: return %iphost;
10070: }
10071: }
1.894 albertel 10072:
10073: # get yesterday's info for fallback
10074: my %old_name_to_ip;
10075: my ($ip_info,$cached)=
10076: &Apache::lonnet::is_cached_new('iphost','iphost');
10077: if ($cached) {
10078: %old_name_to_ip = %{$ip_info->[1]};
10079: }
10080:
1.888 albertel 10081: my %name_to_host = &all_names();
10082: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10083: my $ip;
10084: if (!exists($name_to_ip{$name})) {
10085: $ip = gethostbyname($name);
10086: if (!$ip || length($ip) ne 4) {
1.894 albertel 10087: if (defined($old_name_to_ip{$name})) {
10088: $ip = $old_name_to_ip{$name};
10089: &logthis("Can't find $name defaulting to old $ip");
10090: } else {
10091: &logthis("Name $name no IP found");
10092: next;
10093: }
10094: } else {
10095: $ip=inet_ntoa($ip);
1.847 albertel 10096: }
10097: $name_to_ip{$name} = $ip;
10098: } else {
10099: $ip = $name_to_ip{$name};
1.653 albertel 10100: }
1.888 albertel 10101: foreach my $id (@{ $name_to_host{$name} }) {
10102: $lonid_to_ip{$id} = $ip;
10103: }
10104: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10105: }
1.869 albertel 10106: &Apache::lonnet::do_cache_new('iphost','iphost',
10107: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10108: 48*60*60);
1.869 albertel 10109:
1.847 albertel 10110: return %iphost;
1.598 albertel 10111: }
10112:
1.992 raeburn 10113: #
10114: # Given a DNS returns the loncapa host name for that DNS
10115: #
10116: sub host_from_dns {
10117: my ($dns) = @_;
10118: my @hosts;
10119: my $ip;
10120:
1.993 raeburn 10121: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10122: $ip = $name_to_ip{$dns};
10123: }
10124: if (!$ip) {
10125: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10126: if (length($ip) == 4) {
10127: $ip = &IO::Socket::inet_ntoa($ip);
10128: }
10129: }
10130: if ($ip) {
10131: @hosts = get_hosts_from_ip($ip);
10132: return $hosts[0];
10133: }
10134: return undef;
1.986 foxr 10135: }
1.992 raeburn 10136:
1.1056.4.3! raeburn 10137: sub get_internet_names {
! 10138: my ($lonid) = @_;
! 10139: return if ($lonid eq '');
! 10140: my ($idnref,$cached)=
! 10141: &Apache::lonnet::is_cached_new('internetnames',$lonid);
! 10142: if ($cached) {
! 10143: return $idnref;
! 10144: }
! 10145: my $ip = &get_host_ip($lonid);
! 10146: my @hosts = &get_hosts_from_ip($ip);
! 10147: my %iphost = &get_iphost();
! 10148: my (@idns,%seen);
! 10149: foreach my $id (@hosts) {
! 10150: my $dom = &host_domain($id);
! 10151: my $prim_id = &domain($dom,'primary');
! 10152: my $prim_ip = &get_host_ip($prim_id);
! 10153: next if ($seen{$prim_ip});
! 10154: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
! 10155: foreach my $id (@{$iphost{$prim_ip}}) {
! 10156: my $intdom = &internet_dom($id);
! 10157: unless (grep(/^\Q$intdom\E$/,@idns)) {
! 10158: push(@idns,$intdom);
! 10159: }
! 10160: }
! 10161: }
! 10162: $seen{$prim_ip} = 1;
! 10163: }
! 10164: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
! 10165: }
! 10166:
! 10167: }
! 10168:
! 10169: sub all_loncaparevs {
! 10170: 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);
1.986 foxr 10171: }
10172:
1.862 albertel 10173: BEGIN {
10174:
10175: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10176: unless ($readit) {
10177: {
10178: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10179: %perlvar = (%perlvar,%{$configvars});
10180: }
10181:
10182:
1.1 albertel 10183: # ------------------------------------------------------ Read spare server file
10184: {
1.448 albertel 10185: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10186:
10187: while (my $configline=<$config>) {
10188: chomp($configline);
1.284 matthew 10189: if ($configline) {
1.784 albertel 10190: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10191: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10192: push(@{ $spareid{$type} }, $host);
1.1 albertel 10193: }
10194: }
1.448 albertel 10195: close($config);
1.1 albertel 10196: }
1.11 www 10197: # ------------------------------------------------------------ Read permissions
10198: {
1.448 albertel 10199: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10200:
10201: while (my $configline=<$config>) {
1.448 albertel 10202: chomp($configline);
10203: if ($configline) {
10204: my ($role,$perm)=split(/ /,$configline);
10205: if ($perm ne '') { $pr{$role}=$perm; }
10206: }
1.11 www 10207: }
1.448 albertel 10208: close($config);
1.11 www 10209: }
10210:
10211: # -------------------------------------------- Read plain texts for permissions
10212: {
1.448 albertel 10213: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10214:
10215: while (my $configline=<$config>) {
1.448 albertel 10216: chomp($configline);
10217: if ($configline) {
1.742 raeburn 10218: my ($short,@plain)=split(/:/,$configline);
10219: %{$prp{$short}} = ();
10220: if (@plain > 0) {
10221: $prp{$short}{'std'} = $plain[0];
10222: for (my $i=1; $i<@plain; $i++) {
10223: $prp{$short}{'alt'.$i} = $plain[$i];
10224: }
10225: }
1.448 albertel 10226: }
1.135 www 10227: }
1.448 albertel 10228: close($config);
1.135 www 10229: }
10230:
10231: # ---------------------------------------------------------- Read package table
10232: {
1.448 albertel 10233: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10234:
10235: while (my $configline=<$config>) {
1.483 albertel 10236: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10237: chomp($configline);
10238: my ($short,$plain)=split(/:/,$configline);
10239: my ($pack,$name)=split(/\&/,$short);
10240: if ($plain ne '') {
10241: $packagetab{$pack.'&'.$name.'&name'}=$name;
10242: $packagetab{$short}=$plain;
10243: }
1.11 www 10244: }
1.448 albertel 10245: close($config);
1.329 matthew 10246: }
10247:
1.1056.4.3! raeburn 10248: # ---------------------------------------------------------- Read loncaparev table
! 10249: {
! 10250: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
! 10251: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
! 10252: while (my $configline=<$config>) {
! 10253: chomp($configline);
! 10254: my ($hostid,$loncaparev)=split(/:/,$configline);
! 10255: $loncaparevs{$hostid}=$loncaparev;
! 10256: }
! 10257: close($config);
! 10258: }
! 10259: }
! 10260: }
! 10261:
! 10262: # ---------------------------------------------------------- Read serverhostID table
! 10263: {
! 10264: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
! 10265: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
! 10266: while (my $configline=<$config>) {
! 10267: chomp($configline);
! 10268: my ($name,$id)=split(/:/,$configline);
! 10269: $serverhomeIDs{$name}=$id;
! 10270: }
! 10271: close($config);
! 10272: }
! 10273: }
! 10274: }
! 10275:
1.329 matthew 10276: # ------------- set up temporary directory
10277: {
10278: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10279:
1.11 www 10280: }
10281:
1.794 albertel 10282: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10283: 'compress_threshold'=> 20_000,
10284: });
1.185 www 10285:
1.281 www 10286: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10287: $dumpcount=0;
1.958 www 10288: $locknum=0;
1.22 www 10289:
1.163 harris41 10290: &logtouch();
1.672 albertel 10291: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10292: $readit=1;
1.564 albertel 10293: {
10294: use integer;
10295: my $test=(2**32)+1;
1.568 albertel 10296: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10297: &logthis(" Detected 64bit platform ($_64bit)");
10298: }
1.195 www 10299: }
1.1 albertel 10300: }
1.179 www 10301:
1.1 albertel 10302: 1;
1.191 harris41 10303: __END__
10304:
1.243 albertel 10305: =pod
10306:
1.191 harris41 10307: =head1 NAME
10308:
1.243 albertel 10309: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10310:
10311: =head1 SYNOPSIS
10312:
1.243 albertel 10313: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10314:
10315: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10316:
1.243 albertel 10317: Common parameters:
10318:
10319: =over 4
10320:
10321: =item *
10322:
10323: $uname : an internal username (if $cname expecting a course Id specifically)
10324:
10325: =item *
10326:
10327: $udom : a domain (if $cdom expecting a course's domain specifically)
10328:
10329: =item *
10330:
10331: $symb : a resource instance identifier
10332:
10333: =item *
10334:
10335: $namespace : the name of a .db file that contains the data needed or
10336: being set.
10337:
10338: =back
10339:
1.394 bowersj2 10340: =head1 OVERVIEW
1.191 harris41 10341:
1.394 bowersj2 10342: lonnet provides subroutines which interact with the
10343: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10344: about classes, users, and resources.
1.243 albertel 10345:
10346: For many of these objects you can also use this to store data about
10347: them or modify them in various ways.
1.191 harris41 10348:
1.394 bowersj2 10349: =head2 Symbs
1.191 harris41 10350:
1.394 bowersj2 10351: To identify a specific instance of a resource, LON-CAPA uses symbols
10352: or "symbs"X<symb>. These identifiers are built from the URL of the
10353: map, the resource number of the resource in the map, and the URL of
10354: the resource itself. The latter is somewhat redundant, but might help
10355: if maps change.
10356:
10357: An example is
10358:
10359: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10360:
10361: The respective map entry is
10362:
10363: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10364: title="Problem 2">
10365: </resource>
10366:
10367: Symbs are used by the random number generator, as well as to store and
10368: restore data specific to a certain instance of for example a problem.
10369:
10370: =head2 Storing And Retrieving Data
10371:
10372: X<store()>X<cstore()>X<restore()>Three of the most important functions
10373: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10374: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10375: is is the non-critical message twin of cstore. These functions are for
10376: handlers to store a perl hash to a user's permanent data space in an
10377: easy manner, and to retrieve it again on another call. It is expected
10378: that a handler would use this once at the beginning to retrieve data,
10379: and then again once at the end to send only the new data back.
10380:
10381: The data is stored in the user's data directory on the user's
10382: homeserver under the ID of the course.
10383:
10384: The hash that is returned by restore will have all of the previous
10385: value for all of the elements of the hash.
10386:
10387: Example:
10388:
10389: #creating a hash
10390: my %hash;
10391: $hash{'foo'}='bar';
10392:
10393: #storing it
10394: &Apache::lonnet::cstore(\%hash);
10395:
10396: #changing a value
10397: $hash{'foo'}='notbar';
10398:
10399: #adding a new value
10400: $hash{'bar'}='foo';
10401: &Apache::lonnet::cstore(\%hash);
10402:
10403: #retrieving the hash
10404: my %history=&Apache::lonnet::restore();
10405:
10406: #print the hash
10407: foreach my $key (sort(keys(%history))) {
10408: print("\%history{$key} = $history{$key}");
10409: }
10410:
10411: Will print out:
1.191 harris41 10412:
1.394 bowersj2 10413: %history{1:foo} = bar
10414: %history{1:keys} = foo:timestamp
10415: %history{1:timestamp} = 990455579
10416: %history{2:bar} = foo
10417: %history{2:foo} = notbar
10418: %history{2:keys} = foo:bar:timestamp
10419: %history{2:timestamp} = 990455580
10420: %history{bar} = foo
10421: %history{foo} = notbar
10422: %history{timestamp} = 990455580
10423: %history{version} = 2
10424:
10425: Note that the special hash entries C<keys>, C<version> and
10426: C<timestamp> were added to the hash. C<version> will be equal to the
10427: total number of versions of the data that have been stored. The
10428: C<timestamp> attribute will be the UNIX time the hash was
10429: stored. C<keys> is available in every historical section to list which
10430: keys were added or changed at a specific historical revision of a
10431: hash.
10432:
10433: B<Warning>: do not store the hash that restore returns directly. This
10434: will cause a mess since it will restore the historical keys as if the
10435: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10436:
1.394 bowersj2 10437: Calling convention:
1.191 harris41 10438:
1.394 bowersj2 10439: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10440: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10441:
1.394 bowersj2 10442: For more detailed information, see lonnet specific documentation.
1.191 harris41 10443:
1.394 bowersj2 10444: =head1 RETURN MESSAGES
1.191 harris41 10445:
1.394 bowersj2 10446: =over 4
1.191 harris41 10447:
1.394 bowersj2 10448: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10449:
1.394 bowersj2 10450: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10451: when the connection is brought back up
1.191 harris41 10452:
1.394 bowersj2 10453: =item * B<con_failed>: unable to contact remote host and unable to save message
10454: for later delivery
1.191 harris41 10455:
1.967 bisitz 10456: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10457:
1.394 bowersj2 10458: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10459: that was requested
1.191 harris41 10460:
1.243 albertel 10461: =back
1.191 harris41 10462:
1.243 albertel 10463: =head1 PUBLIC SUBROUTINES
1.191 harris41 10464:
1.243 albertel 10465: =head2 Session Environment Functions
1.191 harris41 10466:
1.243 albertel 10467: =over 4
1.191 harris41 10468:
1.394 bowersj2 10469: =item *
10470: X<appenv()>
1.949 raeburn 10471: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10472: the user envirnoment file, and will be restored for each access this
1.620 albertel 10473: user makes during this session, also modifies the %env for the current
1.949 raeburn 10474: process. Optional rolesarrayref - if defined contains a reference to an array
10475: of roles which are exempt from the restriction on modifying user.role entries
10476: in the user's environment.db and in %env.
1.191 harris41 10477:
10478: =item *
1.394 bowersj2 10479: X<delenv()>
1.987 raeburn 10480: B<delenv($delthis,$regexp)>: removes all items from the session
10481: environment file that begin with $delthis. If the
10482: optional second arg - $regexp - is true, $delthis is treated as a
10483: regular expression, otherwise \Q$delthis\E is used.
10484: The values are also deleted from the current processes %env.
1.191 harris41 10485:
1.795 albertel 10486: =item * get_env_multiple($name)
10487:
10488: gets $name from the %env hash, it seemlessly handles the cases where multiple
10489: values may be defined and end up as an array ref.
10490:
10491: returns an array of values
10492:
1.243 albertel 10493: =back
10494:
10495: =head2 User Information
1.191 harris41 10496:
1.243 albertel 10497: =over 4
1.191 harris41 10498:
10499: =item *
1.394 bowersj2 10500: X<queryauthenticate()>
10501: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10502: authentication scheme
10503:
10504: =item *
1.394 bowersj2 10505: X<authenticate()>
1.1056.4.3! raeburn 10506: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 10507: authenticate user from domain's lib servers (first use the current
10508: one). C<$upass> should be the users password.
1.1056.4.3! raeburn 10509: $checkdefauth is optional (value is 1 if a check should be made to
! 10510: authenticate user using default authentication method, and allow
! 10511: account creation if username does not have account in the domain).
! 10512: $clientcancheckhost is optional (value is 1 if checking whether the
! 10513: server can host will occur on the client side in lonauth.pm).
1.191 harris41 10514:
10515: =item *
1.394 bowersj2 10516: X<homeserver()>
10517: B<homeserver($uname,$udom)>: find the server which has
10518: the user's directory and files (there must be only one), this caches
10519: the answer, and also caches if there is a borken connection.
1.191 harris41 10520:
10521: =item *
1.394 bowersj2 10522: X<idget()>
10523: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10524: (IDs are a unique resource in a domain, there must be only 1 ID per
10525: username, and only 1 username per ID in a specific domain) (returns
10526: hash: id=>name,id=>name)
1.191 harris41 10527:
10528: =item *
1.394 bowersj2 10529: X<idrget()>
10530: B<idrget($udom,@unames)>: find the IDs behind a list of
10531: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10532:
10533: =item *
1.394 bowersj2 10534: X<idput()>
10535: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10536:
10537: =item *
1.394 bowersj2 10538: X<rolesinit()>
10539: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10540:
10541: =item *
1.551 albertel 10542: X<getsection()>
10543: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10544: course $cname, return section name/number or '' for "not in course"
10545: and '-1' for "no section"
10546:
10547: =item *
1.394 bowersj2 10548: X<userenvironment()>
10549: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10550: passed in @what from the requested user's environment, returns a hash
10551:
1.858 raeburn 10552: =item *
10553: X<userlog_query()>
1.859 albertel 10554: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10555: activity.log file. %filters defines filters applied when parsing the
10556: log file. These can be start or end timestamps, or the type of action
10557: - log to look for Login or Logout events, check for Checkin or
10558: Checkout, role for role selection. The response is in the form
10559: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10560: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10561:
1.243 albertel 10562: =back
10563:
10564: =head2 User Roles
10565:
10566: =over 4
10567:
10568: =item *
10569:
1.810 raeburn 10570: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10571: F: full access
10572: U,I,K: authentication modes (cxx only)
10573: '': forbidden
10574: 1: user needs to choose course
10575: 2: browse allowed
1.766 albertel 10576: A: passphrase authentication needed
1.243 albertel 10577:
10578: =item *
10579:
10580: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10581: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10582: and course level
10583:
10584: =item *
10585:
1.988 raeburn 10586: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10587: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10588: $type is Course (default) or Community.
1.988 raeburn 10589: If $forcedefault evaluates to true, text returned will be default
10590: text for $type. Otherwise, if this is a course, the text returned
10591: will be a custom name for the role (if defined in the course's
10592: environment). If no custom name is defined the default is returned.
10593:
1.832 raeburn 10594: =item *
10595:
1.935 raeburn 10596: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10597: All arguments are optional. Returns a hash of a roles, either for
10598: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10599: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10600: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10601: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10602: For each key, value is set to colon-separated start and end times for
10603: the role. If no username and domain are specified, will default to
1.934 raeburn 10604: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10605: of role statuses (active, future or previous), roles
10606: (e.g., cc,in, st etc.) and domains of the roles which can be used
10607: to restrict the list of roles reported. If no array ref is
10608: provided for types, will default to return only active roles.
1.834 albertel 10609:
1.243 albertel 10610: =back
10611:
10612: =head2 User Modification
10613:
10614: =over 4
10615:
10616: =item *
10617:
1.957 raeburn 10618: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10619: user for the level given by URL. Optional start and end dates (leave empty
10620: string or zero for "no date")
1.191 harris41 10621:
10622: =item *
10623:
1.243 albertel 10624: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10625: change a users, password, possible return values are: ok,
10626: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10627: refused
1.191 harris41 10628:
10629: =item *
10630:
1.243 albertel 10631: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10632:
10633: =item *
10634:
1.1056.4.1 raeburn 10635: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10636: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10637:
10638: will update user information (firstname,middlename,lastname,generation,
10639: permanentemail), and if forceid is true, student/employee ID also.
10640: A user's institutional affiliation(s) can also be updated.
10641: User information fields will not be overwritten with empty entries
10642: unless the field is included in the $candelete array reference.
10643: This array is included when a single user is modified via "Manage Users",
10644: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10645:
10646: =item *
10647:
1.286 matthew 10648: modifystudent
10649:
1.957 raeburn 10650: modify a student's enrollment and identification information.
1.286 matthew 10651: The course id is resolved based on the current users environment.
10652: This means the envoking user must be a course coordinator or otherwise
10653: associated with a course.
10654:
1.297 matthew 10655: This call is essentially a wrapper for lonnet::modifyuser and
10656: lonnet::modify_student_enrollment
1.286 matthew 10657:
10658: Inputs:
10659:
10660: =over 4
10661:
1.957 raeburn 10662: =item B<$udom> Student's loncapa domain
1.286 matthew 10663:
1.957 raeburn 10664: =item B<$uname> Student's loncapa login name
1.286 matthew 10665:
1.964 bisitz 10666: =item B<$uid> Student/Employee ID
1.286 matthew 10667:
1.957 raeburn 10668: =item B<$umode> Student's authentication mode
1.286 matthew 10669:
1.957 raeburn 10670: =item B<$upass> Student's password
1.286 matthew 10671:
1.957 raeburn 10672: =item B<$first> Student's first name
1.286 matthew 10673:
1.957 raeburn 10674: =item B<$middle> Student's middle name
1.286 matthew 10675:
1.957 raeburn 10676: =item B<$last> Student's last name
1.286 matthew 10677:
1.957 raeburn 10678: =item B<$gene> Student's generation
1.286 matthew 10679:
1.957 raeburn 10680: =item B<$usec> Student's section in course
1.286 matthew 10681:
10682: =item B<$end> Unix time of the roles expiration
10683:
10684: =item B<$start> Unix time of the roles start date
10685:
10686: =item B<$forceid> If defined, allow $uid to be changed
10687:
10688: =item B<$desiredhome> server to use as home server for student
10689:
1.957 raeburn 10690: =item B<$email> Student's permanent e-mail address
10691:
10692: =item B<$type> Type of enrollment (auto or manual)
10693:
1.963 raeburn 10694: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10695:
10696: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10697:
1.963 raeburn 10698: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10699:
1.963 raeburn 10700: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10701:
1.963 raeburn 10702: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10703:
1.286 matthew 10704: =back
1.297 matthew 10705:
10706: =item *
10707:
10708: modify_student_enrollment
10709:
10710: Change a students enrollment status in a class. The environment variable
10711: 'role.request.course' must be defined for this function to proceed.
10712:
10713: Inputs:
10714:
10715: =over 4
10716:
10717: =item $udom, students domain
10718:
10719: =item $uname, students name
10720:
10721: =item $uid, students user id
10722:
10723: =item $first, students first name
10724:
10725: =item $middle
10726:
10727: =item $last
10728:
10729: =item $gene
10730:
10731: =item $usec
10732:
10733: =item $end
10734:
10735: =item $start
10736:
1.957 raeburn 10737: =item $type
10738:
10739: =item $locktype
10740:
10741: =item $cid
10742:
10743: =item $selfenroll
10744:
10745: =item $context
10746:
1.297 matthew 10747: =back
10748:
1.191 harris41 10749:
10750: =item *
10751:
1.243 albertel 10752: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10753: custom role; give a custom role to a user for the level given by URL. Specify
10754: name and domain of role author, and role name
1.191 harris41 10755:
10756: =item *
10757:
1.243 albertel 10758: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10759:
10760: =item *
10761:
1.243 albertel 10762: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10763:
10764: =back
10765:
10766: =head2 Course Infomation
10767:
10768: =over 4
1.191 harris41 10769:
10770: =item *
10771:
1.631 albertel 10772: coursedescription($courseid) : returns a hash of information about the
10773: specified course id, including all environment settings for the
10774: course, the description of the course will be in the hash under the
10775: key 'description'
1.191 harris41 10776:
10777: =item *
10778:
1.624 albertel 10779: resdata($name,$domain,$type,@which) : request for current parameter
10780: setting for a specific $type, where $type is either 'course' or 'user',
10781: @what should be a list of parameters to ask about. This routine caches
10782: answers for 5 minutes.
1.243 albertel 10783:
1.877 foxr 10784: =item *
10785:
10786: get_courseresdata($courseid, $domain) : dump the entire course resource
10787: data base, returning a hash that is keyed by the resource name and has
10788: values that are the resource value. I believe that the timestamps and
10789: versions are also returned.
10790:
10791:
1.243 albertel 10792: =back
10793:
10794: =head2 Course Modification
10795:
10796: =over 4
1.191 harris41 10797:
10798: =item *
10799:
1.243 albertel 10800: writecoursepref($courseid,%prefs) : write preferences (environment
10801: database) for a course
1.191 harris41 10802:
10803: =item *
10804:
1.1011 raeburn 10805: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10806:
10807: =item *
10808:
1.1038 raeburn 10809: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 10810:
10811: =back
10812:
10813: =head2 Resource Subroutines
10814:
10815: =over 4
1.191 harris41 10816:
10817: =item *
10818:
1.243 albertel 10819: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 10820:
10821: =item *
10822:
1.243 albertel 10823: repcopy($filename) : subscribes to the requested file, and attempts to
10824: replicate from the owning library server, Might return
1.607 raeburn 10825: 'unavailable', 'not_found', 'forbidden', 'ok', or
10826: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 10827: resource. Expects the local filesystem pathname
10828: (/home/httpd/html/res/....)
10829:
10830: =back
10831:
10832: =head2 Resource Information
10833:
10834: =over 4
1.191 harris41 10835:
10836: =item *
10837:
1.243 albertel 10838: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10839: a vairety of different possible values, $varname should be a request
10840: string, and the other parameters can be used to specify who and what
10841: one is asking about.
10842:
10843: Possible values for $varname are environment.lastname (or other item
10844: from the envirnment hash), user.name (or someother aspect about the
10845: user), resource.0.maxtries (or some other part and parameter of a
10846: resource)
1.204 albertel 10847:
10848: =item *
10849:
1.243 albertel 10850: directcondval($number) : get current value of a condition; reads from a state
10851: string
1.204 albertel 10852:
10853: =item *
10854:
1.243 albertel 10855: condval($condidx) : value of condition index based on state
1.204 albertel 10856:
10857: =item *
10858:
1.243 albertel 10859: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10860: resource's metadata, $what should be either a specific key, or either
10861: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10862: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10863:
10864: this function automatically caches all requests
1.191 harris41 10865:
10866: =item *
10867:
1.243 albertel 10868: metadata_query($query,$custom,$customshow) : make a metadata query against the
10869: network of library servers; returns file handle of where SQL and regex results
10870: will be stored for query
1.191 harris41 10871:
10872: =item *
10873:
1.243 albertel 10874: symbread($filename) : return symbolic list entry (filename argument optional);
10875: returns the data handle
1.191 harris41 10876:
10877: =item *
10878:
1.243 albertel 10879: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 10880: a possible symb for the URL in $thisfn, and if is an encryypted
10881: resource that the user accessed using /enc/ returns a 1 on success, 0
10882: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 10883: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 10884:
1.191 harris41 10885:
10886: =item *
10887:
1.243 albertel 10888: symbclean($symb) : removes versions numbers from a symb, returns the
10889: cleaned symb
1.191 harris41 10890:
10891: =item *
10892:
1.243 albertel 10893: is_on_map($uri) : checks if the $uri is somewhere on the current
10894: course map, user must be in a course for it to work.
1.191 harris41 10895:
10896: =item *
10897:
1.243 albertel 10898: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 10899:
10900: =item *
10901:
1.243 albertel 10902: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10903: a random seed, all arguments are optional, if they aren't sent it uses the
10904: environment to derive them. Note: if symb isn't sent and it can't get one
10905: from &symbread it will use the current time as its return value
1.191 harris41 10906:
10907: =item *
10908:
1.243 albertel 10909: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10910: unfakeable, receipt
1.191 harris41 10911:
10912: =item *
10913:
1.620 albertel 10914: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 10915:
10916: =item *
10917:
1.243 albertel 10918: countacc($url) : count the number of accesses to a given URL
1.191 harris41 10919:
10920: =item *
10921:
1.243 albertel 10922: 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 10923:
10924: =item *
10925:
1.243 albertel 10926: 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 10927:
10928: =item *
10929:
1.243 albertel 10930: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 10931:
10932: =item *
10933:
1.243 albertel 10934: devalidate($symb) : devalidate temporary spreadsheet calculations,
10935: forcing spreadsheet to reevaluate the resource scores next time.
10936:
10937: =back
10938:
10939: =head2 Storing/Retreiving Data
10940:
10941: =over 4
1.191 harris41 10942:
10943: =item *
10944:
1.243 albertel 10945: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10946: for this url; hashref needs to be given and should be a \%hashname; the
10947: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 10948: be derived from the env
1.191 harris41 10949:
10950: =item *
10951:
1.243 albertel 10952: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10953: uses critical subroutine
1.191 harris41 10954:
10955: =item *
10956:
1.243 albertel 10957: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10958: all args are optional
1.191 harris41 10959:
10960: =item *
10961:
1.717 albertel 10962: dumpstore($namespace,$udom,$uname,$regexp,$range) :
10963: dumps the complete (or key matching regexp) namespace into a hash
10964: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10965: normally &store()ed into
10966:
10967: $range should be either an integer '100' (give me the first 100
10968: matching records)
10969: or be two integers sperated by a - with no spaces
10970: '30-50' (give me the 30th through the 50th matching
10971: records)
10972:
10973:
10974: =item *
10975:
10976: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10977: replaces a &store() version of data with a replacement set of data
10978: for a particular resource in a namespace passed in the $storehash hash
10979: reference
10980:
10981: =item *
10982:
1.243 albertel 10983: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10984: works very similar to store/cstore, but all data is stored in a
10985: temporary location and can be reset using tmpreset, $storehash should
10986: be a hash reference, returns nothing on success
1.191 harris41 10987:
10988: =item *
10989:
1.243 albertel 10990: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10991: similar to restore, but all data is stored in a temporary location and
10992: can be reset using tmpreset. Returns a hash of values on success,
10993: error string otherwise.
1.191 harris41 10994:
10995: =item *
10996:
1.243 albertel 10997: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10998: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 10999:
11000: =item *
11001:
1.243 albertel 11002: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11003: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11004:
11005: =item *
11006:
1.243 albertel 11007: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11008: namesp ($udom and $uname are optional)
1.191 harris41 11009:
11010: =item *
11011:
1.702 albertel 11012: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11013: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11014: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11015:
1.702 albertel 11016: $range should be either an integer '100' (give me the first 100
11017: matching records)
11018: or be two integers sperated by a - with no spaces
11019: '30-50' (give me the 30th through the 50th matching
11020: records)
1.449 matthew 11021: =item *
11022:
11023: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11024: $store can be a scalar, an array reference, or if the amount to be
11025: incremented is > 1, a hash reference.
11026:
11027: ($udom and $uname are optional)
1.191 harris41 11028:
11029: =item *
11030:
1.243 albertel 11031: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11032: ($udom and $uname are optional)
1.191 harris41 11033:
11034: =item *
11035:
1.243 albertel 11036: cput($namespace,$storehash,$udom,$uname) : critical put
11037: ($udom and $uname are optional)
1.191 harris41 11038:
11039: =item *
11040:
1.748 albertel 11041: newput($namespace,$storehash,$udom,$uname) :
11042:
11043: Attempts to store the items in the $storehash, but only if they don't
11044: currently exist, if this succeeds you can be certain that you have
11045: successfully created a new key value pair in the $namespace db.
11046:
11047:
11048: Args:
11049: $namespace: name of database to store values to
11050: $storehash: hashref to store to the db
11051: $udom: (optional) domain of user containing the db
11052: $uname: (optional) name of user caontaining the db
11053:
11054: Returns:
11055: 'ok' -> succeeded in storing all keys of $storehash
11056: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11057: least <key> already existed in the db (other
11058: requested keys may also already exist)
1.967 bisitz 11059: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11060: 'con_lost' -> unable to contact request server
11061: 'refused' -> action was not allowed by remote machine
11062:
11063:
11064: =item *
11065:
1.243 albertel 11066: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11067: reference filled in from namesp (encrypts the return communication)
11068: ($udom and $uname are optional)
1.191 harris41 11069:
11070: =item *
11071:
1.243 albertel 11072: log($udom,$name,$home,$message) : write to permanent log for user; use
11073: critical subroutine
11074:
1.806 raeburn 11075: =item *
11076:
1.860 raeburn 11077: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11078: array reference filled in from namespace found in domain level on either
11079: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11080:
11081: =item *
11082:
1.860 raeburn 11083: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11084: domain level either on specified domain server ($uhome) or primary domain
11085: server ($udom and $uhome are optional)
1.806 raeburn 11086:
1.943 raeburn 11087: =item *
11088:
11089: get_domain_defaults($target_domain) : returns hash with defaults for
11090: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11091: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11092: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11093: Values are retrieved from cache (if current), or from domain's configuration.db
11094: (if available), or lastly from values in lonTabs/dns_domain,tab,
11095: or lonTabs/domain.tab.
11096:
11097: %domdefaults = &get_auth_defaults($target_domain);
11098:
1.243 albertel 11099: =back
11100:
11101: =head2 Network Status Functions
11102:
11103: =over 4
1.191 harris41 11104:
11105: =item *
11106:
11107: dirlist($uri) : return directory list based on URI
11108:
11109: =item *
11110:
1.243 albertel 11111: spareserver() : find server with least workload from spare.tab
11112:
1.986 foxr 11113:
11114: =item *
11115:
11116: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11117: if there is no corresponding loncapa host.
11118:
1.243 albertel 11119: =back
11120:
1.986 foxr 11121:
1.243 albertel 11122: =head2 Apache Request
11123:
11124: =over 4
1.191 harris41 11125:
11126: =item *
11127:
1.243 albertel 11128: ssi($url,%hash) : server side include, does a complete request cycle on url to
11129: localhost, posts hash
11130:
11131: =back
11132:
11133: =head2 Data to String to Data
11134:
11135: =over 4
1.191 harris41 11136:
11137: =item *
11138:
1.243 albertel 11139: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11140: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11141:
11142: =item *
11143:
1.243 albertel 11144: hashref2str($hashref) : convert a hashref into a string complete with
11145: escaping and '=' and '&' separators, supports elements that are
11146: arrayrefs and hashrefs
1.191 harris41 11147:
11148: =item *
11149:
1.243 albertel 11150: arrayref2str($arrayref) : convert an arrayref into a string complete
11151: with escaping and '&' separators, supports elements that are arrayrefs
11152: and hashrefs
1.191 harris41 11153:
11154: =item *
11155:
1.243 albertel 11156: str2hash($string) : convert string to hash using unescaping and
11157: splitting on '=' and '&', supports elements that are arrayrefs and
11158: hashrefs
1.191 harris41 11159:
11160: =item *
11161:
1.243 albertel 11162: str2array($string) : convert string to hash using unescaping and
11163: splitting on '&', supports elements that are arrayrefs and hashrefs
11164:
11165: =back
11166:
11167: =head2 Logging Routines
11168:
11169: =over 4
11170:
11171: These routines allow one to make log messages in the lonnet.log and
11172: lonnet.perm logfiles.
1.191 harris41 11173:
11174: =item *
11175:
1.243 albertel 11176: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11177:
11178: =item *
11179:
1.243 albertel 11180: logthis() : append message to the normal lonnet.log file, it gets
11181: preiodically rolled over and deleted.
1.191 harris41 11182:
11183: =item *
11184:
1.243 albertel 11185: logperm() : append a permanent message to lonnet.perm.log, this log
11186: file never gets deleted by any automated portion of the system, only
11187: messages of critical importance should go in here.
11188:
11189: =back
11190:
11191: =head2 General File Helper Routines
11192:
11193: =over 4
1.191 harris41 11194:
11195: =item *
11196:
1.481 raeburn 11197: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11198: (a) files in /uploaded
11199: (i) If a local copy of the file exists -
11200: compares modification date of local copy with last-modified date for
11201: definitive version stored on home server for course. If local copy is
11202: stale, requests a new version from the home server and stores it.
11203: If the original has been removed from the home server, then local copy
11204: is unlinked.
11205: (ii) If local copy does not exist -
11206: requests the file from the home server and stores it.
11207:
11208: If $caller is 'uploadrep':
11209: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11210: for request for files originally uploaded via DOCS.
11211: - returns 'ok' if fresh local copy now available, -1 otherwise.
11212:
11213: Otherwise:
11214: This indicates a call from the content generation phase of the request.
11215: - returns the entire contents of the file or -1.
11216:
11217: (b) files in /res
11218: - returns the entire contents of a file or -1;
11219: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11220:
1.712 albertel 11221:
11222: =item *
11223:
11224: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11225: reference
11226:
11227: returns either a stat() list of data about the file or an empty list
11228: if the file doesn't exist or couldn't find out about it (connection
11229: problems or user unknown)
11230:
1.191 harris41 11231: =item *
11232:
1.243 albertel 11233: filelocation($dir,$file) : returns file system location of a file
11234: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11235: directory that relative $file lookups are to looked in ($dir of /a/dir
11236: and a file of ../bob will become /a/bob)
1.191 harris41 11237:
11238: =item *
11239:
11240: hreflocation($dir,$file) : returns file system location or a URL; same as
11241: filelocation except for hrefs
11242:
11243: =item *
11244:
11245: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11246:
1.243 albertel 11247: =back
11248:
1.608 albertel 11249: =head2 Usererfile file routines (/uploaded*)
11250:
11251: =over 4
11252:
11253: =item *
11254:
11255: userfileupload(): main rotine for putting a file in a user or course's
11256: filespace, arguments are,
11257:
1.620 albertel 11258: formname - required - this is the name of the element in $env where the
1.608 albertel 11259: filename, and the contents of the file to create/modifed exist
1.620 albertel 11260: the filename is in $env{'form.'.$formname.'.filename'} and the
11261: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 11262: coursedoc - if true, store the file in the course of the active role
11263: of the current user
11264: subdir - required - subdirectory to put the file in under ../userfiles/
11265: if undefined, it will be placed in "unknown"
11266:
11267: (This routine calls clean_filename() to remove any dangerous
11268: characters from the filename, and then calls finuserfileupload() to
11269: complete the transaction)
11270:
11271: returns either the url of the uploaded file (/uploaded/....) if successful
11272: and /adm/notfound.html if unsuccessful
11273:
11274: =item *
11275:
11276: clean_filename(): routine for cleaing a filename up for storage in
11277: userfile space, argument is:
11278:
11279: filename - proposed filename
11280:
11281: returns: the new clean filename
11282:
11283: =item *
11284:
11285: finishuserfileupload(): routine that creaes and sends the file to
11286: userspace, probably shouldn't be called directly
11287:
11288: docuname: username or courseid of destination for the file
11289: docudom: domain of user/course of destination for the file
11290: formname: same as for userfileupload()
11291: fname: filename (inculding subdirectories) for the file
11292:
11293: returns either the url of the uploaded file (/uploaded/....) if successful
11294: and /adm/notfound.html if unsuccessful
11295:
11296: =item *
11297:
11298: renameuserfile(): renames an existing userfile to a new name
11299:
11300: Args:
11301: docuname: username or courseid of destination for the file
11302: docudom: domain of user/course of destination for the file
11303: old: current file name (including any subdirs under userfiles)
11304: new: desired file name (including any subdirs under userfiles)
11305:
11306: =item *
11307:
11308: mkdiruserfile(): creates a directory is a userfiles dir
11309:
11310: Args:
11311: docuname: username or courseid of destination for the file
11312: docudom: domain of user/course of destination for the file
11313: dir: dir to create (including any subdirs under userfiles)
11314:
11315: =item *
11316:
11317: removeuserfile(): removes a file that exists in userfiles
11318:
11319: Args:
11320: docuname: username or courseid of destination for the file
11321: docudom: domain of user/course of destination for the file
11322: fname: filname to delete (including any subdirs under userfiles)
11323:
11324: =item *
11325:
11326: removeuploadedurl(): convience function for removeuserfile()
11327:
11328: Args:
11329: url: a full /uploaded/... url to delete
11330:
1.747 albertel 11331: =item *
11332:
11333: get_portfile_permissions():
11334: Args:
11335: domain: domain of user or course contain the portfolio files
11336: user: name of user or num of course contain the portfolio files
11337: Returns:
11338: hashref of a dump of the proper file_permissions.db
11339:
11340:
11341: =item *
11342:
11343: get_access_controls():
11344:
11345: Args:
11346: current_permissions: the hash ref returned from get_portfile_permissions()
11347: group: (optional) the group you want the files associated with
11348: file: (optional) the file you want access info on
11349:
11350: Returns:
1.749 raeburn 11351: a hash (keys are file names) of hashes containing
11352: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11353: values are XML containing access control settings (see below)
1.747 albertel 11354:
11355: Internal notes:
11356:
1.749 raeburn 11357: access controls are stored in file_permissions.db as key=value pairs.
11358: key -> path to file/file_name\0uniqueID:scope_end_start
11359: where scope -> public,guest,course,group,domains or users.
11360: end -> UNIX time for end of access (0 -> no end date)
11361: start -> UNIX time for start of access
11362:
11363: value -> XML description of access control
11364: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11365: <start></start>
11366: <end></end>
11367:
11368: <password></password> for scope type = guest
11369:
11370: <domain></domain> for scope type = course or group
11371: <number></number>
11372: <roles id="">
11373: <role></role>
11374: <access></access>
11375: <section></section>
11376: <group></group>
11377: </roles>
11378:
11379: <dom></dom> for scope type = domains
11380:
11381: <users> for scope type = users
11382: <user>
11383: <uname></uname>
11384: <udom></udom>
11385: </user>
11386: </users>
11387: </scope>
11388:
11389: Access data is also aggregated for each file in an additional key=value pair:
11390: key -> path to file/file_name\0accesscontrol
11391: value -> reference to hash
11392: hash contains key = value pairs
11393: where key = uniqueID:scope_end_start
11394: value = UNIX time record was last updated
11395:
11396: Used to improve speed of look-ups of access controls for each file.
11397:
11398: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11399:
11400: modify_access_controls():
11401:
11402: Modifies access controls for a portfolio file
11403: Args
11404: 1. file name
11405: 2. reference to hash of required changes,
11406: 3. domain
11407: 4. username
11408: where domain,username are the domain of the portfolio owner
11409: (either a user or a course)
11410:
11411: Returns:
11412: 1. result of additions or updates ('ok' or 'error', with error message).
11413: 2. result of deletions ('ok' or 'error', with error message).
11414: 3. reference to hash of any new or updated access controls.
11415: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11416: key = integer (inbound ID)
11417: value = uniqueID
1.747 albertel 11418:
1.608 albertel 11419: =back
11420:
1.243 albertel 11421: =head2 HTTP Helper Routines
11422:
11423: =over 4
11424:
1.191 harris41 11425: =item *
11426:
11427: escape() : unpack non-word characters into CGI-compatible hex codes
11428:
11429: =item *
11430:
11431: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11432:
1.243 albertel 11433: =back
11434:
11435: =head1 PRIVATE SUBROUTINES
11436:
11437: =head2 Underlying communication routines (Shouldn't call)
11438:
11439: =over 4
11440:
11441: =item *
11442:
11443: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11444:
11445: =item *
11446:
11447: reply() : uses subreply to send a message to remote machine, logs all failures
11448:
11449: =item *
11450:
11451: critical() : passes a critical message to another server; if cannot
11452: get through then place message in connection buffer directory and
11453: returns con_delayed, if incapable of saving message, returns
11454: con_failed
11455:
11456: =item *
11457:
11458: reconlonc() : tries to reconnect lonc client processes.
11459:
11460: =back
11461:
11462: =head2 Resource Access Logging
11463:
11464: =over 4
11465:
11466: =item *
11467:
11468: flushcourselogs() : flush (save) buffer logs and access logs
11469:
11470: =item *
11471:
11472: courselog($what) : save message for course in hash
11473:
11474: =item *
11475:
11476: courseacclog($what) : save message for course using &courselog(). Perform
11477: special processing for specific resource types (problems, exams, quizzes, etc).
11478:
1.191 harris41 11479: =item *
11480:
11481: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11482: as a PerlChildExitHandler
1.243 albertel 11483:
11484: =back
11485:
11486: =head2 Other
11487:
11488: =over 4
11489:
11490: =item *
11491:
11492: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11493:
11494: =back
11495:
11496: =cut
1.877 foxr 11497:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>