Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1086
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1086 ! raeburn 4: # $Id: lonnet.pm,v 1.1085 2010/09/24 13:15:47 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.1079 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
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.1073 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.1073 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'};
1.1081 raeburn 225: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 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;
1.1082 raeburn 233: $ua->timeout(4);
1.1073 raeburn 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;
1.1081 raeburn 241: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 242: $loncaparev = $1;
243: }
244: }
245: } else {
246: $loncaparev = $loncaparevs{$lonhost};
247: }
1.1081 raeburn 248: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 249: $loncaparev = $1;
250: }
1.993 raeburn 251: }
1.1073 raeburn 252: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 253: }
254: }
255:
1.1074 raeburn 256: sub get_server_homeID {
257: my ($hostname,$ignore_cache,$caller) = @_;
258: unless ($ignore_cache) {
259: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
260: if (defined($cached)) {
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: }
274: }
275: if ($serverhomeID eq '') {
276: $serverhomeID = $machine_ids[-1];
277: }
278: } else {
279: $serverhomeID = $serverhomeIDs{$hostname};
280: }
281: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
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:
1.1 albertel 727: # ------------------------------ Find server with least workload from spare.tab
1.11 www 728:
1.1 albertel 729: sub spareserver {
1.1083 raeburn 730: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 731: my $spare_server;
1.370 albertel 732: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 733: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
734: : $userloadpercent;
1.1083 raeburn 735: my ($uint_dom,$remotesessions);
736: if (($udom ne '') && (&domain($udom) ne '')) {
737: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
738: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
739: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
740: $remotesessions = $udomdefaults{'remotesessions'};
741: }
1.784 albertel 742: foreach my $try_server (@{ $spareid{'primary'} }) {
1.1083 raeburn 743: if ($uint_dom) {
744: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
745: $try_server));
746: }
1.784 albertel 747: ($spare_server, $lowest_load) =
748: &compare_server_load($try_server, $spare_server, $lowest_load);
749: }
750:
751: my $found_server = ($spare_server ne '' && $lowest_load < 100);
752:
753: if (!$found_server) {
754: foreach my $try_server (@{ $spareid{'default'} }) {
1.1083 raeburn 755: if ($uint_dom) {
756: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
757: $try_server));
758: }
1.784 albertel 759: ($spare_server, $lowest_load) =
760: &compare_server_load($try_server, $spare_server, $lowest_load);
761: }
762: }
763:
764: if (!$want_server_name) {
1.968 raeburn 765: my $protocol = 'http';
766: if ($protocol{$spare_server} eq 'https') {
767: $protocol = $protocol{$spare_server};
768: }
1.1001 raeburn 769: if (defined($spare_server)) {
770: my $hostname = &hostname($spare_server);
1.1083 raeburn 771: if (defined($hostname)) {
1.1001 raeburn 772: $spare_server = $protocol.'://'.$hostname;
773: }
774: }
1.784 albertel 775: }
776: return $spare_server;
777: }
778:
779: sub compare_server_load {
780: my ($try_server, $spare_server, $lowest_load) = @_;
781:
782: my $loadans = &reply('load', $try_server);
783: my $userloadans = &reply('userload',$try_server);
784:
785: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1072 www 786: return; #didn't get a number from the server
1.784 albertel 787: }
788:
789: my $load;
790: if ($loadans =~ /\d/) {
791: if ($userloadans =~ /\d/) {
792: #both are numbers, pick the bigger one
793: $load = ($loadans > $userloadans) ? $loadans
794: : $userloadans;
1.411 albertel 795: } else {
1.784 albertel 796: $load = $loadans;
1.411 albertel 797: }
1.784 albertel 798: } else {
799: $load = $userloadans;
800: }
801:
802: if (($load =~ /\d/) && ($load < $lowest_load)) {
803: $spare_server = $try_server;
804: $lowest_load = $load;
1.370 albertel 805: }
1.784 albertel 806: return ($spare_server,$lowest_load);
1.202 matthew 807: }
1.914 albertel 808:
809: # --------------------------- ask offload servers if user already has a session
810: sub find_existing_session {
811: my ($udom,$uname) = @_;
812: foreach my $try_server (@{ $spareid{'primary'} },
813: @{ $spareid{'default'} }) {
814: return $try_server if (&has_user_session($try_server, $udom, $uname));
815: }
816: return;
817: }
818:
819: # -------------------------------- ask if server already has a session for user
820: sub has_user_session {
821: my ($lonid,$udom,$uname) = @_;
822: my $result = &reply(join(':','userhassession',
823: map {&escape($_)} ($udom,$uname)),$lonid);
824: return 1 if ($result eq 'ok');
825:
826: return 0;
827: }
828:
1.1076 raeburn 829: # --------- determine least loaded server in a user's domain which allows login
830:
831: sub choose_server {
832: my ($udom) = @_;
833: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 834: my %servers = &get_servers($udom);
1.1076 raeburn 835: my $lowest_load = 30000;
836: my ($login_host,$hostname);
837: foreach my $lonhost (keys(%servers)) {
838: my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
839: if ($loginvia eq '') {
840: ($login_host, $lowest_load) =
841: &compare_server_load($lonhost, $login_host, $lowest_load);
842: }
843: }
844: if ($login_host ne '') {
845: $hostname = $servers{$login_host};
846: }
847: return ($login_host,$hostname);
848: }
849:
1.202 matthew 850: # --------------------------------------------- Try to change a user's password
851:
852: sub changepass {
1.799 raeburn 853: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 854: $currentpass = &escape($currentpass);
855: $newpass = &escape($newpass);
1.1030 raeburn 856: my $lonhost = $perlvar{'lonHostID'};
857: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 858: $server);
859: if (! $answer) {
860: &logthis("No reply on password change request to $server ".
861: "by $uname in domain $udom.");
862: } elsif ($answer =~ "^ok") {
863: &logthis("$uname in $udom successfully changed their password ".
864: "on $server.");
865: } elsif ($answer =~ "^pwchange_failure") {
866: &logthis("$uname in $udom was unable to change their password ".
867: "on $server. The action was blocked by either lcpasswd ".
868: "or pwchange");
869: } elsif ($answer =~ "^non_authorized") {
870: &logthis("$uname in $udom did not get their password correct when ".
871: "attempting to change it on $server.");
872: } elsif ($answer =~ "^auth_mode_error") {
873: &logthis("$uname in $udom attempted to change their password despite ".
874: "not being locally or internally authenticated on $server.");
875: } elsif ($answer =~ "^unknown_user") {
876: &logthis("$uname in $udom attempted to change their password ".
877: "on $server but were unable to because $server is not ".
878: "their home server.");
879: } elsif ($answer =~ "^refused") {
880: &logthis("$server refused to change $uname in $udom password because ".
881: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 882: } elsif ($answer =~ "invalid_client") {
883: &logthis("$server refused to change $uname in $udom password because ".
884: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 885: }
886: return $answer;
1.1 albertel 887: }
888:
1.169 harris41 889: # ----------------------- Try to determine user's current authentication scheme
890:
891: sub queryauthenticate {
892: my ($uname,$udom)=@_;
1.456 albertel 893: my $uhome=&homeserver($uname,$udom);
894: if (!$uhome) {
895: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
896: return 'no_host';
897: }
898: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
899: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
900: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 901: }
1.456 albertel 902: return $answer;
1.169 harris41 903: }
904:
1.1 albertel 905: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 906:
1.1 albertel 907: sub authenticate {
1.1073 raeburn 908: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 909: $upass=&escape($upass);
910: $uname= &LONCAPA::clean_username($uname);
1.836 www 911: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 912: my $newhome;
1.836 www 913: if ((!$uhome) || ($uhome eq 'no_host')) {
914: # Maybe the machine was offline and only re-appeared again recently?
915: &reconlonc();
916: # One more
1.952 raeburn 917: $uhome=&homeserver($uname,$udom,1);
918: if (($uhome eq 'no_host') && $checkdefauth) {
919: if (defined(&domain($udom,'primary'))) {
920: $newhome=&domain($udom,'primary');
921: }
922: if ($newhome ne '') {
923: $uhome = $newhome;
924: }
925: }
1.836 www 926: if ((!$uhome) || ($uhome eq 'no_host')) {
927: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 928: return 'no_host';
929: }
1.1 albertel 930: }
1.1073 raeburn 931: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 932: if ($answer eq 'authorized') {
1.952 raeburn 933: if ($newhome) {
934: &logthis("User $uname at $udom authorized by $uhome, but needs account");
935: return 'no_account_on_host';
936: } else {
937: &logthis("User $uname at $udom authorized by $uhome");
938: return $uhome;
939: }
1.471 albertel 940: }
941: if ($answer eq 'non_authorized') {
942: &logthis("User $uname at $udom rejected by $uhome");
943: return 'no_host';
1.9 www 944: }
1.471 albertel 945: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 946: return 'no_host';
947: }
948:
1.1073 raeburn 949: sub can_host_session {
1.1074 raeburn 950: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 951: my $canhost = 1;
1.1074 raeburn 952: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 953: if (ref($remotesessions) eq 'HASH') {
954: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 955: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 956: $canhost = 0;
957: } else {
958: $canhost = 1;
959: }
960: }
961: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 962: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 963: $canhost = 1;
964: } else {
965: $canhost = 0;
966: }
967: }
968: if ($canhost) {
969: if ($remotesessions->{'version'} ne '') {
970: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
971: if ($reqmajor ne '' && $reqminor ne '') {
972: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
973: my $major = $1;
974: my $minor = $2;
975: if (($major < $reqmajor ) ||
976: (($major == $reqmajor) && ($minor < $reqminor))) {
977: $canhost = 0;
978: }
979: } else {
980: $canhost = 0;
981: }
982: }
983: }
984: }
985: }
986: if ($canhost) {
987: if (ref($hostedsessions) eq 'HASH') {
988: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
989: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
990: $canhost = 0;
991: } else {
992: $canhost = 1;
993: }
994: }
995: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
996: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
997: $canhost = 1;
998: } else {
999: $canhost = 0;
1000: }
1001: }
1002: }
1003: }
1004: return $canhost;
1005: }
1006:
1.1083 raeburn 1007: sub spare_can_host {
1008: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1009: my $canhost=1;
1010: my @intdoms;
1011: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1012: if (ref($internet_names) eq 'ARRAY') {
1013: @intdoms = @{$internet_names};
1014: }
1015: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1016: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1017: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1018: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1019: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1020: $canhost = &can_host_session($udom,$try_server,$remoterev,
1021: $remotesessions,
1022: $defdomdefaults{'hostedsessions'});
1023: }
1024: return $canhost;
1025: }
1026:
1.1 albertel 1027: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1028:
1.599 albertel 1029: my %homecache;
1.1 albertel 1030: sub homeserver {
1.230 stredwic 1031: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1032: my $index="$uname:$udom";
1.426 albertel 1033:
1.599 albertel 1034: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1035:
1036: my %servers = &get_servers($udom,'library');
1037: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1038: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1039: exists($badServerCache{$tryserver}));
1.841 albertel 1040:
1041: my $answer=reply("home:$udom:$uname",$tryserver);
1042: if ($answer eq 'found') {
1043: delete($badServerCache{$tryserver});
1044: return $homecache{$index}=$tryserver;
1045: } elsif ($answer eq 'no_host') {
1046: $badServerCache{$tryserver}=1;
1047: }
1.1 albertel 1048: }
1049: return 'no_host';
1.70 www 1050: }
1051:
1052: # ------------------------------------- Find the usernames behind a list of IDs
1053:
1054: sub idget {
1055: my ($udom,@ids)=@_;
1056: my %returnhash=();
1057:
1.841 albertel 1058: my %servers = &get_servers($udom,'library');
1059: foreach my $tryserver (keys(%servers)) {
1060: my $idlist=join('&',@ids);
1061: $idlist=~tr/A-Z/a-z/;
1062: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1063: my @answer=();
1064: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1065: @answer=split(/\&/,$reply);
1066: } ;
1067: my $i;
1068: for ($i=0;$i<=$#ids;$i++) {
1069: if ($answer[$i]) {
1070: $returnhash{$ids[$i]}=$answer[$i];
1071: }
1072: }
1073: }
1.70 www 1074: return %returnhash;
1075: }
1076:
1077: # ------------------------------------- Find the IDs behind a list of usernames
1078:
1079: sub idrget {
1080: my ($udom,@unames)=@_;
1081: my %returnhash=();
1.800 albertel 1082: foreach my $uname (@unames) {
1083: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1084: }
1.70 www 1085: return %returnhash;
1086: }
1087:
1088: # ------------------------------- Store away a list of names and associated IDs
1089:
1090: sub idput {
1091: my ($udom,%ids)=@_;
1092: my %servers=();
1.800 albertel 1093: foreach my $uname (keys(%ids)) {
1094: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1095: my $uhom=&homeserver($uname,$udom);
1.70 www 1096: if ($uhom ne 'no_host') {
1.800 albertel 1097: my $id=&escape($ids{$uname});
1.70 www 1098: $id=~tr/A-Z/a-z/;
1.800 albertel 1099: my $esc_unam=&escape($uname);
1.70 www 1100: if ($servers{$uhom}) {
1.800 albertel 1101: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1102: } else {
1.800 albertel 1103: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1104: }
1105: }
1.191 harris41 1106: }
1.800 albertel 1107: foreach my $server (keys(%servers)) {
1108: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1109: }
1.344 www 1110: }
1111:
1.1023 raeburn 1112: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1113: sub dump_dom {
1.1023 raeburn 1114: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1115: if (!$udom) {
1116: $udom=$env{'user.domain'};
1117: }
1118: my %returnhash;
1.1023 raeburn 1119: if ($udom) {
1120: my $uname = &get_domainconfiguser($udom);
1121: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1122: }
1123: return %returnhash;
1124: }
1125:
1.1023 raeburn 1126: # ------------------------------------------ get items from domain db files
1.806 raeburn 1127:
1128: sub get_dom {
1.860 raeburn 1129: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1130: my $items='';
1131: foreach my $item (@$storearr) {
1132: $items.=&escape($item).'&';
1133: }
1134: $items=~s/\&$//;
1.860 raeburn 1135: if (!$udom) {
1136: $udom=$env{'user.domain'};
1137: if (defined(&domain($udom,'primary'))) {
1138: $uhome=&domain($udom,'primary');
1139: } else {
1.874 albertel 1140: undef($uhome);
1.860 raeburn 1141: }
1142: } else {
1143: if (!$uhome) {
1144: if (defined(&domain($udom,'primary'))) {
1145: $uhome=&domain($udom,'primary');
1146: }
1147: }
1148: }
1149: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1150: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1151: my %returnhash;
1.875 albertel 1152: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1153: return %returnhash;
1154: }
1.806 raeburn 1155: my @pairs=split(/\&/,$rep);
1156: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1157: return @pairs;
1158: }
1159: my $i=0;
1160: foreach my $item (@$storearr) {
1161: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1162: $i++;
1163: }
1164: return %returnhash;
1165: } else {
1.880 banghart 1166: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1167: }
1168: }
1169:
1170: # -------------------------------------------- put items in domain db files
1171:
1172: sub put_dom {
1.860 raeburn 1173: my ($namespace,$storehash,$udom,$uhome)=@_;
1174: if (!$udom) {
1175: $udom=$env{'user.domain'};
1176: if (defined(&domain($udom,'primary'))) {
1177: $uhome=&domain($udom,'primary');
1178: } else {
1.874 albertel 1179: undef($uhome);
1.860 raeburn 1180: }
1181: } else {
1182: if (!$uhome) {
1183: if (defined(&domain($udom,'primary'))) {
1184: $uhome=&domain($udom,'primary');
1185: }
1186: }
1187: }
1188: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1189: my $items='';
1190: foreach my $item (keys(%$storehash)) {
1191: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1192: }
1193: $items=~s/\&$//;
1194: return &reply("putdom:$udom:$namespace:$items",$uhome);
1195: } else {
1.860 raeburn 1196: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1197: }
1198: }
1199:
1.1023 raeburn 1200: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1201: sub newput_dom {
1.1023 raeburn 1202: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1203: my $result;
1204: if (!$udom) {
1205: $udom=$env{'user.domain'};
1206: }
1.1023 raeburn 1207: if ($udom) {
1208: my $uname = &get_domainconfiguser($udom);
1209: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1210: }
1211: return $result;
1212: }
1213:
1.1023 raeburn 1214: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1215: sub del_dom {
1.1023 raeburn 1216: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1217: if (ref($storearr) eq 'ARRAY') {
1218: if (!$udom) {
1219: $udom=$env{'user.domain'};
1220: }
1.1023 raeburn 1221: if ($udom) {
1222: my $uname = &get_domainconfiguser($udom);
1223: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1224: }
1225: }
1226: }
1227:
1.1023 raeburn 1228: # ----------------------------------construct domainconfig user for a domain
1229: sub get_domainconfiguser {
1230: my ($udom) = @_;
1231: return $udom.'-domainconfig';
1232: }
1233:
1.837 raeburn 1234: sub retrieve_inst_usertypes {
1235: my ($udom) = @_;
1236: my (%returnhash,@order);
1.989 raeburn 1237: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1238: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1239: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1240: %returnhash = %{$domdefs{'inststatustypes'}};
1241: @order = @{$domdefs{'inststatusorder'}};
1242: } else {
1243: if (defined(&domain($udom,'primary'))) {
1244: my $uhome=&domain($udom,'primary');
1245: my $rep=&reply("inst_usertypes:$udom",$uhome);
1246: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1247: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1248: return (\%returnhash,\@order);
1249: }
1250: my ($hashitems,$orderitems) = split(/:/,$rep);
1251: my @pairs=split(/\&/,$hashitems);
1252: foreach my $item (@pairs) {
1253: my ($key,$value)=split(/=/,$item,2);
1254: $key = &unescape($key);
1255: next if ($key =~ /^error: 2 /);
1256: $returnhash{$key}=&thaw_unescape($value);
1257: }
1258: my @esc_order = split(/\&/,$orderitems);
1259: foreach my $item (@esc_order) {
1260: push(@order,&unescape($item));
1261: }
1262: } else {
1263: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1264: }
1265: }
1266: return (\%returnhash,\@order);
1267: }
1268:
1.868 raeburn 1269: sub is_domainimage {
1270: my ($url) = @_;
1271: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1272: if (&domain($1) ne '') {
1273: return '1';
1274: }
1275: }
1276: return;
1277: }
1278:
1.899 raeburn 1279: sub inst_directory_query {
1280: my ($srch) = @_;
1281: my $udom = $srch->{'srchdomain'};
1282: my %results;
1283: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1284: my $outcome;
1.899 raeburn 1285: if ($homeserver ne '') {
1.904 albertel 1286: my $queryid=&reply("querysend:instdirsearch:".
1287: &escape($srch->{'srchby'}).':'.
1288: &escape($srch->{'srchterm'}).':'.
1289: &escape($srch->{'srchtype'}),$homeserver);
1290: my $host=&hostname($homeserver);
1291: if ($queryid !~/^\Q$host\E\_/) {
1292: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1293: return;
1294: }
1295: my $response = &get_query_reply($queryid);
1296: my $maxtries = 5;
1297: my $tries = 1;
1298: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1299: $response = &get_query_reply($queryid);
1300: $tries ++;
1301: }
1302:
1303: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1304: if ($response eq 'unavailable') {
1305: $outcome = $response;
1306: } else {
1307: $outcome = 'ok';
1308: my @matches = split(/\n/,$response);
1309: foreach my $match (@matches) {
1310: my ($key,$value) = split(/=/,$match);
1311: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1312: }
1.899 raeburn 1313: }
1314: }
1315: }
1.909 raeburn 1316: return ($outcome,%results);
1.899 raeburn 1317: }
1318:
1319: sub usersearch {
1320: my ($srch) = @_;
1321: my $dom = $srch->{'srchdomain'};
1322: my %results;
1323: my %libserv = &all_library();
1324: my $query = 'usersearch';
1325: foreach my $tryserver (keys(%libserv)) {
1326: if (&host_domain($tryserver) eq $dom) {
1327: my $host=&hostname($tryserver);
1328: my $queryid=
1.911 raeburn 1329: &reply("querysend:".&escape($query).':'.
1330: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1331: &escape($srch->{'srchtype'}).':'.
1332: &escape($srch->{'srchterm'}),$tryserver);
1333: if ($queryid !~/^\Q$host\E\_/) {
1334: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1335: next;
1.899 raeburn 1336: }
1337: my $reply = &get_query_reply($queryid);
1338: my $maxtries = 1;
1339: my $tries = 1;
1340: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1341: $reply = &get_query_reply($queryid);
1342: $tries ++;
1343: }
1344: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1345: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1346: } else {
1.911 raeburn 1347: my @matches;
1348: if ($reply =~ /\n/) {
1349: @matches = split(/\n/,$reply);
1350: } else {
1351: @matches = split(/\&/,$reply);
1352: }
1.899 raeburn 1353: foreach my $match (@matches) {
1354: my ($uname,$udom,%userhash);
1.911 raeburn 1355: foreach my $entry (split(/:/,$match)) {
1356: my ($key,$value) =
1357: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1358: $userhash{$key} = $value;
1359: if ($key eq 'username') {
1360: $uname = $value;
1361: } elsif ($key eq 'domain') {
1362: $udom = $value;
1.911 raeburn 1363: }
1.899 raeburn 1364: }
1365: $results{$uname.':'.$udom} = \%userhash;
1366: }
1367: }
1368: }
1369: }
1370: return %results;
1371: }
1372:
1.912 raeburn 1373: sub get_instuser {
1374: my ($udom,$uname,$id) = @_;
1375: my $homeserver = &domain($udom,'primary');
1376: my ($outcome,%results);
1377: if ($homeserver ne '') {
1378: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1379: &escape($id).':'.&escape($udom),$homeserver);
1380: my $host=&hostname($homeserver);
1381: if ($queryid !~/^\Q$host\E\_/) {
1382: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1383: return;
1384: }
1385: my $response = &get_query_reply($queryid);
1386: my $maxtries = 5;
1387: my $tries = 1;
1388: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1389: $response = &get_query_reply($queryid);
1390: $tries ++;
1391: }
1392: if (!&error($response) && $response ne 'refused') {
1393: if ($response eq 'unavailable') {
1394: $outcome = $response;
1395: } else {
1396: $outcome = 'ok';
1397: my @matches = split(/\n/,$response);
1398: foreach my $match (@matches) {
1399: my ($key,$value) = split(/=/,$match);
1400: $results{&unescape($key)} = &thaw_unescape($value);
1401: }
1402: }
1403: }
1404: }
1405: my %userinfo;
1406: if (ref($results{$uname}) eq 'HASH') {
1407: %userinfo = %{$results{$uname}};
1408: }
1409: return ($outcome,%userinfo);
1410: }
1411:
1412: sub inst_rulecheck {
1.923 raeburn 1413: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1414: my %returnhash;
1415: if ($udom ne '') {
1416: if (ref($rules) eq 'ARRAY') {
1417: @{$rules} = map {&escape($_);} (@{$rules});
1418: my $rulestr = join(':',@{$rules});
1419: my $homeserver=&domain($udom,'primary');
1420: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1421: my $response;
1422: if ($item eq 'username') {
1423: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1424: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1425: $homeserver));
1.923 raeburn 1426: } elsif ($item eq 'id') {
1427: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1428: ':'.&escape($id).':'.$rulestr,
1429: $homeserver));
1.945 raeburn 1430: } elsif ($item eq 'selfcreate') {
1431: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1432: &escape($udom).':'.&escape($uname).
1433: ':'.$rulestr,$homeserver));
1.923 raeburn 1434: }
1.912 raeburn 1435: if ($response ne 'refused') {
1436: my @pairs=split(/\&/,$response);
1437: foreach my $item (@pairs) {
1438: my ($key,$value)=split(/=/,$item,2);
1439: $key = &unescape($key);
1440: next if ($key =~ /^error: 2 /);
1441: $returnhash{$key}=&thaw_unescape($value);
1442: }
1443: }
1444: }
1445: }
1446: }
1447: return %returnhash;
1448: }
1449:
1450: sub inst_userrules {
1.923 raeburn 1451: my ($udom,$check) = @_;
1.912 raeburn 1452: my (%ruleshash,@ruleorder);
1453: if ($udom ne '') {
1454: my $homeserver=&domain($udom,'primary');
1455: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1456: my $response;
1457: if ($check eq 'id') {
1458: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1459: $homeserver);
1.943 raeburn 1460: } elsif ($check eq 'email') {
1461: $response=&reply('instemailrules:'.&escape($udom),
1462: $homeserver);
1.923 raeburn 1463: } else {
1464: $response=&reply('instuserrules:'.&escape($udom),
1465: $homeserver);
1466: }
1.912 raeburn 1467: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1468: ($response ne 'unknown_cmd') &&
1.912 raeburn 1469: ($response ne 'no_such_host')) {
1470: my ($hashitems,$orderitems) = split(/:/,$response);
1471: my @pairs=split(/\&/,$hashitems);
1472: foreach my $item (@pairs) {
1473: my ($key,$value)=split(/=/,$item,2);
1474: $key = &unescape($key);
1475: next if ($key =~ /^error: 2 /);
1476: $ruleshash{$key}=&thaw_unescape($value);
1477: }
1478: my @esc_order = split(/\&/,$orderitems);
1479: foreach my $item (@esc_order) {
1480: push(@ruleorder,&unescape($item));
1481: }
1482: }
1483: }
1484: }
1485: return (\%ruleshash,\@ruleorder);
1486: }
1487:
1.976 raeburn 1488: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1489:
1490: sub get_domain_defaults {
1491: my ($domain) = @_;
1492: my $cachetime = 60*60*24;
1493: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1494: if (defined($cached)) {
1495: if (ref($result) eq 'HASH') {
1496: return %{$result};
1497: }
1498: }
1499: my %domdefaults;
1500: my %domconfig =
1.989 raeburn 1501: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1502: 'requestcourses','inststatus',
1.1073 raeburn 1503: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1504: if (ref($domconfig{'defaults'}) eq 'HASH') {
1505: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1506: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1507: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1508: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1509: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1510: } else {
1511: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1512: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1513: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1514: }
1.976 raeburn 1515: if (ref($domconfig{'quotas'}) eq 'HASH') {
1516: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1517: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1518: } else {
1519: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1520: }
1521: my @usertools = ('aboutme','blog','portfolio');
1522: foreach my $item (@usertools) {
1523: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1524: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1525: }
1526: }
1527: }
1.985 raeburn 1528: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1529: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1530: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1531: }
1532: }
1.989 raeburn 1533: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1534: foreach my $item ('inststatustypes','inststatusorder') {
1535: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1536: }
1537: }
1.1047 raeburn 1538: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1539: foreach my $item ('canuse_pdfforms') {
1540: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1541: }
1542: }
1.1073 raeburn 1543: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1544: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1545: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1546: }
1547: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1548: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1549: }
1550: }
1.943 raeburn 1551: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1552: $cachetime);
1553: return %domdefaults;
1554: }
1555:
1.344 www 1556: # --------------------------------------------------- Assign a key to a student
1557:
1558: sub assign_access_key {
1.364 www 1559: #
1560: # a valid key looks like uname:udom#comments
1561: # comments are being appended
1562: #
1.498 www 1563: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1564: $kdom=
1.620 albertel 1565: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1566: $knum=
1.620 albertel 1567: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1568: $cdom=
1.620 albertel 1569: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1570: $cnum=
1.620 albertel 1571: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1572: $udom=$env{'user.name'} unless (defined($udom));
1573: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1574: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1575: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1576: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1577: # assigned to this person
1578: # - this should not happen,
1.345 www 1579: # unless something went wrong
1580: # the first time around
1581: # ready to assign
1.364 www 1582: $logentry=$1.'; '.$logentry;
1.496 www 1583: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1584: $kdom,$knum) eq 'ok') {
1.345 www 1585: # key now belongs to user
1.346 www 1586: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1587: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1588: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1589: return 'ok';
1590: } else {
1591: return
1592: 'error: Count not permanently assign key, will need to be re-entered later.';
1593: }
1594: } else {
1595: return 'error: Could not assign key, try again later.';
1596: }
1.364 www 1597: } elsif (!$existing{$ckey}) {
1.345 www 1598: # the key does not exist
1599: return 'error: The key does not exist';
1600: } else {
1601: # the key is somebody else's
1602: return 'error: The key is already in use';
1603: }
1.344 www 1604: }
1605:
1.364 www 1606: # ------------------------------------------ put an additional comment on a key
1607:
1608: sub comment_access_key {
1609: #
1610: # a valid key looks like uname:udom#comments
1611: # comments are being appended
1612: #
1613: my ($ckey,$cdom,$cnum,$logentry)=@_;
1614: $cdom=
1.620 albertel 1615: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1616: $cnum=
1.620 albertel 1617: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1618: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1619: if ($existing{$ckey}) {
1620: $existing{$ckey}.='; '.$logentry;
1621: # ready to assign
1.367 www 1622: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1623: $cdom,$cnum) eq 'ok') {
1624: return 'ok';
1625: } else {
1626: return 'error: Count not store comment.';
1627: }
1628: } else {
1629: # the key does not exist
1630: return 'error: The key does not exist';
1631: }
1632: }
1633:
1.344 www 1634: # ------------------------------------------------------ Generate a set of keys
1635:
1636: sub generate_access_keys {
1.364 www 1637: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1638: $cdom=
1.620 albertel 1639: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1640: $cnum=
1.620 albertel 1641: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1642: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1643: unless (($cdom) && ($cnum)) { return 0; }
1644: if ($number>10000) { return 0; }
1645: sleep(2); # make sure don't get same seed twice
1646: srand(time()^($$+($$<<15))); # from "Programming Perl"
1647: my $total=0;
1648: for (my $i=1;$i<=$number;$i++) {
1649: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1650: sprintf("%lx",int(100000*rand)).'-'.
1651: sprintf("%lx",int(100000*rand));
1652: $newkey=~s/1/g/g; # folks mix up 1 and l
1653: $newkey=~s/0/h/g; # and also 0 and O
1654: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1655: if ($existing{$newkey}) {
1656: $i--;
1657: } else {
1.364 www 1658: if (&put('accesskeys',
1659: { $newkey => '# generated '.localtime().
1.620 albertel 1660: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1661: '; '.$logentry },
1662: $cdom,$cnum) eq 'ok') {
1.344 www 1663: $total++;
1664: }
1665: }
1666: }
1.620 albertel 1667: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1668: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1669: return $total;
1670: }
1671:
1672: # ------------------------------------------------------- Validate an accesskey
1673:
1674: sub validate_access_key {
1675: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1676: $cdom=
1.620 albertel 1677: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1678: $cnum=
1.620 albertel 1679: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1680: $udom=$env{'user.domain'} unless (defined($udom));
1681: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1682: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1683: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1684: }
1685:
1686: # ------------------------------------- Find the section of student in a course
1.652 albertel 1687: sub devalidate_getsection_cache {
1688: my ($udom,$unam,$courseid)=@_;
1689: my $hashid="$udom:$unam:$courseid";
1690: &devalidate_cache_new('getsection',$hashid);
1691: }
1.298 matthew 1692:
1.815 albertel 1693: sub courseid_to_courseurl {
1694: my ($courseid) = @_;
1695: #already url style courseid
1696: return $courseid if ($courseid =~ m{^/});
1697:
1698: if (exists($env{'course.'.$courseid.'.num'})) {
1699: my $cnum = $env{'course.'.$courseid.'.num'};
1700: my $cdom = $env{'course.'.$courseid.'.domain'};
1701: return "/$cdom/$cnum";
1702: }
1703:
1704: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1705: if (exists($courseinfo{'num'})) {
1706: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1707: }
1708:
1709: return undef;
1710: }
1711:
1.298 matthew 1712: sub getsection {
1713: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1714: my $cachetime=1800;
1.551 albertel 1715:
1716: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1717: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1718: if (defined($cached)) { return $result; }
1719:
1.298 matthew 1720: my %Pending;
1721: my %Expired;
1722: #
1723: # Each role can either have not started yet (pending), be active,
1724: # or have expired.
1725: #
1726: # If there is an active role, we are done.
1727: #
1728: # If there is more than one role which has not started yet,
1729: # choose the one which will start sooner
1730: # If there is one role which has not started yet, return it.
1731: #
1732: # If there is more than one expired role, choose the one which ended last.
1733: # If there is a role which has expired, return it.
1734: #
1.815 albertel 1735: $courseid = &courseid_to_courseurl($courseid);
1.1086 ! raeburn 1736: my $extra = &freeze_escape({'skipcheck' => 1});
! 1737: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 1738: foreach my $key (keys(%roleshash)) {
1.479 albertel 1739: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1740: my $section=$1;
1741: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1742: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1743: my $now=time;
1.548 albertel 1744: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1745: $Expired{$end}=$section;
1746: next;
1747: }
1.548 albertel 1748: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1749: $Pending{$start}=$section;
1750: next;
1751: }
1.599 albertel 1752: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1753: }
1754: #
1755: # Presumedly there will be few matching roles from the above
1756: # loop and the sorting time will be negligible.
1757: if (scalar(keys(%Pending))) {
1758: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1759: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1760: }
1761: if (scalar(keys(%Expired))) {
1762: my @sorted = sort {$a <=> $b} keys(%Expired);
1763: my $time = pop(@sorted);
1.599 albertel 1764: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1765: }
1.599 albertel 1766: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1767: }
1.70 www 1768:
1.599 albertel 1769: sub save_cache {
1770: &purge_remembered();
1.722 albertel 1771: #&Apache::loncommon::validate_page();
1.620 albertel 1772: undef(%env);
1.780 albertel 1773: undef($env_loaded);
1.599 albertel 1774: }
1.452 albertel 1775:
1.599 albertel 1776: my $to_remember=-1;
1777: my %remembered;
1778: my %accessed;
1779: my $kicks=0;
1780: my $hits=0;
1.849 albertel 1781: sub make_key {
1782: my ($name,$id) = @_;
1.872 albertel 1783: if (length($id) > 65
1784: && length(&escape($id)) > 200) {
1785: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1786: }
1.849 albertel 1787: return &escape($name.':'.$id);
1788: }
1789:
1.599 albertel 1790: sub devalidate_cache_new {
1791: my ($name,$id,$debug) = @_;
1792: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1793: $id=&make_key($name,$id);
1.599 albertel 1794: $memcache->delete($id);
1795: delete($remembered{$id});
1796: delete($accessed{$id});
1797: }
1798:
1799: sub is_cached_new {
1800: my ($name,$id,$debug) = @_;
1.849 albertel 1801: $id=&make_key($name,$id);
1.599 albertel 1802: if (exists($remembered{$id})) {
1803: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1804: $accessed{$id}=[&gettimeofday()];
1805: $hits++;
1806: return ($remembered{$id},1);
1807: }
1808: my $value = $memcache->get($id);
1809: if (!(defined($value))) {
1810: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1811: return (undef,undef);
1.416 albertel 1812: }
1.599 albertel 1813: if ($value eq '__undef__') {
1814: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1815: $value=undef;
1816: }
1817: &make_room($id,$value,$debug);
1818: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1819: return ($value,1);
1820: }
1821:
1822: sub do_cache_new {
1823: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1824: $id=&make_key($name,$id);
1.599 albertel 1825: my $setvalue=$value;
1826: if (!defined($setvalue)) {
1827: $setvalue='__undef__';
1828: }
1.623 albertel 1829: if (!defined($time) ) {
1830: $time=600;
1831: }
1.599 albertel 1832: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1833: my $result = $memcache->set($id,$setvalue,$time);
1834: if (! $result) {
1.872 albertel 1835: &logthis("caching of id -> $id failed");
1.910 albertel 1836: $memcache->disconnect_all();
1.872 albertel 1837: }
1.600 albertel 1838: # need to make a copy of $value
1.919 albertel 1839: &make_room($id,$value,$debug);
1.599 albertel 1840: return $value;
1841: }
1842:
1843: sub make_room {
1844: my ($id,$value,$debug)=@_;
1.919 albertel 1845:
1846: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1847: : $value;
1.599 albertel 1848: if ($to_remember<0) { return; }
1849: $accessed{$id}=[&gettimeofday()];
1850: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1851: my $to_kick;
1852: my $max_time=0;
1853: foreach my $other (keys(%accessed)) {
1854: if (&tv_interval($accessed{$other}) > $max_time) {
1855: $to_kick=$other;
1856: $max_time=&tv_interval($accessed{$other});
1857: }
1858: }
1859: delete($remembered{$to_kick});
1860: delete($accessed{$to_kick});
1861: $kicks++;
1862: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1863: return;
1864: }
1865:
1.599 albertel 1866: sub purge_remembered {
1.604 albertel 1867: #&logthis("Tossing ".scalar(keys(%remembered)));
1868: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1869: undef(%remembered);
1870: undef(%accessed);
1.428 albertel 1871: }
1.70 www 1872: # ------------------------------------- Read an entry from a user's environment
1873:
1874: sub userenvironment {
1875: my ($udom,$unam,@what)=@_;
1.976 raeburn 1876: my $items;
1877: foreach my $item (@what) {
1878: $items.=&escape($item).'&';
1879: }
1880: $items=~s/\&$//;
1.70 www 1881: my %returnhash=();
1.1009 raeburn 1882: my $uhome = &homeserver($unam,$udom);
1883: unless ($uhome eq 'no_host') {
1884: my @answer=split(/\&/,
1885: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1886: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1887: return %returnhash;
1888: }
1.1009 raeburn 1889: my $i;
1890: for ($i=0;$i<=$#what;$i++) {
1891: $returnhash{$what[$i]}=&unescape($answer[$i]);
1892: }
1.70 www 1893: }
1894: return %returnhash;
1.1 albertel 1895: }
1896:
1.617 albertel 1897: # ---------------------------------------------------------- Get a studentphoto
1898: sub studentphoto {
1899: my ($udom,$unam,$ext) = @_;
1900: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1901: if (defined($env{'request.course.id'})) {
1.708 raeburn 1902: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1903: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1904: return(&retrievestudentphoto($udom,$unam,$ext));
1905: } else {
1906: my ($result,$perm_reqd)=
1.707 albertel 1907: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1908: if ($result eq 'ok') {
1909: if (!($perm_reqd eq 'yes')) {
1910: return(&retrievestudentphoto($udom,$unam,$ext));
1911: }
1912: }
1913: }
1914: }
1915: } else {
1916: my ($result,$perm_reqd) =
1.707 albertel 1917: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1918: if ($result eq 'ok') {
1919: if (!($perm_reqd eq 'yes')) {
1920: return(&retrievestudentphoto($udom,$unam,$ext));
1921: }
1922: }
1923: }
1924: return '/adm/lonKaputt/lonlogo_broken.gif';
1925: }
1926:
1927: sub retrievestudentphoto {
1928: my ($udom,$unam,$ext,$type) = @_;
1929: my $home=&Apache::lonnet::homeserver($unam,$udom);
1930: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1931: if ($ret eq 'ok') {
1932: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1933: if ($type eq 'thumbnail') {
1934: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1935: }
1936: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1937: return $tokenurl;
1938: } else {
1939: if ($type eq 'thumbnail') {
1940: return '/adm/lonKaputt/genericstudent_tn.gif';
1941: } else {
1942: return '/adm/lonKaputt/lonlogo_broken.gif';
1943: }
1.617 albertel 1944: }
1945: }
1946:
1.263 www 1947: # -------------------------------------------------------------------- New chat
1948:
1949: sub chatsend {
1.724 raeburn 1950: my ($newentry,$anon,$group)=@_;
1.620 albertel 1951: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1952: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1953: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1954: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1955: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1956: &escape($newentry)).':'.$group,$chome);
1.292 www 1957: }
1958:
1959: # ------------------------------------------ Find current version of a resource
1960:
1961: sub getversion {
1962: my $fname=&clutter(shift);
1963: unless ($fname=~/^\/res\//) { return -1; }
1964: return ¤tversion(&filelocation('',$fname));
1965: }
1966:
1967: sub currentversion {
1968: my $fname=shift;
1.599 albertel 1969: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1970: if (defined($cached)) { return $result; }
1.292 www 1971: my $author=$fname;
1972: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1973: my ($udom,$uname)=split(/\//,$author);
1974: my $home=homeserver($uname,$udom);
1975: if ($home eq 'no_host') {
1976: return -1;
1977: }
1978: my $answer=reply("currentversion:$fname",$home);
1979: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1980: return -1;
1981: }
1.599 albertel 1982: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1983: }
1984:
1.1 albertel 1985: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1986:
1.1 albertel 1987: sub subscribe {
1988: my $fname=shift;
1.761 raeburn 1989: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1990: $fname=~s/[\n\r]//g;
1.1 albertel 1991: my $author=$fname;
1992: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1993: my ($udom,$uname)=split(/\//,$author);
1994: my $home=homeserver($uname,$udom);
1.335 albertel 1995: if ($home eq 'no_host') {
1996: return 'not_found';
1.1 albertel 1997: }
1998: my $answer=reply("sub:$fname",$home);
1.64 www 1999: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2000: $answer.=' by '.$home;
2001: }
1.1 albertel 2002: return $answer;
2003: }
2004:
1.8 www 2005: # -------------------------------------------------------------- Replicate file
2006:
2007: sub repcopy {
2008: my $filename=shift;
1.23 www 2009: $filename=~s/\/+/\//g;
1.607 raeburn 2010: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2011: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2012: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2013: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2014: return &repcopy_userfile($filename);
2015: }
1.532 albertel 2016: $filename=~s/[\n\r]//g;
1.8 www 2017: my $transname="$filename.in.transfer";
1.828 www 2018: # FIXME: this should flock
1.607 raeburn 2019: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2020: my $remoteurl=subscribe($filename);
1.64 www 2021: if ($remoteurl =~ /^con_lost by/) {
2022: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2023: return 'unavailable';
1.8 www 2024: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2025: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2026: return 'not_found';
1.64 www 2027: } elsif ($remoteurl =~ /^rejected by/) {
2028: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2029: return 'forbidden';
1.20 www 2030: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2031: return 'ok';
1.8 www 2032: } else {
1.290 www 2033: my $author=$filename;
2034: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2035: my ($udom,$uname)=split(/\//,$author);
2036: my $home=homeserver($uname,$udom);
2037: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2038: my @parts=split(/\//,$filename);
2039: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2040: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2041: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2042: return 'bad_request';
1.8 www 2043: }
2044: my $count;
2045: for ($count=5;$count<$#parts;$count++) {
2046: $path.="/$parts[$count]";
2047: if ((-e $path)!=1) {
2048: mkdir($path,0777);
2049: }
2050: }
2051: my $ua=new LWP::UserAgent;
2052: my $request=new HTTP::Request('GET',"$remoteurl");
2053: my $response=$ua->request($request,$transname);
2054: if ($response->is_error()) {
2055: unlink($transname);
2056: my $message=$response->status_line;
1.672 albertel 2057: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2058: ." LWP get: $message: $filename</font>");
1.607 raeburn 2059: return 'unavailable';
1.8 www 2060: } else {
1.16 www 2061: if ($remoteurl!~/\.meta$/) {
2062: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2063: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2064: if ($mresponse->is_error()) {
2065: unlink($filename.'.meta');
2066: &logthis(
1.672 albertel 2067: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2068: }
2069: }
1.8 www 2070: rename($transname,$filename);
1.607 raeburn 2071: return 'ok';
1.8 www 2072: }
1.290 www 2073: }
1.8 www 2074: }
1.330 www 2075: }
2076:
2077: # ------------------------------------------------ Get server side include body
2078: sub ssi_body {
1.381 albertel 2079: my ($filelink,%form)=@_;
1.606 matthew 2080: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2081: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2082: }
1.953 www 2083: my $output='';
2084: my $response;
1.980 raeburn 2085: if ($filelink=~/^https?\:/) {
1.954 raeburn 2086: ($output,$response)=&externalssi($filelink);
1.953 www 2087: } else {
1.1004 droeschl 2088: $filelink .= $filelink=~/\?/ ? '&' : '?';
2089: $filelink .= 'inhibitmenu=yes';
1.953 www 2090: ($output,$response)=&ssi($filelink,%form);
2091: }
1.778 albertel 2092: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2093: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2094: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2095: if (wantarray) {
2096: return ($output, $response);
2097: } else {
2098: return $output;
2099: }
1.8 www 2100: }
2101:
1.15 www 2102: # --------------------------------------------------------- Server Side Include
2103:
1.782 albertel 2104: sub absolute_url {
2105: my ($host_name) = @_;
2106: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2107: if ($host_name eq '') {
2108: $host_name = $ENV{'SERVER_NAME'};
2109: }
2110: return $protocol.$host_name;
2111: }
2112:
1.942 foxr 2113: #
2114: # Server side include.
2115: # Parameters:
2116: # fn Possibly encrypted resource name/id.
2117: # form Hash that describes how the rendering should be done
2118: # and other things.
1.944 foxr 2119: # Returns:
1.950 raeburn 2120: # Scalar context: The content of the response.
2121: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2122: #
1.15 www 2123: sub ssi {
2124:
1.944 foxr 2125: my ($fn,%form)=@_;
1.15 www 2126: my $ua=new LWP::UserAgent;
1.23 www 2127: my $request;
1.711 albertel 2128:
2129: $form{'no_update_last_known'}=1;
1.895 albertel 2130: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2131: if (%form) {
1.782 albertel 2132: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2133: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2134: } else {
1.782 albertel 2135: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2136: }
2137:
1.15 www 2138: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2139: my $response=$ua->request($request);
2140:
1.944 foxr 2141: if (wantarray) {
2142: return ($response->content, $response);
2143: } else {
2144: return $response->content;
1.942 foxr 2145: }
1.324 www 2146: }
2147:
2148: sub externalssi {
2149: my ($url)=@_;
2150: my $ua=new LWP::UserAgent;
2151: my $request=new HTTP::Request('GET',$url);
2152: my $response=$ua->request($request);
1.954 raeburn 2153: if (wantarray) {
2154: return ($response->content, $response);
2155: } else {
2156: return $response->content;
2157: }
1.15 www 2158: }
1.254 www 2159:
1.492 albertel 2160: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2161:
2162: sub allowuploaded {
2163: my ($srcurl,$url)=@_;
2164: $url=&clutter(&declutter($url));
2165: my $dir=$url;
2166: $dir=~s/\/[^\/]+$//;
2167: my %httpref=();
2168: my $httpurl=&hreflocation('',$url);
2169: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2170: &Apache::lonnet::appenv(\%httpref);
1.254 www 2171: }
1.477 raeburn 2172:
1.478 albertel 2173: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2174: # input: action, courseID, current domain, intended
1.637 raeburn 2175: # path to file, source of file, instruction to parse file for objects,
2176: # ref to hash for embedded objects,
2177: # ref to hash for codebase of java objects.
2178: #
1.485 raeburn 2179: # output: url to file (if action was uploaddoc),
2180: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2181: #
1.478 albertel 2182: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2183: # course.
1.477 raeburn 2184: #
1.478 albertel 2185: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2186: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2187: # course's home server.
1.477 raeburn 2188: #
1.478 albertel 2189: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2190: # be copied from $source (current location) to
2191: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2192: # and will then be copied to
2193: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2194: # course's home server.
1.485 raeburn 2195: #
1.481 raeburn 2196: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2197: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2198: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2199: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2200: # in course's home server.
1.637 raeburn 2201: #
1.477 raeburn 2202:
2203: sub process_coursefile {
1.638 albertel 2204: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 2205: my $fetchresult;
1.638 albertel 2206: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2207: if ($action eq 'propagate') {
1.638 albertel 2208: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2209: $home);
1.481 raeburn 2210: } else {
1.477 raeburn 2211: my $fpath = '';
2212: my $fname = $file;
1.478 albertel 2213: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2214: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2215: my $filepath = &build_filepath($fpath);
1.481 raeburn 2216: if ($action eq 'copy') {
2217: if ($source eq '') {
2218: $fetchresult = 'no source file';
2219: return $fetchresult;
2220: } else {
2221: my $destination = $filepath.'/'.$fname;
2222: rename($source,$destination);
2223: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2224: $home);
1.481 raeburn 2225: }
2226: } elsif ($action eq 'uploaddoc') {
2227: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2228: print $fh $env{'form.'.$source};
1.481 raeburn 2229: close($fh);
1.637 raeburn 2230: if ($parser eq 'parse') {
1.1024 raeburn 2231: my $mm = new File::MMagic;
2232: my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
2233: if ($mime_type eq 'text/html') {
2234: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2235: unless ($parse_result eq 'ok') {
2236: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2237: }
1.637 raeburn 2238: }
2239: }
1.477 raeburn 2240: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2241: $home);
1.481 raeburn 2242: if ($fetchresult eq 'ok') {
2243: return '/uploaded/'.$fpath.'/'.$fname;
2244: } else {
2245: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2246: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2247: return '/adm/notfound.html';
2248: }
1.477 raeburn 2249: }
2250: }
1.485 raeburn 2251: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2252: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2253: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2254: }
2255: return $fetchresult;
2256: }
2257:
1.637 raeburn 2258: sub build_filepath {
2259: my ($fpath) = @_;
2260: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2261: unless ($fpath eq '') {
2262: my @parts=split('/',$fpath);
2263: foreach my $part (@parts) {
2264: $filepath.= '/'.$part;
2265: if ((-e $filepath)!=1) {
2266: mkdir($filepath,0777);
2267: }
2268: }
2269: }
2270: return $filepath;
2271: }
2272:
2273: sub store_edited_file {
1.638 albertel 2274: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2275: my $file = $primary_url;
2276: $file =~ s#^/uploaded/$docudom/$docuname/##;
2277: my $fpath = '';
2278: my $fname = $file;
2279: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2280: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2281: my $filepath = &build_filepath($fpath);
2282: open(my $fh,'>'.$filepath.'/'.$fname);
2283: print $fh $content;
2284: close($fh);
1.638 albertel 2285: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2286: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2287: $home);
1.637 raeburn 2288: if ($$fetchresult eq 'ok') {
2289: return '/uploaded/'.$fpath.'/'.$fname;
2290: } else {
1.638 albertel 2291: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2292: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2293: return '/adm/notfound.html';
2294: }
2295: }
2296:
1.531 albertel 2297: sub clean_filename {
1.831 albertel 2298: my ($fname,$args)=@_;
1.315 www 2299: # Replace Windows backslashes by forward slashes
1.257 www 2300: $fname=~s/\\/\//g;
1.831 albertel 2301: if (!$args->{'keep_path'}) {
2302: # Get rid of everything but the actual filename
2303: $fname=~s/^.*\/([^\/]+)$/$1/;
2304: }
1.315 www 2305: # Replace spaces by underscores
2306: $fname=~s/\s+/\_/g;
2307: # Replace all other weird characters by nothing
1.831 albertel 2308: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2309: # Replace all .\d. sequences with _\d. so they no longer look like version
2310: # numbers
2311: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2312: return $fname;
2313: }
1.1051 raeburn 2314: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2315: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2316: # image with the same aspect ratio as the original, but with dimensions which do
2317: # not exceed $resizewidth and $resizeheight.
2318:
1.984 neumanie 2319: sub resizeImage {
1.1051 raeburn 2320: my ($img_path,$resizewidth,$resizeheight) = @_;
2321: my $ima = Image::Magick->new;
2322: my $resized;
2323: if (-e $img_path) {
2324: $ima->Read($img_path);
2325: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2326: my $width = $ima->Get('width');
2327: my $height = $ima->Get('height');
2328: if ($width > $resizewidth) {
2329: my $factor = $width/$resizewidth;
2330: my $newheight = $height/$factor;
2331: $ima->Scale(width=>$resizewidth,height=>$newheight);
2332: $resized = 1;
2333: }
2334: }
2335: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2336: my $width = $ima->Get('width');
2337: my $height = $ima->Get('height');
2338: if ($height > $resizeheight) {
2339: my $factor = $height/$resizeheight;
2340: my $newwidth = $width/$factor;
2341: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2342: $resized = 1;
2343: }
2344: }
2345: if ($resized) {
2346: $ima->Write($img_path);
2347: }
2348: }
2349: return;
1.977 amueller 2350: }
2351:
1.608 albertel 2352: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2353: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2354: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2355: # $coursedoc - if true up to the current course
2356: # if false
2357: # $subdir - directory in userfile to store the file into
1.858 raeburn 2358: # $parser - instruction to parse file for objects ($parser = parse)
2359: # $allfiles - reference to hash for embedded objects
2360: # $codebase - reference to hash for codebase of java objects
2361: # $desuname - username for permanent storage of uploaded file
2362: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2363: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2364: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2365: # $resizewidth - width (pixels) to which to resize uploaded image
2366: # $resizeheight - height (pixels) to which to resize uploaded image
1.858 raeburn 2367: #
1.686 albertel 2368: # output: url of file in userspace, or error: <message>
2369: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2370:
1.531 albertel 2371: sub userfileupload {
1.860 raeburn 2372: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051 raeburn 2373: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531 albertel 2374: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2375: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2376: $fname=&clean_filename($fname);
1.315 www 2377: # See if there is anything left
1.257 www 2378: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2379: chop($env{'form.'.$formname});
1.523 raeburn 2380: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2381: my $now = time;
2382: my $filepath = 'tmp/helprequests/'.$now;
2383: my @parts=split(/\//,$filepath);
2384: my $fullpath = $perlvar{'lonDaemons'};
2385: for (my $i=0;$i<@parts;$i++) {
2386: $fullpath .= '/'.$parts[$i];
2387: if ((-e $fullpath)!=1) {
2388: mkdir($fullpath,0777);
2389: }
2390: }
2391: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2392: print $fh $env{'form.'.$formname};
1.523 raeburn 2393: close($fh);
1.741 raeburn 2394: return $fullpath.'/'.$fname;
2395: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2396: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2397: '_'.$env{'user.domain'}.'/pending';
2398: my @parts=split(/\//,$filepath);
2399: my $fullpath = $perlvar{'lonDaemons'};
2400: for (my $i=0;$i<@parts;$i++) {
2401: $fullpath .= '/'.$parts[$i];
2402: if ((-e $fullpath)!=1) {
2403: mkdir($fullpath,0777);
2404: }
2405: }
2406: open(my $fh,'>'.$fullpath.'/'.$fname);
2407: print $fh $env{'form.'.$formname};
2408: close($fh);
2409: return $fullpath.'/'.$fname;
1.523 raeburn 2410: }
1.995 raeburn 2411: if ($subdir eq 'scantron') {
2412: $fname = 'scantron_orig_'.$fname;
2413: } else {
1.258 www 2414: # Create the directory if not present
1.995 raeburn 2415: $fname="$subdir/$fname";
2416: }
1.259 www 2417: if ($coursedoc) {
1.638 albertel 2418: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2419: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2420: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2421: return &finishuserfileupload($docuname,$docudom,
2422: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2423: $codebase,$thumbwidth,$thumbheight,
2424: $resizewidth,$resizeheight);
1.481 raeburn 2425: } else {
1.620 albertel 2426: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2427: return &process_coursefile('uploaddoc',$docuname,$docudom,
2428: $fname,$formname,$parser,
2429: $allfiles,$codebase);
1.481 raeburn 2430: }
1.719 banghart 2431: } elsif (defined($destuname)) {
2432: my $docuname=$destuname;
2433: my $docudom=$destudom;
1.860 raeburn 2434: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2435: $parser,$allfiles,$codebase,
1.1051 raeburn 2436: $thumbwidth,$thumbheight,
2437: $resizewidth,$resizeheight);
1.719 banghart 2438:
1.259 www 2439: } else {
1.638 albertel 2440: my $docuname=$env{'user.name'};
2441: my $docudom=$env{'user.domain'};
1.714 raeburn 2442: if (exists($env{'form.group'})) {
2443: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2444: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2445: }
1.860 raeburn 2446: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2447: $parser,$allfiles,$codebase,
1.1051 raeburn 2448: $thumbwidth,$thumbheight,
2449: $resizewidth,$resizeheight);
1.259 www 2450: }
1.271 www 2451: }
2452:
2453: sub finishuserfileupload {
1.860 raeburn 2454: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051 raeburn 2455: $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477 raeburn 2456: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2457: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2458:
1.860 raeburn 2459: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2460: $file=$fname;
2461: if ($fname=~m|/|) {
2462: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2463: $path.=$fnamepath.'/';
2464: }
1.259 www 2465: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2466: my $count;
2467: for ($count=4;$count<=$#parts;$count++) {
2468: $filepath.="/$parts[$count]";
2469: if ((-e $filepath)!=1) {
2470: mkdir($filepath,0777);
2471: }
2472: }
1.984 neumanie 2473:
1.258 www 2474: # Save the file
2475: {
1.701 albertel 2476: if (!open(FH,'>'.$filepath.'/'.$file)) {
2477: &logthis('Failed to create '.$filepath.'/'.$file);
2478: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2479: return '/adm/notfound.html';
2480: }
2481: if (!print FH ($env{'form.'.$formname})) {
2482: &logthis('Failed to write to '.$filepath.'/'.$file);
2483: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2484: return '/adm/notfound.html';
2485: }
1.570 albertel 2486: close(FH);
1.1051 raeburn 2487: if ($resizewidth && $resizeheight) {
2488: my $mm = new File::MMagic;
2489: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2490: if ($mime_type =~ m{^image/}) {
2491: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2492: }
1.977 amueller 2493: }
1.258 www 2494: }
1.637 raeburn 2495: if ($parser eq 'parse') {
1.1024 raeburn 2496: my $mm = new File::MMagic;
2497: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2498: if ($mime_type eq 'text/html') {
2499: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2500: $allfiles,$codebase);
2501: unless ($parse_result eq 'ok') {
2502: &logthis('Failed to parse '.$filepath.$file.
2503: ' for embedded media: '.$parse_result);
2504: }
1.637 raeburn 2505: }
2506: }
1.860 raeburn 2507: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2508: my $input = $filepath.'/'.$file;
2509: my $output = $filepath.'/'.'tn-'.$file;
2510: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2511: system("convert -sample $thumbsize $input $output");
2512: if (-e $filepath.'/'.'tn-'.$file) {
2513: $fetchthumb = 1;
2514: }
2515: }
1.858 raeburn 2516:
1.259 www 2517: # Notify homeserver to grep it
2518: #
1.984 neumanie 2519: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2520: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2521: if ($fetchresult eq 'ok') {
1.860 raeburn 2522: if ($fetchthumb) {
2523: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2524: if ($thumbresult ne 'ok') {
2525: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2526: $docuhome.': '.$thumbresult);
2527: }
2528: }
1.259 www 2529: #
1.258 www 2530: # Return the URL to it
1.494 albertel 2531: return '/uploaded/'.$path.$file;
1.263 www 2532: } else {
1.494 albertel 2533: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2534: ': '.$fetchresult);
1.263 www 2535: return '/adm/notfound.html';
1.858 raeburn 2536: }
1.493 albertel 2537: }
2538:
1.637 raeburn 2539: sub extract_embedded_items {
1.961 raeburn 2540: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2541: my @state = ();
2542: my %javafiles = (
2543: codebase => '',
2544: code => '',
2545: archive => ''
2546: );
2547: my %mediafiles = (
2548: src => '',
2549: movie => '',
2550: );
1.648 raeburn 2551: my $p;
2552: if ($content) {
2553: $p = HTML::LCParser->new($content);
2554: } else {
1.961 raeburn 2555: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2556: }
1.641 albertel 2557: while (my $t=$p->get_token()) {
1.640 albertel 2558: if ($t->[0] eq 'S') {
2559: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2560: push(@state, $tagname);
1.648 raeburn 2561: if (lc($tagname) eq 'allow') {
2562: &add_filetype($allfiles,$attr->{'src'},'src');
2563: }
1.640 albertel 2564: if (lc($tagname) eq 'img') {
2565: &add_filetype($allfiles,$attr->{'src'},'src');
2566: }
1.886 albertel 2567: if (lc($tagname) eq 'a') {
2568: &add_filetype($allfiles,$attr->{'href'},'href');
2569: }
1.645 raeburn 2570: if (lc($tagname) eq 'script') {
2571: if ($attr->{'archive'} =~ /\.jar$/i) {
2572: &add_filetype($allfiles,$attr->{'archive'},'archive');
2573: } else {
2574: &add_filetype($allfiles,$attr->{'src'},'src');
2575: }
2576: }
2577: if (lc($tagname) eq 'link') {
2578: if (lc($attr->{'rel'}) eq 'stylesheet') {
2579: &add_filetype($allfiles,$attr->{'href'},'href');
2580: }
2581: }
1.640 albertel 2582: if (lc($tagname) eq 'object' ||
2583: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2584: foreach my $item (keys(%javafiles)) {
2585: $javafiles{$item} = '';
2586: }
2587: }
2588: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2589: my $name = lc($attr->{'name'});
2590: foreach my $item (keys(%javafiles)) {
2591: if ($name eq $item) {
2592: $javafiles{$item} = $attr->{'value'};
2593: last;
2594: }
2595: }
2596: foreach my $item (keys(%mediafiles)) {
2597: if ($name eq $item) {
2598: &add_filetype($allfiles, $attr->{'value'}, 'value');
2599: last;
2600: }
2601: }
2602: }
2603: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2604: foreach my $item (keys(%javafiles)) {
2605: if ($attr->{$item}) {
2606: $javafiles{$item} = $attr->{$item};
2607: last;
2608: }
2609: }
2610: foreach my $item (keys(%mediafiles)) {
2611: if ($attr->{$item}) {
2612: &add_filetype($allfiles,$attr->{$item},$item);
2613: last;
2614: }
2615: }
2616: }
2617: } elsif ($t->[0] eq 'E') {
2618: my ($tagname) = ($t->[1]);
2619: if ($javafiles{'codebase'} ne '') {
2620: $javafiles{'codebase'} .= '/';
2621: }
2622: if (lc($tagname) eq 'applet' ||
2623: lc($tagname) eq 'object' ||
2624: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2625: ) {
2626: foreach my $item (keys(%javafiles)) {
2627: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2628: my $file=$javafiles{'codebase'}.$javafiles{$item};
2629: &add_filetype($allfiles,$file,$item);
2630: }
2631: }
2632: }
2633: pop @state;
2634: }
2635: }
1.637 raeburn 2636: return 'ok';
2637: }
2638:
1.639 albertel 2639: sub add_filetype {
2640: my ($allfiles,$file,$type)=@_;
2641: if (exists($allfiles->{$file})) {
2642: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2643: push(@{$allfiles->{$file}}, &escape($type));
2644: }
2645: } else {
2646: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2647: }
2648: }
2649:
1.493 albertel 2650: sub removeuploadedurl {
1.984 neumanie 2651: my ($url)=@_;
2652: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2653: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2654: }
2655:
2656: sub removeuserfile {
2657: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2658: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2659: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2660: if ($result eq 'ok') {
1.798 raeburn 2661: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2662: my $metafile = $fname.'.meta';
2663: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2664: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2665: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2666: my $sqlresult =
1.823 albertel 2667: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2668: 'portfolio_metadata',$group,
2669: 'delete');
1.798 raeburn 2670: }
2671: }
2672: return $result;
1.257 www 2673: }
1.15 www 2674:
1.530 albertel 2675: sub mkdiruserfile {
2676: my ($docuname,$docudom,$dir)=@_;
2677: my $home=&homeserver($docuname,$docudom);
2678: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2679: }
2680:
1.531 albertel 2681: sub renameuserfile {
2682: my ($docuname,$docudom,$old,$new)=@_;
2683: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2684: my $result = &reply("renameuserfile:$docudom:$docuname:".
2685: &escape("$old").':'.&escape("$new"),$home);
2686: if ($result eq 'ok') {
2687: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2688: my $oldmeta = $old.'.meta';
2689: my $newmeta = $new.'.meta';
2690: my $metaresult =
2691: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2692: my $url = "/uploaded/$docudom/$docuname/$old";
2693: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2694: my $sqlresult =
1.823 albertel 2695: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2696: 'portfolio_metadata',$group,
2697: 'delete');
1.798 raeburn 2698: }
2699: }
2700: return $result;
1.531 albertel 2701: }
2702:
1.14 www 2703: # ------------------------------------------------------------------------- Log
2704:
2705: sub log {
2706: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2707: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2708: }
2709:
2710: # ------------------------------------------------------------------ Course Log
1.352 www 2711: #
2712: # This routine flushes several buffers of non-mission-critical nature
2713: #
1.157 www 2714:
2715: sub flushcourselogs {
1.352 www 2716: &logthis('Flushing log buffers');
2717: #
2718: # course logs
2719: # This is a log of all transactions in a course, which can be used
2720: # for data mining purposes
2721: #
2722: # It also collects the courseid database, which lists last transaction
2723: # times and course titles for all courseids
2724: #
2725: my %courseidbuffer=();
1.921 raeburn 2726: foreach my $crsid (keys(%courselogs)) {
1.352 www 2727: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2728: &escape($courselogs{$crsid}),
2729: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2730: delete $courselogs{$crsid};
2731: } else {
2732: &logthis('Failed to flush log buffer for '.$crsid);
2733: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2734: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2735: " exceeded maximum size, deleting.</font>");
2736: delete $courselogs{$crsid};
2737: }
1.352 www 2738: }
1.920 raeburn 2739: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2740: 'description' => $coursedescrbuf{$crsid},
2741: 'inst_code' => $courseinstcodebuf{$crsid},
2742: 'type' => $coursetypebuf{$crsid},
2743: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2744: };
1.191 harris41 2745: }
1.352 www 2746: #
2747: # Write course id database (reverse lookup) to homeserver of courses
2748: # Is used in pickcourse
2749: #
1.840 albertel 2750: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2751: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2752: $courseidbuffer{$crs_home},
2753: $crs_home,'timeonly');
1.352 www 2754: }
2755: #
2756: # File accesses
2757: # Writes to the dynamic metadata of resources to get hit counts, etc.
2758: #
1.449 matthew 2759: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2760: if ($entry =~ /___count$/) {
2761: my ($dom,$name);
1.807 albertel 2762: ($dom,$name,undef)=
1.811 albertel 2763: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2764: if (! defined($dom) || $dom eq '' ||
2765: ! defined($name) || $name eq '') {
1.620 albertel 2766: my $cid = $env{'request.course.id'};
2767: $dom = $env{'request.'.$cid.'.domain'};
2768: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2769: }
1.450 matthew 2770: my $value = $accesshash{$entry};
2771: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2772: my %temphash=($url => $value);
1.449 matthew 2773: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2774: if ($result eq 'ok') {
2775: delete $accesshash{$entry};
2776: } elsif ($result eq 'unknown_cmd') {
2777: # Target server has old code running on it.
1.450 matthew 2778: my %temphash=($entry => $value);
1.449 matthew 2779: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2780: delete $accesshash{$entry};
2781: }
2782: }
2783: } else {
1.811 albertel 2784: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2785: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2786: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2787: delete $accesshash{$entry};
2788: }
1.185 www 2789: }
1.191 harris41 2790: }
1.352 www 2791: #
2792: # Roles
2793: # Reverse lookup of user roles for course faculty/staff and co-authorship
2794: #
1.800 albertel 2795: foreach my $entry (keys(%userrolehash)) {
1.351 www 2796: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2797: split(/\:/,$entry);
2798: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2799: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2800: $rudom,$runame) eq 'ok') {
2801: delete $userrolehash{$entry};
2802: }
2803: }
1.662 raeburn 2804: #
2805: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2806: #
2807: my %domrolebuffer = ();
1.1000 raeburn 2808: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2809: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2810: if ($domrolebuffer{$rudom}) {
2811: $domrolebuffer{$rudom}.='&'.&escape($entry).
2812: '='.&escape($domainrolehash{$entry});
2813: } else {
2814: $domrolebuffer{$rudom}.=&escape($entry).
2815: '='.&escape($domainrolehash{$entry});
2816: }
2817: delete $domainrolehash{$entry};
2818: }
2819: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2820: my %servers = &get_servers($dom,'library');
2821: foreach my $tryserver (keys(%servers)) {
2822: unless (&reply('domroleput:'.$dom.':'.
2823: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2824: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2825: }
1.662 raeburn 2826: }
2827: }
1.186 www 2828: $dumpcount++;
1.157 www 2829: }
2830:
2831: sub courselog {
2832: my $what=shift;
1.158 www 2833: $what=time.':'.$what;
1.620 albertel 2834: unless ($env{'request.course.id'}) { return ''; }
2835: $coursedombuf{$env{'request.course.id'}}=
2836: $env{'course.'.$env{'request.course.id'}.'.domain'};
2837: $coursenumbuf{$env{'request.course.id'}}=
2838: $env{'course.'.$env{'request.course.id'}.'.num'};
2839: $coursehombuf{$env{'request.course.id'}}=
2840: $env{'course.'.$env{'request.course.id'}.'.home'};
2841: $coursedescrbuf{$env{'request.course.id'}}=
2842: $env{'course.'.$env{'request.course.id'}.'.description'};
2843: $courseinstcodebuf{$env{'request.course.id'}}=
2844: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2845: $courseownerbuf{$env{'request.course.id'}}=
2846: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2847: $coursetypebuf{$env{'request.course.id'}}=
2848: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2849: if (defined $courselogs{$env{'request.course.id'}}) {
2850: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2851: } else {
1.620 albertel 2852: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2853: }
1.620 albertel 2854: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2855: &flushcourselogs();
2856: }
1.158 www 2857: }
2858:
2859: sub courseacclog {
2860: my $fnsymb=shift;
1.620 albertel 2861: unless ($env{'request.course.id'}) { return ''; }
2862: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2863: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2864: $what.=':POST';
1.583 matthew 2865: # FIXME: Probably ought to escape things....
1.800 albertel 2866: foreach my $key (keys(%env)) {
2867: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2868: my $formitem = $1;
2869: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2870: $what.=':'.$formitem.'='.$env{$key};
2871: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2872: $what.=':'.$formitem.'='.$env{$key};
2873: }
1.158 www 2874: }
1.191 harris41 2875: }
1.583 matthew 2876: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2877: # FIXME: We should not be depending on a form parameter that someone
2878: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2879: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2880: $what.= ':POST';
2881: # FIXME: Probably ought to escape things....
2882: foreach my $element ('courseexp','crsfulltext','crsrelated',
2883: 'crsdiscuss') {
1.620 albertel 2884: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2885: }
2886: }
1.158 www 2887: }
2888: &courselog($what);
1.149 www 2889: }
2890:
1.185 www 2891: sub countacc {
2892: my $url=&declutter(shift);
1.458 matthew 2893: return if (! defined($url) || $url eq '');
1.620 albertel 2894: unless ($env{'request.course.id'}) { return ''; }
2895: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2896: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2897: $accesshash{$key}++;
1.185 www 2898: }
1.349 www 2899:
1.361 www 2900: sub linklog {
2901: my ($from,$to)=@_;
2902: $from=&declutter($from);
2903: $to=&declutter($to);
2904: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2905: $accesshash{$to.'___'.$from.'___goto'}=1;
2906: }
2907:
1.349 www 2908: sub userrolelog {
2909: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2910: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2911: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2912: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 2913: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 2914: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2915: $userrolehash
2916: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2917: =$tend.':'.$tstart;
1.662 raeburn 2918: }
1.898 albertel 2919: if (($env{'request.role'} =~ /dc\./) &&
2920: (($trole=~/^au/) || ($trole=~/^in/) ||
2921: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 2922: ($trole=~/^cr/) || ($trole=~/^ta/) ||
2923: ($trole=~/^co/))) {
1.898 albertel 2924: $userrolehash
2925: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2926: =$tend.':'.$tstart;
2927: }
1.662 raeburn 2928: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2929: ($trole=~/^li/) || ($trole=~/^li/) ||
2930: ($trole=~/^au/) || ($trole=~/^dg/) ||
2931: ($trole=~/^sc/)) {
2932: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2933: $domainrolehash
2934: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2935: = $tend.':'.$tstart;
2936: }
1.351 www 2937: }
2938:
1.957 raeburn 2939: sub courserolelog {
2940: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2941: if (($trole eq 'cc') || ($trole eq 'in') ||
2942: ($trole eq 'ep') || ($trole eq 'ad') ||
2943: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 2944: ($trole=~/^cr/) || ($trole eq 'gr') ||
2945: ($trole eq 'co')) {
1.957 raeburn 2946: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2947: my $cdom = $1;
2948: my $cnum = $2;
2949: my $sec = $3;
2950: my $namespace = 'rolelog';
2951: my %storehash = (
2952: role => $trole,
2953: start => $tstart,
2954: end => $tend,
2955: selfenroll => $selfenroll,
2956: context => $context,
2957: );
2958: if ($trole eq 'gr') {
2959: $namespace = 'groupslog';
2960: $storehash{'group'} = $sec;
2961: } else {
2962: $storehash{'section'} = $sec;
2963: }
2964: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 2965: if (($trole ne 'st') || ($sec ne '')) {
2966: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2967: }
1.957 raeburn 2968: }
2969: }
2970: return;
2971: }
2972:
1.351 www 2973: sub get_course_adv_roles {
1.948 raeburn 2974: my ($cid,$codes) = @_;
1.620 albertel 2975: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2976: my %coursehash=&coursedescription($cid);
1.988 raeburn 2977: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 2978: my %nothide=();
1.800 albertel 2979: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2980: if ($user !~ /:/) {
2981: $nothide{join(':',split(/[\@]/,$user))}=1;
2982: } else {
2983: $nothide{$user}=1;
2984: }
1.470 www 2985: }
1.351 www 2986: my %returnhash=();
2987: my %dumphash=
2988: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2989: my $now=time;
1.997 raeburn 2990: my %privileged;
1.1000 raeburn 2991: foreach my $entry (keys(%dumphash)) {
1.800 albertel 2992: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2993: if (($tstart) && ($tstart<0)) { next; }
2994: if (($tend) && ($tend<$now)) { next; }
2995: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2996: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2997: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 2998: unless (ref($privileged{$domain}) eq 'HASH') {
2999: my %dompersonnel =
1.998 raeburn 3000: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3001: $privileged{$domain} = {};
3002: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3003: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3004: foreach my $user (keys(%{$dompersonnel{$server}})) {
3005: my ($trole,$uname,$udom) = split(/:/,$user);
3006: $privileged{$udom}{$uname} = 1;
3007: }
3008: }
3009: }
3010: }
3011: if ((exists($privileged{$domain}{$username})) &&
3012: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3013: if ($role eq 'cr') { next; }
1.948 raeburn 3014: if ($codes) {
3015: if ($section) { $role .= ':'.$section; }
3016: if ($returnhash{$role}) {
3017: $returnhash{$role}.=','.$username.':'.$domain;
3018: } else {
3019: $returnhash{$role}=$username.':'.$domain;
3020: }
1.351 www 3021: } else {
1.988 raeburn 3022: my $key=&plaintext($role,$crstype);
1.973 bisitz 3023: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3024: if ($returnhash{$key}) {
3025: $returnhash{$key}.=','.$username.':'.$domain;
3026: } else {
3027: $returnhash{$key}=$username.':'.$domain;
3028: }
1.351 www 3029: }
1.948 raeburn 3030: }
1.400 www 3031: return %returnhash;
3032: }
3033:
3034: sub get_my_roles {
1.937 raeburn 3035: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3036: unless (defined($uname)) { $uname=$env{'user.name'}; }
3037: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3038: my (%dumphash,%nothide);
1.1086 ! raeburn 3039: if ($context eq 'userroles') {
! 3040: my $extra = &freeze_escape({'skipcheck' => 1});
! 3041: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3042: } else {
3043: %dumphash=
1.400 www 3044: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3045: if ($hidepriv) {
3046: my %coursehash=&coursedescription($udom.'_'.$uname);
3047: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3048: if ($user !~ /:/) {
3049: $nothide{join(':',split(/[\@]/,$user))} = 1;
3050: } else {
3051: $nothide{$user} = 1;
3052: }
3053: }
3054: }
1.858 raeburn 3055: }
1.400 www 3056: my %returnhash=();
3057: my $now=time;
1.999 raeburn 3058: my %privileged;
1.800 albertel 3059: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3060: my ($role,$tend,$tstart);
3061: if ($context eq 'userroles') {
3062: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3063: } else {
3064: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3065: }
1.400 www 3066: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3067: my $status = 'active';
1.939 raeburn 3068: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3069: $status = 'previous';
3070: }
3071: if (($tstart) && ($now<$tstart)) {
3072: $status = 'future';
3073: }
3074: if (ref($types) eq 'ARRAY') {
3075: if (!grep(/^\Q$status\E$/,@{$types})) {
3076: next;
3077: }
3078: } else {
3079: if ($status ne 'active') {
3080: next;
3081: }
3082: }
1.867 raeburn 3083: my ($rolecode,$username,$domain,$section,$area);
3084: if ($context eq 'userroles') {
3085: ($area,$rolecode) = split(/_/,$entry);
3086: (undef,$domain,$username,$section) = split(/\//,$area);
3087: } else {
3088: ($role,$username,$domain,$section) = split(/\:/,$entry);
3089: }
1.832 raeburn 3090: if (ref($roledoms) eq 'ARRAY') {
3091: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3092: next;
3093: }
3094: }
3095: if (ref($roles) eq 'ARRAY') {
3096: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3097: if ($role =~ /^cr\//) {
3098: if (!grep(/^cr$/,@{$roles})) {
3099: next;
3100: }
3101: } else {
3102: next;
3103: }
1.832 raeburn 3104: }
1.867 raeburn 3105: }
1.937 raeburn 3106: if ($hidepriv) {
1.999 raeburn 3107: if ($context eq 'userroles') {
3108: if ((&privileged($username,$domain)) &&
3109: (!$nothide{$username.':'.$domain})) {
3110: next;
3111: }
3112: } else {
3113: unless (ref($privileged{$domain}) eq 'HASH') {
3114: my %dompersonnel =
3115: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3116: $privileged{$domain} = {};
3117: if (keys(%dompersonnel)) {
3118: foreach my $server (keys(%dompersonnel)) {
3119: if (ref($dompersonnel{$server}) eq 'HASH') {
3120: foreach my $user (keys(%{$dompersonnel{$server}})) {
3121: my ($trole,$uname,$udom) = split(/:/,$user);
3122: $privileged{$udom}{$uname} = $trole;
3123: }
3124: }
3125: }
3126: }
3127: }
3128: if (exists($privileged{$domain}{$username})) {
3129: if (!$nothide{$username.':'.$domain}) {
3130: next;
3131: }
3132: }
1.937 raeburn 3133: }
3134: }
1.933 raeburn 3135: if ($withsec) {
3136: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3137: $tstart.':'.$tend;
3138: } else {
3139: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3140: }
1.832 raeburn 3141: }
1.373 www 3142: return %returnhash;
1.399 www 3143: }
3144:
3145: # ----------------------------------------------------- Frontpage Announcements
3146: #
3147: #
3148:
3149: sub postannounce {
3150: my ($server,$text)=@_;
1.844 albertel 3151: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3152: unless ($text=~/\w/) { $text=''; }
3153: return &reply('setannounce:'.&escape($text),$server);
3154: }
3155:
3156: sub getannounce {
1.448 albertel 3157:
3158: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3159: my $announcement='';
1.800 albertel 3160: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3161: close($fh);
1.399 www 3162: if ($announcement=~/\w/) {
3163: return
3164: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3165: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3166: } else {
3167: return '';
3168: }
3169: } else {
3170: return '';
3171: }
1.351 www 3172: }
1.353 www 3173:
3174: # ---------------------------------------------------------- Course ID routines
3175: # Deal with domain's nohist_courseid.db files
3176: #
3177:
3178: sub courseidput {
1.921 raeburn 3179: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3180: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3181: my $outcome;
3182: if ($caller eq 'timeonly') {
3183: my $cids = '';
3184: foreach my $item (keys(%$storehash)) {
3185: $cids.=&escape($item).'&';
3186: }
3187: $cids=~s/\&$//;
3188: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3189: $coursehome);
3190: } else {
3191: my $items = '';
3192: foreach my $item (keys(%$storehash)) {
3193: $items.= &escape($item).'='.
3194: &freeze_escape($$storehash{$item}).'&';
3195: }
3196: $items=~s/\&$//;
3197: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3198: $coursehome);
1.918 raeburn 3199: }
3200: if ($outcome eq 'unknown_cmd') {
3201: my $what;
3202: foreach my $cid (keys(%$storehash)) {
3203: $what .= &escape($cid).'=';
1.921 raeburn 3204: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3205: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3206: }
3207: $what =~ s/\:$/&/;
3208: }
3209: $what =~ s/\&$//;
3210: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3211: } else {
3212: return $outcome;
3213: }
1.353 www 3214: }
3215:
3216: sub courseiddump {
1.921 raeburn 3217: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3218: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3219: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3220: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3221: my $as_hash = 1;
3222: my %returnhash;
3223: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3224: my %libserv = &all_library();
3225: foreach my $tryserver (keys(%libserv)) {
3226: if ( ( $hostidflag == 1
3227: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3228: || (!defined($hostidflag)) ) {
3229:
1.918 raeburn 3230: if (($domfilter eq '') ||
3231: (&host_domain($tryserver) eq $domfilter)) {
3232: my $rep =
3233: &reply('courseiddump:'.&host_domain($tryserver).':'.
3234: $sincefilter.':'.&escape($descfilter).':'.
3235: &escape($instcodefilter).':'.&escape($ownerfilter).
3236: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3237: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3238: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3239: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3240: &escape($cc_clone).':'.$cloneonly.':'.
3241: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3242: &escape($creationcontext).':'.$domcloner,
3243: $tryserver);
1.918 raeburn 3244: my @pairs=split(/\&/,$rep);
3245: foreach my $item (@pairs) {
3246: my ($key,$value)=split(/\=/,$item,2);
3247: $key = &unescape($key);
3248: next if ($key =~ /^error: 2 /);
3249: my $result = &thaw_unescape($value);
3250: if (ref($result) eq 'HASH') {
3251: $returnhash{$key}=$result;
3252: } else {
1.921 raeburn 3253: my @responses = split(/:/,$value);
3254: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3255: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3256: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3257: }
1.1008 raeburn 3258: }
1.353 www 3259: }
3260: }
3261: }
3262: }
3263: return %returnhash;
3264: }
3265:
1.1055 raeburn 3266: sub courselastaccess {
3267: my ($cdom,$cnum,$hostidref) = @_;
3268: my %returnhash;
3269: if ($cdom && $cnum) {
3270: my $chome = &homeserver($cnum,$cdom);
3271: if ($chome ne 'no_host') {
3272: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3273: &extract_lastaccess(\%returnhash,$rep);
3274: }
3275: } else {
3276: if (!$cdom) { $cdom=''; }
3277: my %libserv = &all_library();
3278: foreach my $tryserver (keys(%libserv)) {
3279: if (ref($hostidref) eq 'ARRAY') {
3280: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3281: }
3282: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3283: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3284: &extract_lastaccess(\%returnhash,$rep);
3285: }
3286: }
3287: }
3288: return %returnhash;
3289: }
3290:
3291: sub extract_lastaccess {
3292: my ($returnhash,$rep) = @_;
3293: if (ref($returnhash) eq 'HASH') {
3294: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3295: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3296: $rep eq '') {
3297: my @pairs=split(/\&/,$rep);
3298: foreach my $item (@pairs) {
3299: my ($key,$value)=split(/\=/,$item,2);
3300: $key = &unescape($key);
3301: next if ($key =~ /^error: 2 /);
3302: $returnhash->{$key} = &thaw_unescape($value);
3303: }
3304: }
3305: }
3306: return;
3307: }
3308:
1.658 raeburn 3309: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3310:
3311: sub dcmailput {
1.685 raeburn 3312: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3313: my $status = &Apache::lonnet::critical(
1.740 www 3314: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3315: &escape($message),$server);
1.662 raeburn 3316: return $status;
3317: }
3318:
1.658 raeburn 3319: sub dcmaildump {
3320: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3321: my %returnhash=();
1.846 albertel 3322:
3323: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3324: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3325: &escape($enddate).':';
3326: my @esc_senders=map { &escape($_)} @$senders;
3327: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3328: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3329: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3330: if (($key) && ($value)) {
3331: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3332: }
3333: }
3334: }
3335: return %returnhash;
3336: }
1.662 raeburn 3337: # ---------------------------------------------------------- Domain roles
3338:
3339: sub get_domain_roles {
3340: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3341: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3342: $startdate = '.';
3343: }
1.1018 raeburn 3344: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3345: $enddate = '.';
3346: }
1.922 raeburn 3347: my $rolelist;
3348: if (ref($roles) eq 'ARRAY') {
3349: $rolelist = join(':',@{$roles});
3350: }
1.662 raeburn 3351: my %personnel = ();
1.841 albertel 3352:
3353: my %servers = &get_servers($dom,'library');
3354: foreach my $tryserver (keys(%servers)) {
3355: %{$personnel{$tryserver}}=();
3356: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3357: &escape($startdate).':'.
3358: &escape($enddate).':'.
3359: &escape($rolelist), $tryserver))) {
3360: my ($key,$value) = split(/\=/,$line,2);
3361: if (($key) && ($value)) {
3362: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3363: }
3364: }
1.662 raeburn 3365: }
3366: return %personnel;
3367: }
1.658 raeburn 3368:
1.1057 www 3369: # ----------------------------------------------------------- Interval timing
1.149 www 3370:
1.504 albertel 3371: sub get_first_access {
3372: my ($type,$argsymb)=@_;
1.790 albertel 3373: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3374: if ($argsymb) { $symb=$argsymb; }
3375: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3376: if ($type eq 'course') {
3377: $res='course';
3378: } elsif ($type eq 'map') {
1.588 albertel 3379: $res=&symbread($map);
3380: } else {
3381: $res=$symb;
3382: }
3383: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3384: return $times{"$courseid\0$res"};
1.504 albertel 3385: }
3386:
3387: sub set_first_access {
3388: my ($type)=@_;
1.790 albertel 3389: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3390: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3391: if ($type eq 'course') {
3392: $res='course';
3393: } elsif ($type eq 'map') {
1.588 albertel 3394: $res=&symbread($map);
3395: } else {
3396: $res=$symb;
3397: }
3398: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3399: if (!$firstaccess) {
1.588 albertel 3400: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3401: }
3402: return 'already_set';
1.504 albertel 3403: }
3404:
1.110 www 3405: # --------------------------------------------- Set Expire Date for Spreadsheet
3406:
3407: sub expirespread {
3408: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3409: my $cid=$env{'request.course.id'};
1.110 www 3410: if ($cid) {
3411: my $now=time;
3412: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3413: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3414: $env{'course.'.$cid.'.num'}.
1.110 www 3415: ':nohist_expirationdates:'.
3416: &escape($key).'='.$now,
1.620 albertel 3417: $env{'course.'.$cid.'.home'})
1.110 www 3418: }
3419: return 'ok';
1.14 www 3420: }
3421:
1.109 www 3422: # ----------------------------------------------------- Devalidate Spreadsheets
3423:
3424: sub devalidate {
1.325 www 3425: my ($symb,$uname,$udom)=@_;
1.620 albertel 3426: my $cid=$env{'request.course.id'};
1.109 www 3427: if ($cid) {
1.391 matthew 3428: # delete the stored spreadsheets for
3429: # - the student level sheet of this user in course's homespace
3430: # - the assessment level sheet for this resource
3431: # for this user in user's homespace
1.553 albertel 3432: # - current conditional state info
1.325 www 3433: my $key=$uname.':'.$udom.':';
1.109 www 3434: my $status=
1.299 matthew 3435: &del('nohist_calculatedsheets',
1.391 matthew 3436: [$key.'studentcalc:'],
1.620 albertel 3437: $env{'course.'.$cid.'.domain'},
3438: $env{'course.'.$cid.'.num'})
1.133 albertel 3439: .' '.
3440: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3441: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3442: unless ($status eq 'ok ok') {
3443: &logthis('Could not devalidate spreadsheet '.
1.325 www 3444: $uname.' at '.$udom.' for '.
1.109 www 3445: $symb.': '.$status);
1.133 albertel 3446: }
1.553 albertel 3447: &delenv('user.state.'.$cid);
1.109 www 3448: }
3449: }
3450:
1.265 albertel 3451: sub get_scalar {
3452: my ($string,$end) = @_;
3453: my $value;
3454: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3455: $value = $1;
3456: } elsif ($$string =~ s/^([^&]*?)&//) {
3457: $value = $1;
3458: }
3459: return &unescape($value);
3460: }
3461:
3462: sub array2str {
3463: my (@array) = @_;
3464: my $result=&arrayref2str(\@array);
3465: $result=~s/^__ARRAY_REF__//;
3466: $result=~s/__END_ARRAY_REF__$//;
3467: return $result;
3468: }
3469:
1.204 albertel 3470: sub arrayref2str {
3471: my ($arrayref) = @_;
1.265 albertel 3472: my $result='__ARRAY_REF__';
1.204 albertel 3473: foreach my $elem (@$arrayref) {
1.265 albertel 3474: if(ref($elem) eq 'ARRAY') {
3475: $result.=&arrayref2str($elem).'&';
3476: } elsif(ref($elem) eq 'HASH') {
3477: $result.=&hashref2str($elem).'&';
3478: } elsif(ref($elem)) {
3479: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3480: } else {
3481: $result.=&escape($elem).'&';
3482: }
3483: }
3484: $result=~s/\&$//;
1.265 albertel 3485: $result .= '__END_ARRAY_REF__';
1.204 albertel 3486: return $result;
3487: }
3488:
1.168 albertel 3489: sub hash2str {
1.204 albertel 3490: my (%hash) = @_;
3491: my $result=&hashref2str(\%hash);
1.265 albertel 3492: $result=~s/^__HASH_REF__//;
3493: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3494: return $result;
3495: }
3496:
3497: sub hashref2str {
3498: my ($hashref)=@_;
1.265 albertel 3499: my $result='__HASH_REF__';
1.800 albertel 3500: foreach my $key (sort(keys(%$hashref))) {
3501: if (ref($key) eq 'ARRAY') {
3502: $result.=&arrayref2str($key).'=';
3503: } elsif (ref($key) eq 'HASH') {
3504: $result.=&hashref2str($key).'=';
3505: } elsif (ref($key)) {
1.265 albertel 3506: $result.='=';
1.800 albertel 3507: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3508: } else {
1.800 albertel 3509: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3510: }
3511:
1.800 albertel 3512: if(ref($hashref->{$key}) eq 'ARRAY') {
3513: $result.=&arrayref2str($hashref->{$key}).'&';
3514: } elsif(ref($hashref->{$key}) eq 'HASH') {
3515: $result.=&hashref2str($hashref->{$key}).'&';
3516: } elsif(ref($hashref->{$key})) {
1.265 albertel 3517: $result.='&';
1.800 albertel 3518: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3519: } else {
1.800 albertel 3520: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3521: }
3522: }
1.168 albertel 3523: $result=~s/\&$//;
1.265 albertel 3524: $result .= '__END_HASH_REF__';
1.168 albertel 3525: return $result;
3526: }
3527:
3528: sub str2hash {
1.265 albertel 3529: my ($string)=@_;
3530: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3531: return %$hash;
3532: }
3533:
3534: sub str2hashref {
1.168 albertel 3535: my ($string) = @_;
1.265 albertel 3536:
3537: my %hash;
3538:
3539: if($string !~ /^__HASH_REF__/) {
3540: if (! ($string eq '' || !defined($string))) {
3541: $hash{'error'}='Not hash reference';
3542: }
3543: return (\%hash, $string);
3544: }
3545:
3546: $string =~ s/^__HASH_REF__//;
3547:
3548: while($string !~ /^__END_HASH_REF__/) {
3549: #key
3550: my $key='';
3551: if($string =~ /^__HASH_REF__/) {
3552: ($key, $string)=&str2hashref($string);
3553: if(defined($key->{'error'})) {
3554: $hash{'error'}='Bad data';
3555: return (\%hash, $string);
3556: }
3557: } elsif($string =~ /^__ARRAY_REF__/) {
3558: ($key, $string)=&str2arrayref($string);
3559: if($key->[0] eq 'Array reference error') {
3560: $hash{'error'}='Bad data';
3561: return (\%hash, $string);
3562: }
3563: } else {
3564: $string =~ s/^(.*?)=//;
1.267 albertel 3565: $key=&unescape($1);
1.265 albertel 3566: }
3567: $string =~ s/^=//;
3568:
3569: #value
3570: my $value='';
3571: if($string =~ /^__HASH_REF__/) {
3572: ($value, $string)=&str2hashref($string);
3573: if(defined($value->{'error'})) {
3574: $hash{'error'}='Bad data';
3575: return (\%hash, $string);
3576: }
3577: } elsif($string =~ /^__ARRAY_REF__/) {
3578: ($value, $string)=&str2arrayref($string);
3579: if($value->[0] eq 'Array reference error') {
3580: $hash{'error'}='Bad data';
3581: return (\%hash, $string);
3582: }
3583: } else {
3584: $value=&get_scalar(\$string,'__END_HASH_REF__');
3585: }
3586: $string =~ s/^&//;
3587:
3588: $hash{$key}=$value;
1.204 albertel 3589: }
1.265 albertel 3590:
3591: $string =~ s/^__END_HASH_REF__//;
3592:
3593: return (\%hash, $string);
1.204 albertel 3594: }
3595:
3596: sub str2array {
1.265 albertel 3597: my ($string)=@_;
3598: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3599: return @$array;
3600: }
3601:
3602: sub str2arrayref {
1.204 albertel 3603: my ($string) = @_;
1.265 albertel 3604: my @array;
3605:
3606: if($string !~ /^__ARRAY_REF__/) {
3607: if (! ($string eq '' || !defined($string))) {
3608: $array[0]='Array reference error';
3609: }
3610: return (\@array, $string);
3611: }
3612:
3613: $string =~ s/^__ARRAY_REF__//;
3614:
3615: while($string !~ /^__END_ARRAY_REF__/) {
3616: my $value='';
3617: if($string =~ /^__HASH_REF__/) {
3618: ($value, $string)=&str2hashref($string);
3619: if(defined($value->{'error'})) {
3620: $array[0] ='Array reference error';
3621: return (\@array, $string);
3622: }
3623: } elsif($string =~ /^__ARRAY_REF__/) {
3624: ($value, $string)=&str2arrayref($string);
3625: if($value->[0] eq 'Array reference error') {
3626: $array[0] ='Array reference error';
3627: return (\@array, $string);
3628: }
3629: } else {
3630: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3631: }
3632: $string =~ s/^&//;
3633:
3634: push(@array, $value);
1.191 harris41 3635: }
1.265 albertel 3636:
3637: $string =~ s/^__END_ARRAY_REF__//;
3638:
3639: return (\@array, $string);
1.168 albertel 3640: }
3641:
1.167 albertel 3642: # -------------------------------------------------------------------Temp Store
3643:
1.168 albertel 3644: sub tmpreset {
3645: my ($symb,$namespace,$domain,$stuname) = @_;
3646: if (!$symb) {
3647: $symb=&symbread();
1.620 albertel 3648: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3649: }
3650: $symb=escape($symb);
3651:
1.620 albertel 3652: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3653: $namespace=~s/\//\_/g;
3654: $namespace=~s/\W//g;
3655:
1.620 albertel 3656: if (!$domain) { $domain=$env{'user.domain'}; }
3657: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3658: if ($domain eq 'public' && $stuname eq 'public') {
3659: $stuname=$ENV{'REMOTE_ADDR'};
3660: }
1.168 albertel 3661: my $path=$perlvar{'lonDaemons'}.'/tmp';
3662: my %hash;
3663: if (tie(%hash,'GDBM_File',
3664: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3665: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3666: foreach my $key (keys(%hash)) {
1.180 albertel 3667: if ($key=~ /:$symb/) {
1.168 albertel 3668: delete($hash{$key});
3669: }
3670: }
3671: }
3672: }
3673:
1.167 albertel 3674: sub tmpstore {
1.168 albertel 3675: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3676:
3677: if (!$symb) {
3678: $symb=&symbread();
1.620 albertel 3679: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3680: }
3681: $symb=escape($symb);
3682:
3683: if (!$namespace) {
3684: # I don't think we would ever want to store this for a course.
3685: # it seems this will only be used if we don't have a course.
1.620 albertel 3686: #$namespace=$env{'request.course.id'};
1.168 albertel 3687: #if (!$namespace) {
1.620 albertel 3688: $namespace=$env{'request.state'};
1.168 albertel 3689: #}
3690: }
3691: $namespace=~s/\//\_/g;
3692: $namespace=~s/\W//g;
1.620 albertel 3693: if (!$domain) { $domain=$env{'user.domain'}; }
3694: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3695: if ($domain eq 'public' && $stuname eq 'public') {
3696: $stuname=$ENV{'REMOTE_ADDR'};
3697: }
1.168 albertel 3698: my $now=time;
3699: my %hash;
3700: my $path=$perlvar{'lonDaemons'}.'/tmp';
3701: if (tie(%hash,'GDBM_File',
3702: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3703: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3704: $hash{"version:$symb"}++;
3705: my $version=$hash{"version:$symb"};
3706: my $allkeys='';
3707: foreach my $key (keys(%$storehash)) {
3708: $allkeys.=$key.':';
1.591 albertel 3709: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3710: }
3711: $hash{"$version:$symb:timestamp"}=$now;
3712: $allkeys.='timestamp';
3713: $hash{"$version:keys:$symb"}=$allkeys;
3714: if (untie(%hash)) {
3715: return 'ok';
3716: } else {
3717: return "error:$!";
3718: }
3719: } else {
3720: return "error:$!";
3721: }
3722: }
1.167 albertel 3723:
1.168 albertel 3724: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3725:
1.168 albertel 3726: sub tmprestore {
3727: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3728:
1.168 albertel 3729: if (!$symb) {
3730: $symb=&symbread();
1.620 albertel 3731: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3732: }
3733: $symb=escape($symb);
3734:
1.620 albertel 3735: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3736:
1.620 albertel 3737: if (!$domain) { $domain=$env{'user.domain'}; }
3738: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3739: if ($domain eq 'public' && $stuname eq 'public') {
3740: $stuname=$ENV{'REMOTE_ADDR'};
3741: }
1.168 albertel 3742: my %returnhash;
3743: $namespace=~s/\//\_/g;
3744: $namespace=~s/\W//g;
3745: my %hash;
3746: my $path=$perlvar{'lonDaemons'}.'/tmp';
3747: if (tie(%hash,'GDBM_File',
3748: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3749: &GDBM_READER(),0640)) {
1.168 albertel 3750: my $version=$hash{"version:$symb"};
3751: $returnhash{'version'}=$version;
3752: my $scope;
3753: for ($scope=1;$scope<=$version;$scope++) {
3754: my $vkeys=$hash{"$scope:keys:$symb"};
3755: my @keys=split(/:/,$vkeys);
3756: my $key;
3757: $returnhash{"$scope:keys"}=$vkeys;
3758: foreach $key (@keys) {
1.591 albertel 3759: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3760: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3761: }
3762: }
1.168 albertel 3763: if (!(untie(%hash))) {
3764: return "error:$!";
3765: }
3766: } else {
3767: return "error:$!";
3768: }
3769: return %returnhash;
1.167 albertel 3770: }
3771:
1.9 www 3772: # ----------------------------------------------------------------------- Store
3773:
3774: sub store {
1.124 www 3775: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3776: my $home='';
3777:
1.168 albertel 3778: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3779:
1.213 www 3780: $symb=&symbclean($symb);
1.122 albertel 3781: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3782:
1.620 albertel 3783: if (!$domain) { $domain=$env{'user.domain'}; }
3784: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3785:
3786: &devalidate($symb,$stuname,$domain);
1.109 www 3787:
3788: $symb=escape($symb);
1.187 www 3789: if (!$namespace) {
1.620 albertel 3790: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3791: return '';
3792: }
3793: }
1.620 albertel 3794: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3795:
3796: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3797: $$storehash{'host'}=$perlvar{'lonHostID'};
3798:
1.12 www 3799: my $namevalue='';
1.800 albertel 3800: foreach my $key (keys(%$storehash)) {
3801: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3802: }
1.12 www 3803: $namevalue=~s/\&$//;
1.187 www 3804: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3805: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3806: }
3807:
1.47 www 3808: # -------------------------------------------------------------- Critical Store
3809:
3810: sub cstore {
1.124 www 3811: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3812: my $home='';
3813:
1.168 albertel 3814: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3815:
1.213 www 3816: $symb=&symbclean($symb);
1.122 albertel 3817: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3818:
1.620 albertel 3819: if (!$domain) { $domain=$env{'user.domain'}; }
3820: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3821:
3822: &devalidate($symb,$stuname,$domain);
1.109 www 3823:
3824: $symb=escape($symb);
1.187 www 3825: if (!$namespace) {
1.620 albertel 3826: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3827: return '';
3828: }
3829: }
1.620 albertel 3830: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3831:
3832: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3833: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3834:
1.47 www 3835: my $namevalue='';
1.800 albertel 3836: foreach my $key (keys(%$storehash)) {
3837: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3838: }
1.47 www 3839: $namevalue=~s/\&$//;
1.187 www 3840: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3841: return critical
3842: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3843: }
3844:
1.9 www 3845: # --------------------------------------------------------------------- Restore
3846:
3847: sub restore {
1.124 www 3848: my ($symb,$namespace,$domain,$stuname) = @_;
3849: my $home='';
3850:
1.168 albertel 3851: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3852:
1.122 albertel 3853: if (!$symb) {
3854: unless ($symb=escape(&symbread())) { return ''; }
3855: } else {
1.213 www 3856: $symb=&escape(&symbclean($symb));
1.122 albertel 3857: }
1.188 www 3858: if (!$namespace) {
1.620 albertel 3859: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3860: return '';
3861: }
3862: }
1.620 albertel 3863: if (!$domain) { $domain=$env{'user.domain'}; }
3864: if (!$stuname) { $stuname=$env{'user.name'}; }
3865: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3866: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3867:
1.12 www 3868: my %returnhash=();
1.800 albertel 3869: foreach my $line (split(/\&/,$answer)) {
3870: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3871: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3872: }
1.75 www 3873: my $version;
3874: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3875: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3876: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3877: }
1.75 www 3878: }
1.13 www 3879: return %returnhash;
1.34 www 3880: }
3881:
3882: # ---------------------------------------------------------- Course Description
3883:
3884: sub coursedescription {
1.731 albertel 3885: my ($courseid,$args)=@_;
1.34 www 3886: $courseid=~s/^\///;
1.49 www 3887: $courseid=~s/\_/\//g;
1.34 www 3888: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3889: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3890: my $normalid=$cdomain.'_'.$cnum;
3891: # need to always cache even if we get errors otherwise we keep
3892: # trying and trying and trying to get the course description.
3893: my %envhash=();
3894: my %returnhash=();
1.731 albertel 3895:
3896: my $expiretime=600;
3897: if ($env{'request.course.id'} eq $normalid) {
3898: $expiretime=120;
3899: }
3900:
3901: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3902: if (!$args->{'freshen_cache'}
3903: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3904: foreach my $key (keys(%env)) {
3905: next if ($key !~ /^\Q$prefix\E(.*)/);
3906: my ($setting) = $1;
3907: $returnhash{$setting} = $env{$key};
3908: }
3909: return %returnhash;
3910: }
3911:
3912: # get the data agin
3913: if (!$args->{'one_time'}) {
3914: $envhash{'course.'.$normalid.'.last_cache'}=time;
3915: }
1.811 albertel 3916:
1.34 www 3917: if ($chome ne 'no_host') {
1.302 albertel 3918: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3919: if (!exists($returnhash{'con_lost'})) {
3920: $returnhash{'home'}= $chome;
3921: $returnhash{'domain'} = $cdomain;
3922: $returnhash{'num'} = $cnum;
1.741 raeburn 3923: if (!defined($returnhash{'type'})) {
3924: $returnhash{'type'} = 'Course';
3925: }
1.130 albertel 3926: while (my ($name,$value) = each %returnhash) {
1.53 www 3927: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3928: }
1.270 www 3929: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3930: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3931: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3932: $envhash{'course.'.$normalid.'.home'}=$chome;
3933: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3934: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3935: }
3936: }
1.731 albertel 3937: if (!$args->{'one_time'}) {
1.949 raeburn 3938: &appenv(\%envhash);
1.731 albertel 3939: }
1.302 albertel 3940: return %returnhash;
1.461 www 3941: }
3942:
1.1080 raeburn 3943: sub update_released_required {
3944: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
3945: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
3946: $cid = $env{'request.course.id'};
3947: $cdom = $env{'course.'.$cid.'.domain'};
3948: $cnum = $env{'course.'.$cid.'.num'};
3949: $chome = $env{'course.'.$cid.'.home'};
3950: }
3951: if ($needsrelease) {
3952: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
3953: my $needsupdate;
3954: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
3955: $needsupdate = 1;
3956: } else {
3957: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
3958: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
3959: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
3960: $needsupdate = 1;
3961: }
3962: }
3963: if ($needsupdate) {
3964: my %needshash = (
3965: 'internal.releaserequired' => $needsrelease,
3966: );
3967: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
3968: if ($putresult eq 'ok') {
3969: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
3970: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
3971: if (ref($crsinfo{$cid}) eq 'HASH') {
3972: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
3973: &courseidput($cdom,\%crsinfo,$chome,'notime');
3974: }
3975: }
3976: }
3977: }
3978: return;
3979: }
3980:
1.461 www 3981: # -------------------------------------------------See if a user is privileged
3982:
3983: sub privileged {
3984: my ($username,$domain)=@_;
3985: my $rolesdump=&reply("dump:$domain:$username:roles",
3986: &homeserver($username,$domain));
1.1033 raeburn 3987: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3988: ($rolesdump =~ /^error:/)) {
3989: return 0;
3990: }
1.461 www 3991: my $now=time;
3992: if ($rolesdump ne '') {
1.800 albertel 3993: foreach my $entry (split(/&/,$rolesdump)) {
3994: if ($entry!~/^rolesdef_/) {
3995: my ($area,$role)=split(/=/,$entry);
1.461 www 3996: $area=~s/\_\w\w$//;
3997: my ($trole,$tend,$tstart)=split(/_/,$role);
3998: if (($trole eq 'dc') || ($trole eq 'su')) {
3999: my $active=1;
4000: if ($tend) {
4001: if ($tend<$now) { $active=0; }
4002: }
4003: if ($tstart) {
4004: if ($tstart>$now) { $active=0; }
4005: }
4006: if ($active) { return 1; }
4007: }
4008: }
4009: }
4010: }
4011: return 0;
1.9 www 4012: }
1.1 albertel 4013:
1.103 harris41 4014: # -------------------------------------------------------- Get user privileges
1.11 www 4015:
4016: sub rolesinit {
4017: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4018: my $now=time;
4019: my %userroles = ('user.login.time' => $now);
1.1086 ! raeburn 4020: my $extra = &freeze_escape({'skipcheck' => 1});
1.1078 raeburn 4021: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4022: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1078 raeburn 4023: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4024: return \%userroles;
4025: }
1.11 www 4026: my %allroles=();
1.678 raeburn 4027: my %allgroups=();
4028: my $group_privs;
1.11 www 4029:
4030: if ($rolesdump ne '') {
1.800 albertel 4031: foreach my $entry (split(/&/,$rolesdump)) {
4032: if ($entry!~/^rolesdef_/) {
4033: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4034: $area=~s/\_\w\w$//;
1.678 raeburn 4035: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4036: if ($role=~/^cr/) {
1.807 albertel 4037: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4038: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4039: ($tend,$tstart)=split('_',$trest);
4040: } else {
4041: $trole=$role;
4042: }
1.678 raeburn 4043: } elsif ($role =~ m|^gr/|) {
4044: ($trole,$tend,$tstart) = split(/_/,$role);
4045: ($trole,$group_privs) = split(/\//,$trole);
4046: $group_privs = &unescape($group_privs);
1.587 albertel 4047: } else {
4048: ($trole,$tend,$tstart)=split(/_/,$role);
4049: }
1.743 albertel 4050: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4051: $username);
4052: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4053: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4054: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4055: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4056: my $spec=$trole.'.'.$area;
4057: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4058: if ($trole =~ /^cr\//) {
1.567 raeburn 4059: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4060: } elsif ($trole eq 'gr') {
4061: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4062: } else {
1.567 raeburn 4063: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4064: }
1.12 www 4065: }
1.662 raeburn 4066: }
1.191 harris41 4067: }
1.743 albertel 4068: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4069: $userroles{'user.adv'} = $adv;
4070: $userroles{'user.author'} = $author;
1.620 albertel 4071: $env{'user.adv'}=$adv;
1.11 www 4072: }
1.743 albertel 4073: return \%userroles;
1.11 www 4074: }
4075:
1.567 raeburn 4076: sub set_arearole {
4077: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4078: # log the associated role with the area
4079: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4080: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4081: }
4082:
4083: sub custom_roleprivs {
4084: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4085: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4086: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4087: if (&hostname($homsvr) ne '') {
1.567 raeburn 4088: my ($rdummy,$roledef)=
4089: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4090: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4091: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4092: if (defined($syspriv)) {
1.1043 raeburn 4093: if ($trest =~ /^$match_community$/) {
4094: $syspriv =~ s/bre\&S//;
4095: }
1.567 raeburn 4096: $$allroles{'cm./'}.=':'.$syspriv;
4097: $$allroles{$spec.'./'}.=':'.$syspriv;
4098: }
4099: if ($tdomain ne '') {
4100: if (defined($dompriv)) {
4101: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4102: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4103: }
4104: if (($trest ne '') && (defined($coursepriv))) {
4105: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4106: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4107: }
4108: }
4109: }
4110: }
4111: }
4112:
1.678 raeburn 4113: sub group_roleprivs {
4114: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4115: my $access = 1;
4116: my $now = time;
4117: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4118: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4119: if ($access) {
1.811 albertel 4120: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4121: $$allgroups{$course}{$group} .=':'.$group_privs;
4122: }
4123: }
1.567 raeburn 4124:
4125: sub standard_roleprivs {
4126: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4127: if (defined($pr{$trole.':s'})) {
4128: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4129: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4130: }
4131: if ($tdomain ne '') {
4132: if (defined($pr{$trole.':d'})) {
4133: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4134: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4135: }
4136: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4137: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4138: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4139: }
4140: }
4141: }
4142:
4143: sub set_userprivs {
1.1064 raeburn 4144: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4145: my $author=0;
4146: my $adv=0;
1.678 raeburn 4147: my %grouproles = ();
4148: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4149: my @groupkeys;
1.1000 raeburn 4150: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4151: push(@groupkeys,$role);
4152: }
4153: if (ref($groups_roles) eq 'HASH') {
4154: foreach my $key (keys(%{$groups_roles})) {
4155: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4156: push(@groupkeys,$key);
4157: }
4158: }
4159: }
4160: if (@groupkeys > 0) {
4161: foreach my $role (@groupkeys) {
4162: my ($trole,$area,$sec,$extendedarea);
4163: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4164: $trole = $1;
4165: $area = $2;
4166: $sec = $3;
4167: $extendedarea = $area.$sec;
4168: if (exists($$allgroups{$area})) {
4169: foreach my $group (keys(%{$$allgroups{$area}})) {
4170: my $spec = $trole.'.'.$extendedarea;
4171: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4172: $$allgroups{$area}{$group};
1.1064 raeburn 4173: }
1.678 raeburn 4174: }
4175: }
4176: }
4177: }
4178: }
1.800 albertel 4179: foreach my $group (keys(%grouproles)) {
4180: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4181: }
1.800 albertel 4182: foreach my $role (keys(%{$allroles})) {
4183: my %thesepriv;
1.941 raeburn 4184: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4185: foreach my $item (split(/:/,$$allroles{$role})) {
4186: if ($item ne '') {
4187: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4188: if ($restrictions eq '') {
4189: $thesepriv{$privilege}='F';
4190: } elsif ($thesepriv{$privilege} ne 'F') {
4191: $thesepriv{$privilege}.=$restrictions;
4192: }
4193: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4194: }
4195: }
4196: my $thesestr='';
1.800 albertel 4197: foreach my $priv (keys(%thesepriv)) {
4198: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4199: }
4200: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4201: }
4202: return ($author,$adv);
4203: }
4204:
1.994 raeburn 4205: sub role_status {
1.1002 raeburn 4206: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4207: my @pwhere = ();
4208: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4209: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4210: unless (!defined($$role) || $$role eq '') {
4211: $$where=join('.',@pwhere);
4212: $$trolecode=$$role.'.'.$$where;
4213: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4214: $$tstatus='is';
4215: if ($$tstart && $$tstart>$then) {
4216: $$tstatus='future';
1.1034 raeburn 4217: if ($$tstart<$now) {
4218: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4219: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4220: my (%allroles,%allgroups,$group_privs,
4221: %groups_roles,@rolecodes);
1.1002 raeburn 4222: my %userroles = (
4223: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4224: );
1.1064 raeburn 4225: @rolecodes = ('cm');
1.1002 raeburn 4226: my $spec=$$role.'.'.$$where;
4227: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4228: if ($$role =~ /^cr\//) {
4229: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4230: push(@rolecodes,'cr');
1.1002 raeburn 4231: } elsif ($$role eq 'gr') {
1.1064 raeburn 4232: push(@rolecodes,$$role);
1.1002 raeburn 4233: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4234: $env{'user.name'});
1.1064 raeburn 4235: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4236: (undef,my $group_privs) = split(/\//,$trole);
4237: $group_privs = &unescape($group_privs);
4238: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4239: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4240: if (keys(%course_roles) > 0) {
4241: my ($tnum) = ($trest =~ /^($match_courseid)/);
4242: if ($tdomain ne '' && $tnum ne '') {
4243: foreach my $key (keys(%course_roles)) {
4244: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4245: my $crsrole = $1;
4246: my $crssec = $2;
4247: if ($crsrole =~ /^cr/) {
4248: unless (grep(/^cr$/,@rolecodes)) {
4249: push(@rolecodes,'cr');
4250: }
4251: } else {
4252: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4253: push(@rolecodes,$crsrole);
4254: }
4255: }
4256: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4257: if ($crssec ne '') {
4258: $rolekey .= '/'.$crssec;
4259: }
4260: $rolekey .= './';
4261: $groups_roles{$rolekey} = \@rolecodes;
4262: }
4263: }
4264: }
4265: }
1.1002 raeburn 4266: } else {
1.1064 raeburn 4267: push(@rolecodes,$$role);
1.1002 raeburn 4268: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4269: }
1.1064 raeburn 4270: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4271: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4272: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4273: }
4274: }
1.1034 raeburn 4275: $$tstatus = 'is';
1.1002 raeburn 4276: }
1.994 raeburn 4277: }
4278: if ($$tend) {
4279: if ($$tend<$then) {
4280: $$tstatus='expired';
4281: } elsif ($$tend<$now) {
4282: $$tstatus='will_not';
4283: }
4284: }
4285: }
4286: }
4287: }
4288:
4289: sub check_adhoc_privs {
1.1002 raeburn 4290: my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994 raeburn 4291: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4292: if ($env{$cckey}) {
4293: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4294: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4295: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4296: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4297: }
4298: } else {
4299: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4300: }
4301: }
4302:
4303: sub set_adhoc_privileges {
4304: # role can be cc or ca
4305: my ($dcdom,$pickedcourse,$role) = @_;
4306: my $area = '/'.$dcdom.'/'.$pickedcourse;
4307: my $spec = $role.'.'.$area;
4308: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4309: $env{'user.name'});
4310: my %ccrole = ();
4311: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4312: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4313: &appenv(\%userroles,[$role,'cm']);
4314: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4315: &appenv( {'request.role' => $spec,
4316: 'request.role.domain' => $dcdom,
4317: 'request.course.sec' => ''
4318: }
4319: );
4320: my $tadv=0;
4321: if (&allowed('adv') eq 'F') { $tadv=1; }
4322: &appenv({'request.role.adv' => $tadv});
4323: }
4324:
1.12 www 4325: # --------------------------------------------------------------- get interface
4326:
4327: sub get {
1.131 albertel 4328: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4329: my $items='';
1.800 albertel 4330: foreach my $item (@$storearr) {
4331: $items.=&escape($item).'&';
1.191 harris41 4332: }
1.12 www 4333: $items=~s/\&$//;
1.620 albertel 4334: if (!$udomain) { $udomain=$env{'user.domain'}; }
4335: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4336: my $uhome=&homeserver($uname,$udomain);
4337:
1.133 albertel 4338: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4339: my @pairs=split(/\&/,$rep);
1.273 albertel 4340: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4341: return @pairs;
4342: }
1.15 www 4343: my %returnhash=();
1.42 www 4344: my $i=0;
1.800 albertel 4345: foreach my $item (@$storearr) {
4346: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4347: $i++;
1.191 harris41 4348: }
1.15 www 4349: return %returnhash;
1.27 www 4350: }
4351:
4352: # --------------------------------------------------------------- del interface
4353:
4354: sub del {
1.133 albertel 4355: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4356: my $items='';
1.800 albertel 4357: foreach my $item (@$storearr) {
4358: $items.=&escape($item).'&';
1.191 harris41 4359: }
1.984 neumanie 4360:
1.27 www 4361: $items=~s/\&$//;
1.620 albertel 4362: if (!$udomain) { $udomain=$env{'user.domain'}; }
4363: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4364: my $uhome=&homeserver($uname,$udomain);
4365: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4366: }
4367:
4368: # -------------------------------------------------------------- dump interface
4369:
4370: sub dump {
1.1086 ! raeburn 4371: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4372: if (!$udomain) { $udomain=$env{'user.domain'}; }
4373: if (!$uname) { $uname=$env{'user.name'}; }
4374: my $uhome=&homeserver($uname,$udomain);
4375: if ($regexp) {
4376: $regexp=&escape($regexp);
4377: } else {
4378: $regexp='.';
4379: }
1.1086 ! raeburn 4380: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4381: my @pairs=split(/\&/,$rep);
4382: my %returnhash=();
4383: foreach my $item (@pairs) {
4384: my ($key,$value)=split(/=/,$item,2);
4385: $key = &unescape($key);
4386: next if ($key =~ /^error: 2 /);
4387: $returnhash{$key}=&thaw_unescape($value);
4388: }
4389: return %returnhash;
1.407 www 4390: }
4391:
1.717 albertel 4392: # --------------------------------------------------------- dumpstore interface
4393:
4394: sub dumpstore {
4395: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4396: if (!$udomain) { $udomain=$env{'user.domain'}; }
4397: if (!$uname) { $uname=$env{'user.name'}; }
4398: my $uhome=&homeserver($uname,$udomain);
4399: if ($regexp) {
4400: $regexp=&escape($regexp);
4401: } else {
4402: $regexp='.';
4403: }
4404: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4405: my @pairs=split(/\&/,$rep);
4406: my %returnhash=();
4407: foreach my $item (@pairs) {
4408: my ($key,$value)=split(/=/,$item,2);
4409: next if ($key =~ /^error: 2 /);
4410: $returnhash{$key}=&thaw_unescape($value);
4411: }
4412: return %returnhash;
1.717 albertel 4413: }
4414:
1.407 www 4415: # -------------------------------------------------------------- keys interface
4416:
4417: sub getkeys {
4418: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4419: if (!$udomain) { $udomain=$env{'user.domain'}; }
4420: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4421: my $uhome=&homeserver($uname,$udomain);
4422: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4423: my @keyarray=();
1.800 albertel 4424: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4425: next if ($key =~ /^error: 2 /);
1.800 albertel 4426: push(@keyarray,&unescape($key));
1.407 www 4427: }
4428: return @keyarray;
1.318 matthew 4429: }
4430:
1.319 matthew 4431: # --------------------------------------------------------------- currentdump
4432: sub currentdump {
1.328 matthew 4433: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4434: $courseid = $env{'request.course.id'} if (! defined($courseid));
4435: $sdom = $env{'user.domain'} if (! defined($sdom));
4436: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4437: my $uhome = &homeserver($sname,$sdom);
4438: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4439: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4440: #
1.318 matthew 4441: my %returnhash=();
1.319 matthew 4442: #
4443: if ($rep eq "unknown_cmd") {
4444: # an old lond will not know currentdump
4445: # Do a dump and make it look like a currentdump
1.822 albertel 4446: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4447: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4448: my %hash = @tmp;
4449: @tmp=();
1.424 matthew 4450: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4451: } else {
4452: my @pairs=split(/\&/,$rep);
1.800 albertel 4453: foreach my $pair (@pairs) {
4454: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4455: my ($symb,$param) = split(/:/,$key);
4456: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4457: &thaw_unescape($value);
1.319 matthew 4458: }
1.191 harris41 4459: }
1.12 www 4460: return %returnhash;
1.424 matthew 4461: }
4462:
4463: sub convert_dump_to_currentdump{
4464: my %hash = %{shift()};
4465: my %returnhash;
4466: # Code ripped from lond, essentially. The only difference
4467: # here is the unescaping done by lonnet::dump(). Conceivably
4468: # we might run in to problems with parameter names =~ /^v\./
4469: while (my ($key,$value) = each(%hash)) {
4470: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4471: $symb = &unescape($symb);
4472: $param = &unescape($param);
1.424 matthew 4473: next if ($v eq 'version' || $symb eq 'keys');
4474: next if (exists($returnhash{$symb}) &&
4475: exists($returnhash{$symb}->{$param}) &&
4476: $returnhash{$symb}->{'v.'.$param} > $v);
4477: $returnhash{$symb}->{$param}=$value;
4478: $returnhash{$symb}->{'v.'.$param}=$v;
4479: }
4480: #
4481: # Remove all of the keys in the hashes which keep track of
4482: # the version of the parameter.
4483: while (my ($symb,$param_hash) = each(%returnhash)) {
4484: # use a foreach because we are going to delete from the hash.
4485: foreach my $key (keys(%$param_hash)) {
4486: delete($param_hash->{$key}) if ($key =~ /^v\./);
4487: }
4488: }
4489: return \%returnhash;
1.12 www 4490: }
4491:
1.627 albertel 4492: # ------------------------------------------------------ critical inc interface
4493:
4494: sub cinc {
4495: return &inc(@_,'critical');
4496: }
4497:
1.449 matthew 4498: # --------------------------------------------------------------- inc interface
4499:
4500: sub inc {
1.627 albertel 4501: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4502: if (!$udomain) { $udomain=$env{'user.domain'}; }
4503: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4504: my $uhome=&homeserver($uname,$udomain);
4505: my $items='';
4506: if (! ref($store)) {
4507: # got a single value, so use that instead
4508: $items = &escape($store).'=&';
4509: } elsif (ref($store) eq 'SCALAR') {
4510: $items = &escape($$store).'=&';
4511: } elsif (ref($store) eq 'ARRAY') {
4512: $items = join('=&',map {&escape($_);} @{$store});
4513: } elsif (ref($store) eq 'HASH') {
4514: while (my($key,$value) = each(%{$store})) {
4515: $items.= &escape($key).'='.&escape($value).'&';
4516: }
4517: }
4518: $items=~s/\&$//;
1.627 albertel 4519: if ($critical) {
4520: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4521: } else {
4522: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4523: }
1.449 matthew 4524: }
4525:
1.12 www 4526: # --------------------------------------------------------------- put interface
4527:
4528: sub put {
1.134 albertel 4529: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4530: if (!$udomain) { $udomain=$env{'user.domain'}; }
4531: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4532: my $uhome=&homeserver($uname,$udomain);
1.12 www 4533: my $items='';
1.800 albertel 4534: foreach my $item (keys(%$storehash)) {
4535: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4536: }
1.12 www 4537: $items=~s/\&$//;
1.134 albertel 4538: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4539: }
4540:
1.631 albertel 4541: # ------------------------------------------------------------ newput interface
4542:
4543: sub newput {
4544: my ($namespace,$storehash,$udomain,$uname)=@_;
4545: if (!$udomain) { $udomain=$env{'user.domain'}; }
4546: if (!$uname) { $uname=$env{'user.name'}; }
4547: my $uhome=&homeserver($uname,$udomain);
4548: my $items='';
4549: foreach my $key (keys(%$storehash)) {
4550: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4551: }
4552: $items=~s/\&$//;
4553: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4554: }
4555:
4556: # --------------------------------------------------------- putstore interface
4557:
1.524 raeburn 4558: sub putstore {
1.715 albertel 4559: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4560: if (!$udomain) { $udomain=$env{'user.domain'}; }
4561: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4562: my $uhome=&homeserver($uname,$udomain);
4563: my $items='';
1.715 albertel 4564: foreach my $key (keys(%$storehash)) {
4565: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4566: }
1.715 albertel 4567: $items=~s/\&$//;
1.716 albertel 4568: my $esc_symb=&escape($symb);
4569: my $esc_v=&escape($version);
1.715 albertel 4570: my $reply =
1.716 albertel 4571: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4572: $uhome);
4573: if ($reply eq 'unknown_cmd') {
1.716 albertel 4574: # gfall back to way things use to be done
1.715 albertel 4575: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4576: $uname);
1.524 raeburn 4577: }
1.715 albertel 4578: return $reply;
4579: }
4580:
4581: sub old_putstore {
1.716 albertel 4582: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4583: if (!$udomain) { $udomain=$env{'user.domain'}; }
4584: if (!$uname) { $uname=$env{'user.name'}; }
4585: my $uhome=&homeserver($uname,$udomain);
4586: my %newstorehash;
1.800 albertel 4587: foreach my $item (keys(%$storehash)) {
4588: my $key = $version.':'.&escape($symb).':'.$item;
4589: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4590: }
4591: my $items='';
4592: my %allitems = ();
1.800 albertel 4593: foreach my $item (keys(%newstorehash)) {
4594: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4595: my $key = $1.':keys:'.$2;
4596: $allitems{$key} .= $3.':';
4597: }
1.800 albertel 4598: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4599: }
1.800 albertel 4600: foreach my $item (keys(%allitems)) {
4601: $allitems{$item} =~ s/\:$//;
4602: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4603: }
4604: $items=~s/\&$//;
4605: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4606: }
4607:
1.47 www 4608: # ------------------------------------------------------ critical put interface
4609:
4610: sub cput {
1.134 albertel 4611: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4612: if (!$udomain) { $udomain=$env{'user.domain'}; }
4613: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4614: my $uhome=&homeserver($uname,$udomain);
1.47 www 4615: my $items='';
1.800 albertel 4616: foreach my $item (keys(%$storehash)) {
4617: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4618: }
1.47 www 4619: $items=~s/\&$//;
1.134 albertel 4620: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4621: }
4622:
4623: # -------------------------------------------------------------- eget interface
4624:
4625: sub eget {
1.133 albertel 4626: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4627: my $items='';
1.800 albertel 4628: foreach my $item (@$storearr) {
4629: $items.=&escape($item).'&';
1.191 harris41 4630: }
1.12 www 4631: $items=~s/\&$//;
1.620 albertel 4632: if (!$udomain) { $udomain=$env{'user.domain'}; }
4633: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4634: my $uhome=&homeserver($uname,$udomain);
4635: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4636: my @pairs=split(/\&/,$rep);
4637: my %returnhash=();
1.42 www 4638: my $i=0;
1.800 albertel 4639: foreach my $item (@$storearr) {
4640: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4641: $i++;
1.191 harris41 4642: }
1.12 www 4643: return %returnhash;
4644: }
4645:
1.667 albertel 4646: # ------------------------------------------------------------ tmpput interface
4647: sub tmpput {
1.802 raeburn 4648: my ($storehash,$server,$context)=@_;
1.667 albertel 4649: my $items='';
1.800 albertel 4650: foreach my $item (keys(%$storehash)) {
4651: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4652: }
4653: $items=~s/\&$//;
1.802 raeburn 4654: if (defined($context)) {
4655: $items .= ':'.&escape($context);
4656: }
1.667 albertel 4657: return &reply("tmpput:$items",$server);
4658: }
4659:
4660: # ------------------------------------------------------------ tmpget interface
4661: sub tmpget {
1.688 albertel 4662: my ($token,$server)=@_;
4663: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4664: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4665: my %returnhash;
4666: foreach my $item (split(/\&/,$rep)) {
4667: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4668: next if ($key =~ /^error: 2 /);
1.667 albertel 4669: $returnhash{&unescape($key)}=&thaw_unescape($value);
4670: }
4671: return %returnhash;
4672: }
4673:
1.688 albertel 4674: # ------------------------------------------------------------ tmpget interface
4675: sub tmpdel {
4676: my ($token,$server)=@_;
4677: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4678: return &reply("tmpdel:$token",$server);
4679: }
4680:
1.765 albertel 4681: # -------------------------------------------------- portfolio access checking
4682:
4683: sub portfolio_access {
1.766 albertel 4684: my ($requrl) = @_;
1.765 albertel 4685: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4686: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4687: if ($result) {
4688: my %setters;
4689: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4690: my ($startblock,$endblock) =
4691: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4692: if ($startblock && $endblock) {
4693: return 'B';
4694: }
4695: } else {
4696: my ($startblock,$endblock) =
4697: &Apache::loncommon::blockcheck(\%setters,'port');
4698: if ($startblock && $endblock) {
4699: return 'B';
4700: }
4701: }
4702: }
1.765 albertel 4703: if ($result eq 'ok') {
1.766 albertel 4704: return 'F';
1.765 albertel 4705: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4706: return 'A';
1.765 albertel 4707: }
1.766 albertel 4708: return '';
1.765 albertel 4709: }
4710:
4711: sub get_portfolio_access {
1.767 albertel 4712: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4713:
4714: if (!ref($access_hash)) {
4715: my $current_perms = &get_portfile_permissions($udom,$unum);
4716: my %access_controls = &get_access_controls($current_perms,$group,
4717: $file_name);
4718: $access_hash = $access_controls{$file_name};
4719: }
4720:
1.765 albertel 4721: my ($public,$guest,@domains,@users,@courses,@groups);
4722: my $now = time;
4723: if (ref($access_hash) eq 'HASH') {
4724: foreach my $key (keys(%{$access_hash})) {
4725: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4726: if ($start > $now) {
4727: next;
4728: }
4729: if ($end && $end<$now) {
4730: next;
4731: }
4732: if ($scope eq 'public') {
4733: $public = $key;
4734: last;
4735: } elsif ($scope eq 'guest') {
4736: $guest = $key;
4737: } elsif ($scope eq 'domains') {
4738: push(@domains,$key);
4739: } elsif ($scope eq 'users') {
4740: push(@users,$key);
4741: } elsif ($scope eq 'course') {
4742: push(@courses,$key);
4743: } elsif ($scope eq 'group') {
4744: push(@groups,$key);
4745: }
4746: }
4747: if ($public) {
4748: return 'ok';
4749: }
4750: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4751: if ($guest) {
4752: return $guest;
4753: }
4754: } else {
4755: if (@domains > 0) {
4756: foreach my $domkey (@domains) {
4757: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4758: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4759: return 'ok';
4760: }
4761: }
4762: }
4763: }
4764: if (@users > 0) {
4765: foreach my $userkey (@users) {
1.865 raeburn 4766: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4767: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4768: if (ref($item) eq 'HASH') {
4769: if (($item->{'uname'} eq $env{'user.name'}) &&
4770: ($item->{'udom'} eq $env{'user.domain'})) {
4771: return 'ok';
4772: }
4773: }
4774: }
4775: }
1.765 albertel 4776: }
4777: }
4778: my %roleshash;
4779: my @courses_and_groups = @courses;
4780: push(@courses_and_groups,@groups);
4781: if (@courses_and_groups > 0) {
4782: my (%allgroups,%allroles);
4783: my ($start,$end,$role,$sec,$group);
4784: foreach my $envkey (%env) {
1.1060 raeburn 4785: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4786: my $cid = $2.'_'.$3;
4787: if ($1 eq 'gr') {
4788: $group = $4;
4789: $allgroups{$cid}{$group} = $env{$envkey};
4790: } else {
4791: if ($4 eq '') {
4792: $sec = 'none';
4793: } else {
4794: $sec = $4;
4795: }
4796: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4797: }
1.811 albertel 4798: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4799: my $cid = $2.'_'.$3;
4800: if ($4 eq '') {
4801: $sec = 'none';
4802: } else {
4803: $sec = $4;
4804: }
4805: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4806: }
4807: }
4808: if (keys(%allroles) == 0) {
4809: return;
4810: }
4811: foreach my $key (@courses_and_groups) {
4812: my %content = %{$$access_hash{$key}};
4813: my $cnum = $content{'number'};
4814: my $cdom = $content{'domain'};
4815: my $cid = $cdom.'_'.$cnum;
4816: if (!exists($allroles{$cid})) {
4817: next;
4818: }
4819: foreach my $role_id (keys(%{$content{'roles'}})) {
4820: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4821: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4822: my @status = @{$content{'roles'}{$role_id}{'access'}};
4823: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4824: foreach my $role (keys(%{$allroles{$cid}})) {
4825: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4826: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4827: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4828: if (grep/^all$/,@sections) {
4829: return 'ok';
4830: } else {
4831: if (grep/^$sec$/,@sections) {
4832: return 'ok';
4833: }
4834: }
4835: }
4836: }
4837: if (keys(%{$allgroups{$cid}}) == 0) {
4838: if (grep/^none$/,@groups) {
4839: return 'ok';
4840: }
4841: } else {
4842: if (grep/^all$/,@groups) {
4843: return 'ok';
4844: }
4845: foreach my $group (keys(%{$allgroups{$cid}})) {
4846: if (grep/^$group$/,@groups) {
4847: return 'ok';
4848: }
4849: }
4850: }
4851: }
4852: }
4853: }
4854: }
4855: }
4856: if ($guest) {
4857: return $guest;
4858: }
4859: }
4860: }
4861: return;
4862: }
4863:
4864: sub course_group_datechecker {
4865: my ($dates,$now,$status) = @_;
4866: my ($start,$end) = split(/\./,$dates);
4867: if (!$start && !$end) {
4868: return 'ok';
4869: }
4870: if (grep/^active$/,@{$status}) {
4871: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4872: return 'ok';
4873: }
4874: }
4875: if (grep/^previous$/,@{$status}) {
4876: if ($end > $now ) {
4877: return 'ok';
4878: }
4879: }
4880: if (grep/^future$/,@{$status}) {
4881: if ($start > $now) {
4882: return 'ok';
4883: }
4884: }
4885: return;
4886: }
4887:
4888: sub parse_portfolio_url {
4889: my ($url) = @_;
4890:
4891: my ($type,$udom,$unum,$group,$file_name);
4892:
1.823 albertel 4893: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4894: $type = 1;
4895: $udom = $1;
4896: $unum = $2;
4897: $file_name = $3;
1.823 albertel 4898: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4899: $type = 2;
4900: $udom = $1;
4901: $unum = $2;
4902: $group = $3;
4903: $file_name = $3.'/'.$4;
4904: }
4905: if (wantarray) {
4906: return ($type,$udom,$unum,$file_name,$group);
4907: }
4908: return $type;
4909: }
4910:
4911: sub is_portfolio_url {
4912: my ($url) = @_;
4913: return scalar(&parse_portfolio_url($url));
4914: }
4915:
1.798 raeburn 4916: sub is_portfolio_file {
4917: my ($file) = @_;
1.820 raeburn 4918: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4919: return 1;
4920: }
4921: return;
4922: }
4923:
1.976 raeburn 4924: sub usertools_access {
1.1084 raeburn 4925: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 4926: my ($access,%tools);
4927: if ($context eq '') {
4928: $context = 'tools';
4929: }
4930: if ($context eq 'requestcourses') {
4931: %tools = (
4932: official => 1,
4933: unofficial => 1,
1.1006 raeburn 4934: community => 1,
1.985 raeburn 4935: );
4936: } else {
4937: %tools = (
4938: aboutme => 1,
4939: blog => 1,
4940: portfolio => 1,
4941: );
4942: }
1.976 raeburn 4943: return if (!defined($tools{$tool}));
4944:
4945: if ((!defined($udom)) || (!defined($uname))) {
4946: $udom = $env{'user.domain'};
4947: $uname = $env{'user.name'};
4948: }
4949:
1.978 raeburn 4950: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4951: if ($action ne 'reload') {
1.985 raeburn 4952: if ($context eq 'requestcourses') {
4953: return $env{'environment.canrequest.'.$tool};
4954: } else {
4955: return $env{'environment.availabletools.'.$tool};
4956: }
4957: }
1.976 raeburn 4958: }
4959:
4960: my ($toolstatus,$inststatus);
4961:
1.985 raeburn 4962: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4963: ($action ne 'reload')) {
4964: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 4965: $inststatus = $env{'environment.inststatus'};
4966: } else {
1.1084 raeburn 4967: if (ref($userenvref) eq 'HASH') {
4968: $toolstatus = $userenvref->{$context.'.'.$tool};
4969: $inststatus = $userenvref->{'inststatus'};
4970: } else {
4971: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
4972: $toolstatus = $userenv{$context.'.'.$tool};
4973: $inststatus = $userenv{'inststatus'};
4974: }
1.976 raeburn 4975: }
4976:
4977: if ($toolstatus ne '') {
4978: if ($toolstatus) {
4979: $access = 1;
4980: } else {
4981: $access = 0;
4982: }
4983: return $access;
4984: }
4985:
1.1084 raeburn 4986: my ($is_adv,%domdef);
4987: if (ref($is_advref) eq 'HASH') {
4988: $is_adv = $is_advref->{'is_adv'};
4989: } else {
4990: $is_adv = &is_advanced_user($udom,$uname);
4991: }
4992: if (ref($domdefref) eq 'HASH') {
4993: %domdef = %{$domdefref};
4994: } else {
4995: %domdef = &get_domain_defaults($udom);
4996: }
1.976 raeburn 4997: if (ref($domdef{$tool}) eq 'HASH') {
4998: if ($is_adv) {
4999: if ($domdef{$tool}{'_LC_adv'} ne '') {
5000: if ($domdef{$tool}{'_LC_adv'}) {
5001: $access = 1;
5002: } else {
5003: $access = 0;
5004: }
5005: return $access;
5006: }
5007: }
5008: if ($inststatus ne '') {
5009: my ($hasaccess,$hasnoaccess);
5010: foreach my $affiliation (split(/:/,$inststatus)) {
5011: if ($domdef{$tool}{$affiliation} ne '') {
5012: if ($domdef{$tool}{$affiliation}) {
5013: $hasaccess = 1;
5014: } else {
5015: $hasnoaccess = 1;
5016: }
5017: }
5018: }
5019: if ($hasaccess || $hasnoaccess) {
5020: if ($hasaccess) {
5021: $access = 1;
5022: } elsif ($hasnoaccess) {
5023: $access = 0;
5024: }
5025: return $access;
5026: }
5027: } else {
5028: if ($domdef{$tool}{'default'} ne '') {
5029: if ($domdef{$tool}{'default'}) {
5030: $access = 1;
5031: } elsif ($domdef{$tool}{'default'} == 0) {
5032: $access = 0;
5033: }
5034: return $access;
5035: }
5036: }
5037: } else {
1.985 raeburn 5038: if ($context eq 'tools') {
5039: $access = 1;
5040: } else {
5041: $access = 0;
5042: }
1.976 raeburn 5043: return $access;
5044: }
5045: }
5046:
1.1050 raeburn 5047: sub is_course_owner {
5048: my ($cdom,$cnum,$udom,$uname) = @_;
5049: if (($udom eq '') || ($uname eq '')) {
5050: $udom = $env{'user.domain'};
5051: $uname = $env{'user.name'};
5052: }
5053: unless (($udom eq '') || ($uname eq '')) {
5054: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5055: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5056: return 1;
5057: } else {
5058: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5059: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5060: return 1;
5061: }
5062: }
5063: }
5064: }
5065: return;
5066: }
5067:
1.976 raeburn 5068: sub is_advanced_user {
5069: my ($udom,$uname) = @_;
1.1085 raeburn 5070: if ($udom ne '' && $uname ne '') {
5071: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5072: return $env{'user.adv'};
5073: }
5074: }
1.976 raeburn 5075: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5076: my %allroles;
5077: my $is_adv;
5078: foreach my $role (keys(%roleshash)) {
5079: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5080: my $area = '/'.$tdomain.'/'.$trest;
5081: if ($sec ne '') {
5082: $area .= '/'.$sec;
5083: }
5084: if (($area ne '') && ($trole ne '')) {
5085: my $spec=$trole.'.'.$area;
5086: if ($trole =~ /^cr\//) {
5087: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5088: } elsif ($trole ne 'gr') {
5089: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5090: }
5091: }
5092: }
5093: foreach my $role (keys(%allroles)) {
5094: last if ($is_adv);
5095: foreach my $item (split(/:/,$allroles{$role})) {
5096: if ($item ne '') {
5097: my ($privilege,$restrictions)=split(/&/,$item);
5098: if ($privilege eq 'adv') {
5099: $is_adv = 1;
5100: last;
5101: }
5102: }
5103: }
5104: }
5105: return $is_adv;
5106: }
1.798 raeburn 5107:
1.1035 raeburn 5108: sub check_can_request {
1.1036 raeburn 5109: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5110: my $canreq = 0;
5111: my ($types,$typename) = &Apache::loncommon::course_types();
5112: my @options = ('approval','validate','autolimit');
5113: my $optregex = join('|',@options);
5114: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5115: foreach my $type (@{$types}) {
5116: if (&usertools_access($env{'user.name'},
5117: $env{'user.domain'},
5118: $type,undef,'requestcourses')) {
5119: $canreq ++;
1.1036 raeburn 5120: if (ref($request_domains) eq 'HASH') {
5121: push(@{$request_domains->{$type}},$env{'user.domain'});
5122: }
1.1035 raeburn 5123: if ($dom eq $env{'user.domain'}) {
5124: $can_request->{$type} = 1;
5125: }
5126: }
5127: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5128: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5129: if (@curr > 0) {
1.1036 raeburn 5130: foreach my $item (@curr) {
5131: if (ref($request_domains) eq 'HASH') {
5132: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5133: if ($otherdom ne '') {
5134: if (ref($request_domains->{$type}) eq 'ARRAY') {
5135: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5136: push(@{$request_domains->{$type}},$otherdom);
5137: }
5138: } else {
5139: push(@{$request_domains->{$type}},$otherdom);
5140: }
5141: }
5142: }
5143: }
5144: unless($dom eq $env{'user.domain'}) {
5145: $canreq ++;
1.1035 raeburn 5146: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5147: $can_request->{$type} = 1;
5148: }
5149: }
5150: }
5151: }
5152: }
5153: }
5154: return $canreq;
5155: }
5156:
1.341 www 5157: # ---------------------------------------------- Custom access rule evaluation
5158:
5159: sub customaccess {
5160: my ($priv,$uri)=@_;
1.807 albertel 5161: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5162: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5163: $udom = &LONCAPA::clean_domain($udom);
5164: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5165: my $access=0;
1.800 albertel 5166: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5167: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5168: if ($type eq 'user') {
5169: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5170: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5171: if ($tdom) {
5172: if ($tdom ne $env{'user.domain'}) { next; }
5173: }
1.896 albertel 5174: if ($tuname) {
5175: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5176: }
5177: $access=($effect eq 'allow');
5178: last;
5179: }
5180: } else {
5181: if ($role) {
5182: if ($role ne $urole) { next; }
5183: }
5184: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5185: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5186: if ($tdom) {
5187: if ($tdom ne $udom) { next; }
5188: }
5189: if ($tcrs) {
5190: if ($tcrs ne $ucrs) { next; }
5191: }
5192: if ($tsec) {
5193: if ($tsec ne $usec) { next; }
5194: }
5195: $access=($effect eq 'allow');
5196: last;
5197: }
5198: if ($realm eq '' && $role eq '') {
5199: $access=($effect eq 'allow');
5200: }
1.402 bowersj2 5201: }
1.341 www 5202: }
5203: return $access;
5204: }
5205:
1.103 harris41 5206: # ------------------------------------------------- Check for a user privilege
1.12 www 5207:
5208: sub allowed {
1.810 raeburn 5209: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5210: my $ver_orguri=$uri;
1.439 www 5211: $uri=&deversion($uri);
1.152 www 5212: my $orguri=$uri;
1.52 www 5213: $uri=&declutter($uri);
1.809 raeburn 5214:
1.810 raeburn 5215: if ($priv eq 'evb') {
5216: # Evade communication block restrictions for specified role in a course
5217: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5218: return $1;
5219: } else {
5220: return;
5221: }
5222: }
5223:
1.620 albertel 5224: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5225: # Free bre access to adm and meta resources
1.775 albertel 5226: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5227: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5228: && ($priv eq 'bre')) {
1.14 www 5229: return 'F';
1.159 www 5230: }
5231:
1.545 banghart 5232: # Free bre access to user's own portfolio contents
1.714 raeburn 5233: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5234: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5235: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5236: my %setters;
5237: my ($startblock,$endblock) =
5238: &Apache::loncommon::blockcheck(\%setters,'port');
5239: if ($startblock && $endblock) {
5240: return 'B';
5241: } else {
5242: return 'F';
5243: }
1.545 banghart 5244: }
5245:
1.762 raeburn 5246: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5247: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5248: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5249: if (exists($env{'request.course.id'})) {
5250: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5251: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5252: if (($domain eq $cdom) && ($name eq $cnum)) {
5253: my $courseprivid=$env{'request.course.id'};
5254: $courseprivid=~s/\_/\//;
5255: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5256: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5257: return $1;
1.762 raeburn 5258: } else {
5259: if ($env{'request.course.sec'}) {
5260: $courseprivid.='/'.$env{'request.course.sec'};
5261: }
5262: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5263: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5264: return $2;
5265: }
1.714 raeburn 5266: }
5267: }
5268: }
5269: }
5270:
1.159 www 5271: # Free bre to public access
5272:
5273: if ($priv eq 'bre') {
1.238 www 5274: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5275: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5276: return 'F';
5277: }
1.238 www 5278: if ($copyright eq 'priv') {
5279: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5280: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5281: return '';
5282: }
5283: }
5284: if ($copyright eq 'domain') {
5285: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5286: unless (($env{'user.domain'} eq $1) ||
5287: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5288: return '';
5289: }
1.262 matthew 5290: }
1.620 albertel 5291: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5292: # Library role, so allow browsing of resources in this domain.
5293: return 'F';
1.238 www 5294: }
1.341 www 5295: if ($copyright eq 'custom') {
5296: unless (&customaccess($priv,$uri)) { return ''; }
5297: }
1.14 www 5298: }
1.264 matthew 5299: # Domain coordinator is trying to create a course
1.620 albertel 5300: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5301: # uri is the requested domain in this case.
5302: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5303: # a role of dc for the domain in question.
1.620 albertel 5304: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5305: }
1.29 www 5306:
1.52 www 5307: my $thisallowed='';
5308: my $statecond=0;
5309: my $courseprivid='';
5310:
1.1039 raeburn 5311: my $ownaccess;
1.1043 raeburn 5312: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5313: if (($priv eq 'bro') && ($env{'user.author'})) {
5314: if ($uri eq '') {
5315: $ownaccess = 1;
5316: } else {
5317: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5318: my $udom = $env{'user.domain'};
5319: my $uname = $env{'user.name'};
5320: if ($uri =~ m{^\Q$udom\E/?$}) {
5321: $ownaccess = 1;
1.1040 raeburn 5322: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5323: unless ($uri =~ m{\.\./}) {
5324: $ownaccess = 1;
5325: }
5326: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5327: my $now = time;
5328: if ($uri =~ m{^([^/]+)/?$}) {
5329: my $adom = $1;
5330: foreach my $key (keys(%env)) {
1.1042 raeburn 5331: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5332: my ($start,$end) = split('.',$env{$key});
5333: if (($now >= $start) && (!$end || $end < $now)) {
5334: $ownaccess = 1;
5335: last;
5336: }
5337: }
5338: }
5339: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5340: my $adom = $1;
5341: my $aname = $2;
1.1042 raeburn 5342: foreach my $role ('ca','aa') {
5343: if ($env{"user.role.$role./$adom/$aname"}) {
5344: my ($start,$end) =
5345: split('.',$env{"user.role.$role./$adom/$aname"});
5346: if (($now >= $start) && (!$end || $end < $now)) {
5347: $ownaccess = 1;
5348: last;
5349: }
1.1039 raeburn 5350: }
5351: }
5352: }
5353: }
5354: }
5355: }
5356: }
5357:
1.52 www 5358: # Course
5359:
1.620 albertel 5360: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5361: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5362: $thisallowed.=$1;
5363: }
1.52 www 5364: }
1.29 www 5365:
1.52 www 5366: # Domain
5367:
1.620 albertel 5368: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5369: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5370: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5371: $thisallowed.=$1;
5372: }
1.12 www 5373: }
1.52 www 5374:
5375: # Course: uri itself is a course
1.66 www 5376: my $courseuri=$uri;
5377: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5378: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5379:
1.620 albertel 5380: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5381: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5382: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5383: $thisallowed.=$1;
5384: }
1.12 www 5385: }
1.29 www 5386:
1.665 albertel 5387: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5388: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5389: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5390: $thisallowed='';
1.671 raeburn 5391: my ($match)=&is_on_map($uri);
5392: if ($match) {
5393: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5394: =~/\Q$priv\E\&([^\:]*)/) {
5395: $thisallowed.=$1;
5396: }
5397: } else {
1.705 albertel 5398: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5399: if ($refuri) {
5400: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5401: $thisallowed='F';
1.671 raeburn 5402: } else {
5403: $refuri=&declutter($refuri);
5404: my ($match) = &is_on_map($refuri);
5405: if ($match) {
5406: $thisallowed='F';
5407: }
1.669 raeburn 5408: }
1.671 raeburn 5409: }
5410: }
1.314 www 5411: }
1.492 albertel 5412:
1.766 albertel 5413: if ($priv eq 'bre'
5414: && $thisallowed ne 'F'
5415: && $thisallowed ne '2'
5416: && &is_portfolio_url($uri)) {
5417: $thisallowed = &portfolio_access($uri);
5418: }
5419:
1.52 www 5420: # Full access at system, domain or course-wide level? Exit.
1.29 www 5421: if ($thisallowed=~/F/) {
5422: return 'F';
5423: }
5424:
1.52 www 5425: # If this is generating or modifying users, exit with special codes
1.29 www 5426:
1.643 www 5427: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5428: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5429: my ($audom,$auname)=split('/',$uri);
1.643 www 5430: # no author name given, so this just checks on the general right to make a co-author in this domain
5431: unless ($auname) { return $thisallowed; }
5432: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5433: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5434: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5435: ($audom ne $env{'request.role.domain'}))) { return ''; }
5436: }
1.52 www 5437: return $thisallowed;
5438: }
5439: #
1.103 harris41 5440: # Gathered so far: system, domain and course wide privileges
1.52 www 5441: #
5442: # Course: See if uri or referer is an individual resource that is part of
5443: # the course
5444:
1.620 albertel 5445: if ($env{'request.course.id'}) {
1.232 www 5446:
1.620 albertel 5447: $courseprivid=$env{'request.course.id'};
5448: if ($env{'request.course.sec'}) {
5449: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5450: }
5451: $courseprivid=~s/\_/\//;
5452: my $checkreferer=1;
1.232 www 5453: my ($match,$cond)=&is_on_map($uri);
5454: if ($match) {
5455: $statecond=$cond;
1.620 albertel 5456: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5457: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5458: $thisallowed.=$1;
5459: $checkreferer=0;
5460: }
1.29 www 5461: }
1.83 www 5462:
1.148 www 5463: if ($checkreferer) {
1.620 albertel 5464: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5465: unless ($refuri) {
1.800 albertel 5466: foreach my $key (keys(%env)) {
5467: if ($key=~/^httpref\..*\*/) {
5468: my $pattern=$key;
1.156 www 5469: $pattern=~s/^httpref\.\/res\///;
1.148 www 5470: $pattern=~s/\*/\[\^\/\]\+/g;
5471: $pattern=~s/\//\\\//g;
1.152 www 5472: if ($orguri=~/$pattern/) {
1.800 albertel 5473: $refuri=$env{$key};
1.148 www 5474: }
5475: }
1.191 harris41 5476: }
1.148 www 5477: }
1.232 www 5478:
1.148 www 5479: if ($refuri) {
1.152 www 5480: $refuri=&declutter($refuri);
1.232 www 5481: my ($match,$cond)=&is_on_map($refuri);
5482: if ($match) {
5483: my $refstatecond=$cond;
1.620 albertel 5484: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5485: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5486: $thisallowed.=$1;
1.53 www 5487: $uri=$refuri;
5488: $statecond=$refstatecond;
1.52 www 5489: }
5490: }
1.148 www 5491: }
1.29 www 5492: }
1.52 www 5493: }
1.29 www 5494:
1.52 www 5495: #
1.103 harris41 5496: # Gathered now: all privileges that could apply, and condition number
1.52 www 5497: #
5498: #
5499: # Full or no access?
5500: #
1.29 www 5501:
1.52 www 5502: if ($thisallowed=~/F/) {
5503: return 'F';
5504: }
1.29 www 5505:
1.52 www 5506: unless ($thisallowed) {
5507: return '';
5508: }
1.29 www 5509:
1.52 www 5510: # Restrictions exist, deal with them
5511: #
5512: # C:according to course preferences
5513: # R:according to resource settings
5514: # L:unless locked
5515: # X:according to user session state
5516: #
5517:
5518: # Possibly locked functionality, check all courses
1.54 www 5519: # Locks might take effect only after 10 minutes cache expiration for other
5520: # courses, and 2 minutes for current course
1.52 www 5521:
5522: my $envkey;
5523: if ($thisallowed=~/L/) {
1.1000 raeburn 5524: foreach $envkey (keys(%env)) {
1.54 www 5525: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5526: my $courseid=$2;
5527: my $roleid=$1.'.'.$2;
1.92 www 5528: $courseid=~s/^\///;
1.54 www 5529: my $expiretime=600;
1.620 albertel 5530: if ($env{'request.role'} eq $roleid) {
1.54 www 5531: $expiretime=120;
5532: }
5533: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5534: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5535: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5536: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5537: }
1.620 albertel 5538: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5539: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5540: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5541: &log($env{'user.domain'},$env{'user.name'},
5542: $env{'user.home'},
1.57 www 5543: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5544: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5545: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5546: return '';
5547: }
5548: }
1.620 albertel 5549: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5550: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5551: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5552: &log($env{'user.domain'},$env{'user.name'},
5553: $env{'user.home'},
1.57 www 5554: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5555: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5556: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5557: return '';
5558: }
5559: }
5560: }
1.29 www 5561: }
1.52 www 5562: }
5563:
5564: #
5565: # Rest of the restrictions depend on selected course
5566: #
5567:
1.620 albertel 5568: unless ($env{'request.course.id'}) {
1.766 albertel 5569: if ($thisallowed eq 'A') {
5570: return 'A';
1.814 raeburn 5571: } elsif ($thisallowed eq 'B') {
5572: return 'B';
1.766 albertel 5573: } else {
5574: return '1';
5575: }
1.52 www 5576: }
1.29 www 5577:
1.52 www 5578: #
5579: # Now user is definitely in a course
5580: #
1.53 www 5581:
5582:
5583: # Course preferences
5584:
5585: if ($thisallowed=~/C/) {
1.620 albertel 5586: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5587: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5588: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5589: =~/\Q$rolecode\E/) {
1.689 albertel 5590: if ($priv ne 'pch') {
5591: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5592: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5593: $env{'request.course.id'});
5594: }
1.237 www 5595: return '';
5596: }
5597:
1.620 albertel 5598: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5599: =~/\Q$unamedom\E/) {
1.689 albertel 5600: if ($priv ne 'pch') {
5601: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5602: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5603: $env{'request.course.id'});
5604: }
1.54 www 5605: return '';
5606: }
1.53 www 5607: }
5608:
5609: # Resource preferences
5610:
5611: if ($thisallowed=~/R/) {
1.620 albertel 5612: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5613: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5614: if ($priv ne 'pch') {
5615: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5616: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5617: }
5618: return '';
1.54 www 5619: }
1.53 www 5620: }
1.30 www 5621:
1.246 www 5622: # Restricted by state or randomout?
1.30 www 5623:
1.52 www 5624: if ($thisallowed=~/X/) {
1.620 albertel 5625: if ($env{'acc.randomout'}) {
1.579 albertel 5626: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5627: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5628: return '';
5629: }
1.247 www 5630: }
5631: if (&condval($statecond)) {
1.52 www 5632: return '2';
5633: } else {
5634: return '';
5635: }
5636: }
1.30 www 5637:
1.766 albertel 5638: if ($thisallowed eq 'A') {
5639: return 'A';
1.814 raeburn 5640: } elsif ($thisallowed eq 'B') {
5641: return 'B';
1.766 albertel 5642: }
1.52 www 5643: return 'F';
1.232 www 5644: }
5645:
1.710 albertel 5646: sub split_uri_for_cond {
5647: my $uri=&deversion(&declutter(shift));
5648: my @uriparts=split(/\//,$uri);
5649: my $filename=pop(@uriparts);
5650: my $pathname=join('/',@uriparts);
5651: return ($pathname,$filename);
5652: }
1.232 www 5653: # --------------------------------------------------- Is a resource on the map?
5654:
5655: sub is_on_map {
1.710 albertel 5656: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5657: #Trying to find the conditional for the file
1.620 albertel 5658: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5659: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5660: if ($match) {
1.289 bowersj2 5661: return (1,$1);
5662: } else {
1.434 www 5663: return (0,0);
1.289 bowersj2 5664: }
1.12 www 5665: }
5666:
1.427 www 5667: # --------------------------------------------------------- Get symb from alias
5668:
5669: sub get_symb_from_alias {
5670: my $symb=shift;
5671: my ($map,$resid,$url)=&decode_symb($symb);
5672: # Already is a symb
5673: if ($url) { return $symb; }
5674: # Must be an alias
5675: my $aliassymb='';
5676: my %bighash;
1.620 albertel 5677: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5678: &GDBM_READER(),0640)) {
5679: my $rid=$bighash{'mapalias_'.$symb};
5680: if ($rid) {
5681: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5682: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5683: $resid,$bighash{'src_'.$rid});
1.427 www 5684: }
5685: untie %bighash;
5686: }
5687: return $aliassymb;
5688: }
5689:
1.12 www 5690: # ----------------------------------------------------------------- Define Role
5691:
5692: sub definerole {
5693: if (allowed('mcr','/')) {
5694: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5695: foreach my $role (split(':',$sysrole)) {
5696: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5697: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5698: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5699: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5700: return "refused:s:$crole&$cqual";
5701: }
5702: }
1.191 harris41 5703: }
1.800 albertel 5704: foreach my $role (split(':',$domrole)) {
5705: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5706: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5707: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5708: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5709: return "refused:d:$crole&$cqual";
5710: }
5711: }
1.191 harris41 5712: }
1.800 albertel 5713: foreach my $role (split(':',$courole)) {
5714: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5715: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5716: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5717: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5718: return "refused:c:$crole&$cqual";
5719: }
5720: }
1.191 harris41 5721: }
1.620 albertel 5722: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5723: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5724: "rolesdef_$rolename=".
5725: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5726: return reply($command,$env{'user.home'});
1.12 www 5727: } else {
5728: return 'refused';
5729: }
1.105 harris41 5730: }
5731:
5732: # ---------------- Make a metadata query against the network of library servers
5733:
5734: sub metadata_query {
1.244 matthew 5735: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5736: my %rhash;
1.845 albertel 5737: my %libserv = &all_library();
1.244 matthew 5738: my @server_list = (defined($server_array) ? @$server_array
5739: : keys(%libserv) );
5740: for my $server (@server_list) {
1.118 harris41 5741: unless ($custom or $customshow) {
5742: my $reply=&reply("querysend:".&escape($query),$server);
5743: $rhash{$server}=$reply;
5744: }
5745: else {
5746: my $reply=&reply("querysend:".&escape($query).':'.
5747: &escape($custom).':'.&escape($customshow),
5748: $server);
5749: $rhash{$server}=$reply;
5750: }
1.112 harris41 5751: }
1.118 harris41 5752: return \%rhash;
1.240 www 5753: }
5754:
5755: # ----------------------------------------- Send log queries and wait for reply
5756:
5757: sub log_query {
5758: my ($uname,$udom,$query,%filters)=@_;
5759: my $uhome=&homeserver($uname,$udom);
5760: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5761: my $uhost=&hostname($uhome);
1.800 albertel 5762: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5763: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5764: $uhome);
1.479 albertel 5765: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5766: return get_query_reply($queryid);
5767: }
5768:
1.818 raeburn 5769: # -------------------------- Update MySQL table for portfolio file
5770:
5771: sub update_portfolio_table {
1.821 raeburn 5772: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5773: if ($group ne '') {
5774: $file_name =~s /^\Q$group\E//;
5775: }
1.818 raeburn 5776: my $homeserver = &homeserver($uname,$udom);
5777: my $queryid=
1.821 raeburn 5778: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5779: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5780: my $reply = &get_query_reply($queryid);
5781: return $reply;
5782: }
5783:
1.899 raeburn 5784: # -------------------------- Update MySQL allusers table
5785:
5786: sub update_allusers_table {
5787: my ($uname,$udom,$names) = @_;
5788: my $homeserver = &homeserver($uname,$udom);
5789: my $queryid=
5790: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5791: 'lastname='.&escape($names->{'lastname'}).'%%'.
5792: 'firstname='.&escape($names->{'firstname'}).'%%'.
5793: 'middlename='.&escape($names->{'middlename'}).'%%'.
5794: 'generation='.&escape($names->{'generation'}).'%%'.
5795: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5796: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 5797: return;
1.899 raeburn 5798: }
5799:
1.508 raeburn 5800: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5801:
5802: sub fetch_enrollment_query {
1.511 raeburn 5803: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5804: my $homeserver;
1.547 raeburn 5805: my $maxtries = 1;
1.508 raeburn 5806: if ($context eq 'automated') {
5807: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5808: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5809: } else {
5810: $homeserver = &homeserver($cnum,$dom);
5811: }
1.838 albertel 5812: my $host=&hostname($homeserver);
1.506 raeburn 5813: my $cmd = '';
1.1000 raeburn 5814: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5815: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5816: }
5817: $cmd =~ s/%%$//;
5818: $cmd = &escape($cmd);
5819: my $query = 'fetchenrollment';
1.620 albertel 5820: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5821: unless ($queryid=~/^\Q$host\E\_/) {
5822: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5823: return 'error: '.$queryid;
5824: }
1.506 raeburn 5825: my $reply = &get_query_reply($queryid);
1.547 raeburn 5826: my $tries = 1;
5827: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5828: $reply = &get_query_reply($queryid);
5829: $tries ++;
5830: }
1.526 raeburn 5831: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5832: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5833: } else {
1.901 albertel 5834: my @responses = split(/:/,$reply);
1.515 raeburn 5835: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5836: foreach my $line (@responses) {
5837: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5838: $$replyref{$key} = $value;
5839: }
5840: } else {
1.506 raeburn 5841: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5842: foreach my $line (@responses) {
5843: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5844: $$replyref{$key} = $value;
5845: if ($value > 0) {
1.800 albertel 5846: foreach my $item (@{$$affiliatesref{$key}}) {
5847: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5848: my $destname = $pathname.'/'.$filename;
5849: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5850: if ($xml_classlist =~ /^error/) {
5851: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5852: } else {
1.506 raeburn 5853: if ( open(FILE,">$destname") ) {
5854: print FILE &unescape($xml_classlist);
5855: close(FILE);
1.526 raeburn 5856: } else {
5857: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5858: }
5859: }
5860: }
5861: }
5862: }
5863: }
5864: return 'ok';
5865: }
5866: return 'error';
5867: }
5868:
1.242 www 5869: sub get_query_reply {
5870: my $queryid=shift;
1.240 www 5871: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5872: my $reply='';
5873: for (1..100) {
5874: sleep 2;
5875: if (-e $replyfile.'.end') {
1.448 albertel 5876: if (open(my $fh,$replyfile)) {
1.904 albertel 5877: $reply = join('',<$fh>);
5878: close($fh);
1.240 www 5879: } else { return 'error: reply_file_error'; }
1.242 www 5880: return &unescape($reply);
5881: }
1.240 www 5882: }
1.242 www 5883: return 'timeout:'.$queryid;
1.240 www 5884: }
5885:
5886: sub courselog_query {
1.241 www 5887: #
5888: # possible filters:
5889: # url: url or symb
5890: # username
5891: # domain
5892: # action: view, submit, grade
5893: # start: timestamp
5894: # end: timestamp
5895: #
1.240 www 5896: my (%filters)=@_;
1.620 albertel 5897: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5898: if ($filters{'url'}) {
5899: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5900: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5901: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5902: }
1.620 albertel 5903: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5904: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5905: return &log_query($cname,$cdom,'courselog',%filters);
5906: }
5907:
5908: sub userlog_query {
1.858 raeburn 5909: #
5910: # possible filters:
5911: # action: log check role
5912: # start: timestamp
5913: # end: timestamp
5914: #
1.240 www 5915: my ($uname,$udom,%filters)=@_;
5916: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5917: }
5918:
1.506 raeburn 5919: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5920:
5921: sub auto_run {
1.508 raeburn 5922: my ($cnum,$cdom) = @_;
1.876 raeburn 5923: my $response = 0;
5924: my $settings;
5925: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5926: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5927: $settings = $domconfig{'autoenroll'};
5928: if ($settings->{'run'} eq '1') {
5929: $response = 1;
5930: }
5931: } else {
1.934 raeburn 5932: my $homeserver;
5933: if (&is_course($cdom,$cnum)) {
5934: $homeserver = &homeserver($cnum,$cdom);
5935: } else {
5936: $homeserver = &domain($cdom,'primary');
5937: }
5938: if ($homeserver ne 'no_host') {
5939: $response = &reply('autorun:'.$cdom,$homeserver);
5940: }
1.876 raeburn 5941: }
1.506 raeburn 5942: return $response;
5943: }
1.776 albertel 5944:
1.506 raeburn 5945: sub auto_get_sections {
1.508 raeburn 5946: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 5947: my $homeserver;
5948: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5949: $homeserver = &homeserver($cnum,$cdom);
5950: }
5951: if (!defined($homeserver)) {
5952: if ($cdom =~ /^$match_domain$/) {
5953: $homeserver = &domain($cdom,'primary');
5954: }
5955: }
5956: my @secs;
5957: if (defined($homeserver)) {
5958: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5959: unless ($response eq 'refused') {
5960: @secs = split(/:/,$response);
5961: }
1.506 raeburn 5962: }
5963: return @secs;
5964: }
1.776 albertel 5965:
1.506 raeburn 5966: sub auto_new_course {
1.508 raeburn 5967: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5968: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5969: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5970: return $response;
5971: }
1.776 albertel 5972:
1.506 raeburn 5973: sub auto_validate_courseID {
1.508 raeburn 5974: my ($cnum,$cdom,$inst_course_id) = @_;
5975: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5976: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5977: return $response;
5978: }
1.776 albertel 5979:
1.1007 raeburn 5980: sub auto_validate_instcode {
1.1020 raeburn 5981: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 5982: my ($homeserver,$response);
5983: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5984: $homeserver = &homeserver($cnum,$cdom);
5985: }
5986: if (!defined($homeserver)) {
5987: if ($cdom =~ /^$match_domain$/) {
5988: $homeserver = &domain($cdom,'primary');
5989: }
5990: }
1.1065 raeburn 5991: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
5992: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 5993: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
5994: return ($outcome,$description);
1.1007 raeburn 5995: }
5996:
1.506 raeburn 5997: sub auto_create_password {
1.873 raeburn 5998: my ($cnum,$cdom,$authparam,$udom) = @_;
5999: my ($homeserver,$response);
1.506 raeburn 6000: my $create_passwd = 0;
6001: my $authchk = '';
1.873 raeburn 6002: if ($udom =~ /^$match_domain$/) {
6003: $homeserver = &domain($udom,'primary');
6004: }
6005: if ($homeserver eq '') {
6006: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6007: $homeserver = &homeserver($cnum,$cdom);
6008: }
6009: }
6010: if ($homeserver eq '') {
6011: $authchk = 'nodomain';
1.506 raeburn 6012: } else {
1.873 raeburn 6013: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6014: if ($response eq 'refused') {
6015: $authchk = 'refused';
6016: } else {
1.901 albertel 6017: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6018: }
1.506 raeburn 6019: }
6020: return ($authparam,$create_passwd,$authchk);
6021: }
6022:
1.706 raeburn 6023: sub auto_photo_permission {
6024: my ($cnum,$cdom,$students) = @_;
6025: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6026: my ($outcome,$perm_reqd,$conditions) =
6027: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6028: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6029: return (undef,undef);
6030: }
1.706 raeburn 6031: return ($outcome,$perm_reqd,$conditions);
6032: }
6033:
6034: sub auto_checkphotos {
6035: my ($uname,$udom,$pid) = @_;
6036: my $homeserver = &homeserver($uname,$udom);
6037: my ($result,$resulttype);
6038: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6039: &escape($uname).':'.&escape($pid),
6040: $homeserver));
1.709 albertel 6041: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6042: return (undef,undef);
6043: }
1.706 raeburn 6044: if ($outcome) {
6045: ($result,$resulttype) = split(/:/,$outcome);
6046: }
6047: return ($result,$resulttype);
6048: }
6049:
6050: sub auto_photochoice {
6051: my ($cnum,$cdom) = @_;
6052: my $homeserver = &homeserver($cnum,$cdom);
6053: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6054: &escape($cdom),
6055: $homeserver)));
1.709 albertel 6056: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6057: return (undef,undef);
6058: }
1.706 raeburn 6059: return ($update,$comment);
6060: }
6061:
6062: sub auto_photoupdate {
6063: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6064: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6065: my $host=&hostname($homeserver);
1.706 raeburn 6066: my $cmd = '';
6067: my $maxtries = 1;
1.800 albertel 6068: foreach my $affiliate (keys(%{$affiliatesref})) {
6069: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6070: }
6071: $cmd =~ s/%%$//;
6072: $cmd = &escape($cmd);
6073: my $query = 'institutionalphotos';
6074: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6075: unless ($queryid=~/^\Q$host\E\_/) {
6076: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6077: return 'error: '.$queryid;
6078: }
6079: my $reply = &get_query_reply($queryid);
6080: my $tries = 1;
6081: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6082: $reply = &get_query_reply($queryid);
6083: $tries ++;
6084: }
6085: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6086: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6087: } else {
6088: my @responses = split(/:/,$reply);
6089: my $outcome = shift(@responses);
6090: foreach my $item (@responses) {
6091: my ($key,$value) = split(/=/,$item);
6092: $$photo{$key} = $value;
6093: }
6094: return $outcome;
6095: }
6096: return 'error';
6097: }
6098:
1.521 raeburn 6099: sub auto_instcode_format {
1.793 albertel 6100: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6101: $cat_order) = @_;
1.521 raeburn 6102: my $courses = '';
1.772 raeburn 6103: my @homeservers;
1.521 raeburn 6104: if ($caller eq 'global') {
1.841 albertel 6105: my %servers = &get_servers($codedom,'library');
6106: foreach my $tryserver (keys(%servers)) {
6107: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6108: push(@homeservers,$tryserver);
6109: }
1.584 raeburn 6110: }
1.1022 raeburn 6111: } elsif ($caller eq 'requests') {
6112: if ($codedom =~ /^$match_domain$/) {
6113: my $chome = &domain($codedom,'primary');
6114: unless ($chome eq 'no_host') {
6115: push(@homeservers,$chome);
6116: }
6117: }
1.521 raeburn 6118: } else {
1.772 raeburn 6119: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6120: }
1.793 albertel 6121: foreach my $code (keys(%{$instcodes})) {
6122: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6123: }
6124: chop($courses);
1.772 raeburn 6125: my $ok_response = 0;
6126: my $response;
6127: while (@homeservers > 0 && $ok_response == 0) {
6128: my $server = shift(@homeservers);
6129: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6130: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6131: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6132: split(/:/,$response);
1.772 raeburn 6133: %{$codes} = (%{$codes},&str2hash($codes_str));
6134: push(@{$codetitles},&str2array($codetitles_str));
6135: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6136: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6137: $ok_response = 1;
6138: }
6139: }
6140: if ($ok_response) {
1.521 raeburn 6141: return 'ok';
1.772 raeburn 6142: } else {
6143: return $response;
1.521 raeburn 6144: }
6145: }
6146:
1.792 raeburn 6147: sub auto_instcode_defaults {
6148: my ($domain,$returnhash,$code_order) = @_;
6149: my @homeservers;
1.841 albertel 6150:
6151: my %servers = &get_servers($domain,'library');
6152: foreach my $tryserver (keys(%servers)) {
6153: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6154: push(@homeservers,$tryserver);
6155: }
1.792 raeburn 6156: }
1.841 albertel 6157:
1.792 raeburn 6158: my $response;
1.841 albertel 6159: foreach my $server (@homeservers) {
1.792 raeburn 6160: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6161: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6162:
6163: foreach my $pair (split(/\&/,$response)) {
6164: my ($name,$value)=split(/\=/,$pair);
6165: if ($name eq 'code_order') {
6166: @{$code_order} = split(/\&/,&unescape($value));
6167: } else {
6168: $returnhash->{&unescape($name)}=&unescape($value);
6169: }
6170: }
6171: return 'ok';
1.792 raeburn 6172: }
1.841 albertel 6173:
6174: return $response;
1.1003 raeburn 6175: }
6176:
6177: sub auto_possible_instcodes {
1.1007 raeburn 6178: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6179: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6180: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6181: return;
6182: }
1.1003 raeburn 6183: my (@homeservers,$uhome);
6184: if (defined(&domain($domain,'primary'))) {
6185: $uhome=&domain($domain,'primary');
6186: push(@homeservers,&domain($domain,'primary'));
6187: } else {
6188: my %servers = &get_servers($domain,'library');
6189: foreach my $tryserver (keys(%servers)) {
6190: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6191: push(@homeservers,$tryserver);
6192: }
6193: }
6194: }
6195: my $response;
6196: foreach my $server (@homeservers) {
6197: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6198: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6199: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6200: split(':',$response);
6201: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6202: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6203: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6204: my ($name,$value)=split('=',$item);
6205: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6206: }
6207: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6208: my ($name,$value)=split('=',$item);
6209: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6210: }
6211: return 'ok';
6212: }
6213: return $response;
6214: }
1.792 raeburn 6215:
1.1010 raeburn 6216: sub auto_courserequest_checks {
6217: my ($dom) = @_;
1.1020 raeburn 6218: my ($homeserver,%validations);
6219: if ($dom =~ /^$match_domain$/) {
6220: $homeserver = &domain($dom,'primary');
6221: }
6222: unless ($homeserver eq 'no_host') {
6223: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6224: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6225: my @items = split(/&/,$response);
6226: foreach my $item (@items) {
6227: my ($key,$value) = split('=',$item);
6228: $validations{&unescape($key)} = &thaw_unescape($value);
6229: }
6230: }
6231: }
1.1010 raeburn 6232: return %validations;
6233: }
6234:
1.1020 raeburn 6235: sub auto_courserequest_validation {
6236: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6237: my ($homeserver,$response);
6238: if ($dom =~ /^$match_domain$/) {
6239: $homeserver = &domain($dom,'primary');
6240: }
6241: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6242:
1.1020 raeburn 6243: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6244: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6245: ':'.&escape($instcode).':'.&escape($instseclist),
6246: $homeserver));
6247: }
6248: return $response;
6249: }
6250:
1.777 albertel 6251: sub auto_validate_class_sec {
1.918 raeburn 6252: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6253: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6254: my $ownerlist;
6255: if (ref($owners) eq 'ARRAY') {
6256: $ownerlist = join(',',@{$owners});
6257: } else {
6258: $ownerlist = $owners;
6259: }
1.773 raeburn 6260: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6261: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6262: return $response;
6263: }
6264:
1.679 raeburn 6265: # ------------------------------------------------------- Course Group routines
6266:
6267: sub get_coursegroups {
1.809 raeburn 6268: my ($cdom,$cnum,$group,$namespace) = @_;
6269: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6270: }
6271:
1.679 raeburn 6272: sub modify_coursegroup {
6273: my ($cdom,$cnum,$groupsettings) = @_;
6274: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6275: }
6276:
1.809 raeburn 6277: sub toggle_coursegroup_status {
6278: my ($cdom,$cnum,$group,$action) = @_;
6279: my ($from_namespace,$to_namespace);
6280: if ($action eq 'delete') {
6281: $from_namespace = 'coursegroups';
6282: $to_namespace = 'deleted_groups';
6283: } else {
6284: $from_namespace = 'deleted_groups';
6285: $to_namespace = 'coursegroups';
6286: }
6287: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6288: if (my $tmp = &error(%curr_group)) {
6289: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6290: return ('read error',$tmp);
6291: } else {
6292: my %savedsettings = %curr_group;
1.809 raeburn 6293: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6294: my $deloutcome;
6295: if ($result eq 'ok') {
1.809 raeburn 6296: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6297: } else {
6298: return ('write error',$result);
6299: }
6300: if ($deloutcome eq 'ok') {
6301: return 'ok';
6302: } else {
6303: return ('delete error',$deloutcome);
6304: }
6305: }
6306: }
6307:
1.679 raeburn 6308: sub modify_group_roles {
1.957 raeburn 6309: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6310: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6311: my $role = 'gr/'.&escape($userprivs);
6312: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6313: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6314: if ($result eq 'ok') {
6315: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6316: }
1.679 raeburn 6317: return $result;
6318: }
6319:
6320: sub modify_coursegroup_membership {
6321: my ($cdom,$cnum,$membership) = @_;
6322: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6323: return $result;
6324: }
6325:
1.682 raeburn 6326: sub get_active_groups {
6327: my ($udom,$uname,$cdom,$cnum) = @_;
6328: my $now = time;
6329: my %groups = ();
6330: foreach my $key (keys(%env)) {
1.811 albertel 6331: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6332: my ($start,$end) = split(/\./,$env{$key});
6333: if (($end!=0) && ($end<$now)) { next; }
6334: if (($start!=0) && ($start>$now)) { next; }
6335: if ($1 eq $cdom && $2 eq $cnum) {
6336: $groups{$3} = $env{$key} ;
6337: }
6338: }
6339: }
6340: return %groups;
6341: }
6342:
1.683 raeburn 6343: sub get_group_membership {
6344: my ($cdom,$cnum,$group) = @_;
6345: return(&dump('groupmembership',$cdom,$cnum,$group));
6346: }
6347:
6348: sub get_users_groups {
6349: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6350: my @usersgroups;
1.683 raeburn 6351: my $cachetime=1800;
6352:
6353: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6354: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6355: if (defined($cached)) {
1.734 albertel 6356: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6357: } else {
6358: $grouplist = '';
1.816 raeburn 6359: my $courseurl = &courseid_to_courseurl($courseid);
1.1086 ! raeburn 6360: my $extra = &freeze_escape({'skipcheck' => 1});
! 6361: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6362: my $access_end = $env{'course.'.$courseid.
6363: '.default_enrollment_end_date'};
6364: my $now = time;
6365: foreach my $key (keys(%roleshash)) {
6366: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6367: my $group = $1;
6368: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6369: my $start = $2;
6370: my $end = $1;
6371: if ($start == -1) { next; } # deleted from group
6372: if (($start!=0) && ($start>$now)) { next; }
6373: if (($end!=0) && ($end<$now)) {
6374: if ($access_end && $access_end < $now) {
6375: if ($access_end - $end < 86400) {
6376: push(@usersgroups,$group);
1.733 raeburn 6377: }
6378: }
1.817 raeburn 6379: next;
1.733 raeburn 6380: }
1.817 raeburn 6381: push(@usersgroups,$group);
1.683 raeburn 6382: }
6383: }
6384: }
1.817 raeburn 6385: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6386: $grouplist = join(':',@usersgroups);
6387: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6388: }
1.733 raeburn 6389: return @usersgroups;
1.683 raeburn 6390: }
6391:
6392: sub devalidate_getgroups_cache {
6393: my ($udom,$uname,$cdom,$cnum)=@_;
6394: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6395:
1.683 raeburn 6396: my $hashid="$udom:$uname:$courseid";
6397: &devalidate_cache_new('getgroups',$hashid);
6398: }
6399:
1.12 www 6400: # ------------------------------------------------------------------ Plain Text
6401:
6402: sub plaintext {
1.988 raeburn 6403: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6404: if ($short =~ m{^cr/}) {
1.758 albertel 6405: return (split('/',$short))[-1];
6406: }
1.742 raeburn 6407: if (!defined($cid)) {
6408: $cid = $env{'request.course.id'};
6409: }
6410: my %rolenames = (
1.1008 raeburn 6411: Course => 'std',
6412: Community => 'alt1',
1.742 raeburn 6413: );
1.1037 raeburn 6414: if ($cid ne '') {
6415: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6416: unless ($forcedefault) {
6417: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6418: &Apache::lonlocal::mt_escape(\$roletext);
6419: return &Apache::lonlocal::mt($roletext);
6420: }
6421: }
6422: }
6423: if ((defined($type)) && (defined($rolenames{$type})) &&
6424: (defined($rolenames{$type})) &&
6425: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6426: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6427: } elsif ($cid ne '') {
6428: my $crstype = $env{'course.'.$cid.'.type'};
6429: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6430: (defined($prp{$short}{$rolenames{$crstype}}))) {
6431: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6432: }
1.742 raeburn 6433: }
1.1037 raeburn 6434: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6435: }
6436:
6437: # ----------------------------------------------------------------- Assign Role
6438:
6439: sub assignrole {
1.957 raeburn 6440: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6441: $context)=@_;
1.21 www 6442: my $mrole;
6443: if ($role =~ /^cr\//) {
1.393 www 6444: my $cwosec=$url;
1.811 albertel 6445: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6446: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6447: my $refused = 1;
6448: if ($context eq 'requestcourses') {
6449: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6450: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6451: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6452: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6453: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6454: if ($crsenv{'internal.courseowner'} eq
6455: $env{'user.name'}.':'.$env{'user.domain'}) {
6456: $refused = '';
6457: }
6458: }
6459: }
6460: }
6461: }
6462: if ($refused) {
6463: &logthis('Refused custom assignrole: '.
6464: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6465: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6466: return 'refused';
6467: }
1.104 www 6468: }
1.21 www 6469: $mrole='cr';
1.678 raeburn 6470: } elsif ($role =~ /^gr\//) {
6471: my $cwogrp=$url;
1.811 albertel 6472: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6473: unless (&allowed('mdg',$cwogrp)) {
6474: &logthis('Refused group assignrole: '.
6475: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6476: $env{'user.name'}.' at '.$env{'user.domain'});
6477: return 'refused';
6478: }
6479: $mrole='gr';
1.21 www 6480: } else {
1.82 www 6481: my $cwosec=$url;
1.811 albertel 6482: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6483: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6484: my $refused;
6485: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6486: if (!(&allowed('c'.$role,$url))) {
6487: $refused = 1;
6488: }
6489: } else {
6490: $refused = 1;
6491: }
1.947 raeburn 6492: if ($refused) {
1.1045 raeburn 6493: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6494: if (!$selfenroll && $context eq 'course') {
6495: my %crsenv;
6496: if ($role eq 'cc' || $role eq 'co') {
6497: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6498: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6499: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6500: if ($crsenv{'internal.courseowner'} eq
6501: $env{'user.name'}.':'.$env{'user.domain'}) {
6502: $refused = '';
6503: }
6504: }
6505: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6506: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6507: if ($crsenv{'internal.courseowner'} eq
6508: $env{'user.name'}.':'.$env{'user.domain'}) {
6509: $refused = '';
6510: }
6511: }
6512: }
6513: }
6514: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6515: $refused = '';
1.1017 raeburn 6516: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6517: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6518: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6519: my $wrongcc;
6520: if ($cnum =~ /^$match_community$/) {
6521: $wrongcc = 1 if ($role eq 'cc');
6522: } else {
6523: $wrongcc = 1 if ($role eq 'co');
6524: }
6525: unless ($wrongcc) {
6526: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6527: if ($crsenv{'internal.courseowner'} eq
6528: $env{'user.name'}.':'.$env{'user.domain'}) {
6529: $refused = '';
6530: }
1.1017 raeburn 6531: }
6532: }
6533: }
6534: if ($refused) {
1.947 raeburn 6535: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6536: ' '.$role.' '.$end.' '.$start.' by '.
6537: $env{'user.name'}.' at '.$env{'user.domain'});
6538: return 'refused';
6539: }
1.932 raeburn 6540: }
1.104 www 6541: }
1.21 www 6542: $mrole=$role;
6543: }
1.620 albertel 6544: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6545: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6546: if ($end) { $command.='_'.$end; }
1.21 www 6547: if ($start) {
6548: if ($end) {
1.81 www 6549: $command.='_'.$start;
1.21 www 6550: } else {
1.81 www 6551: $command.='_0_'.$start;
1.21 www 6552: }
6553: }
1.739 raeburn 6554: my $origstart = $start;
6555: my $origend = $end;
1.957 raeburn 6556: my $delflag;
1.357 www 6557: # actually delete
6558: if ($deleteflag) {
1.373 www 6559: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6560: # modify command to delete the role
1.620 albertel 6561: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6562: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6563: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6564: # set start and finish to negative values for userrolelog
6565: $start=-1;
6566: $end=-1;
1.957 raeburn 6567: $delflag = 1;
1.357 www 6568: }
6569: }
6570: # send command
1.349 www 6571: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6572: # log new user role if status is ok
1.349 www 6573: if ($answer eq 'ok') {
1.663 raeburn 6574: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6575: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6576: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6577: unless ($role =~ /^gr/) {
6578: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6579: $origstart,$selfenroll,$context);
1.739 raeburn 6580: }
1.1053 raeburn 6581: if ($role eq 'cc') {
6582: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6583: }
1.349 www 6584: }
6585: return $answer;
1.169 harris41 6586: }
6587:
1.1053 raeburn 6588: sub autoupdate_coowners {
6589: my ($url,$end,$start,$uname,$udom) = @_;
6590: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6591: if (($cdom ne '') && ($cnum ne '')) {
6592: my $now = time;
6593: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6594: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6595: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6596: my $instcode = $coursehash{'internal.coursecode'};
6597: if ($instcode ne '') {
1.1056 raeburn 6598: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6599: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6600: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6601: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6602: if ($result eq 'valid') {
6603: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6604: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6605: push(@newcoowners,$coowner);
6606: }
6607: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6608: push(@newcoowners,$uname.':'.$udom);
6609: }
6610: @newcoowners = sort(@newcoowners);
6611: } else {
6612: push(@newcoowners,$uname.':'.$udom);
6613: }
6614: } else {
6615: if ($coursehash{'internal.co-owners'}) {
6616: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6617: unless ($coowner eq $uname.':'.$udom) {
6618: push(@newcoowners,$coowner);
6619: }
6620: }
6621: unless (@newcoowners > 0) {
6622: $delcoowners = 1;
6623: $coowners = '';
6624: }
6625: }
6626: }
6627: if (@newcoowners || $delcoowners) {
6628: &store_coowners($cdom,$cnum,$coursehash{'home'},
6629: $delcoowners,@newcoowners);
6630: }
6631: }
6632: }
6633: }
6634: }
6635: }
6636: }
6637:
6638: sub store_coowners {
6639: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6640: my $cid = $cdom.'_'.$cnum;
6641: my ($coowners,$delresult,$putresult);
6642: if (@newcoowners) {
6643: $coowners = join(',',@newcoowners);
6644: my %coownershash = (
6645: 'internal.co-owners' => $coowners,
6646: );
6647: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6648: if ($putresult eq 'ok') {
6649: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6650: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6651: }
6652: }
6653: }
6654: if ($delcoowners) {
6655: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6656: if ($delresult eq 'ok') {
6657: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6658: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6659: }
6660: }
6661: }
6662: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6663: my %crsinfo =
6664: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6665: if (ref($crsinfo{$cid}) eq 'HASH') {
6666: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6667: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6668: }
6669: }
6670: }
6671:
1.169 harris41 6672: # -------------------------------------------------- Modify user authentication
1.197 www 6673: # Overrides without validation
6674:
1.169 harris41 6675: sub modifyuserauth {
6676: my ($udom,$uname,$umode,$upass)=@_;
6677: my $uhome=&homeserver($uname,$udom);
1.197 www 6678: unless (&allowed('mau',$udom)) { return 'refused'; }
6679: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6680: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6681: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6682: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6683: &escape($upass),$uhome);
1.620 albertel 6684: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6685: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6686: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6687: &log($udom,,$uname,$uhome,
1.620 albertel 6688: 'Authentication changed by '.$env{'user.domain'}.', '.
6689: $env{'user.name'}.', '.$umode.
1.197 www 6690: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6691: unless ($reply eq 'ok') {
1.197 www 6692: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6693: return 'error: '.$reply;
6694: }
1.170 harris41 6695: return 'ok';
1.80 www 6696: }
6697:
1.81 www 6698: # --------------------------------------------------------------- Modify a user
1.80 www 6699:
1.81 www 6700: sub modifyuser {
1.206 matthew 6701: my ($udom, $uname, $uid,
6702: $umode, $upass, $first,
6703: $middle, $last, $gene,
1.1058 raeburn 6704: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6705: $udom= &LONCAPA::clean_domain($udom);
6706: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 6707: my $showcandelete = 'none';
6708: if (ref($candelete) eq 'ARRAY') {
6709: if (@{$candelete} > 0) {
6710: $showcandelete = join(', ',@{$candelete});
6711: }
6712: }
1.81 www 6713: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6714: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 6715: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6716: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6717: ' desiredhome not specified').
1.620 albertel 6718: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6719: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6720: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 6721: my $newuser;
6722: if ($uhome eq 'no_host') {
6723: $newuser = 1;
6724: }
1.80 www 6725: # ----------------------------------------------------------------- Create User
1.406 albertel 6726: if (($uhome eq 'no_host') &&
6727: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6728: my $unhome='';
1.844 albertel 6729: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6730: $unhome = $desiredhome;
1.620 albertel 6731: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6732: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6733: } else { # load balancing routine for determining $unhome
1.81 www 6734: my $loadm=10000000;
1.841 albertel 6735: my %servers = &get_servers($udom,'library');
6736: foreach my $tryserver (keys(%servers)) {
6737: my $answer=reply('load',$tryserver);
6738: if (($answer=~/\d+/) && ($answer<$loadm)) {
6739: $loadm=$answer;
6740: $unhome=$tryserver;
6741: }
1.80 www 6742: }
6743: }
6744: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6745: return 'error: unable to find a home server for '.$uname.
6746: ' in domain '.$udom;
1.80 www 6747: }
6748: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6749: &escape($upass),$unhome);
6750: unless ($reply eq 'ok') {
6751: return 'error: '.$reply;
6752: }
1.230 stredwic 6753: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6754: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6755: return 'error: unable verify users home machine.';
1.80 www 6756: }
1.209 matthew 6757: } # End of creation of new user
1.80 www 6758: # ---------------------------------------------------------------------- Add ID
6759: if ($uid) {
6760: $uid=~tr/A-Z/a-z/;
6761: my %uidhash=&idrget($udom,$uname);
1.196 www 6762: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6763: && (!$forceid)) {
1.80 www 6764: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6765: return 'error: user id "'.$uid.'" does not match '.
6766: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6767: }
6768: } else {
6769: &idput($udom,($uname => $uid));
6770: }
6771: }
6772: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6773: my @tmp=&get('environment',
1.899 raeburn 6774: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6775: 'permanentemail','inststatus'],
1.134 albertel 6776: $udom,$uname);
1.1075 raeburn 6777: my (%names,%oldnames);
1.313 matthew 6778: if ($tmp[0] =~ m/^error:.*/) {
6779: %names=();
6780: } else {
6781: %names = @tmp;
1.1075 raeburn 6782: %oldnames = %names;
1.313 matthew 6783: }
1.388 www 6784: #
1.1058 raeburn 6785: # If name, email and/or uid are blank (e.g., because an uploaded file
6786: # of users did not contain them), do not overwrite existing values
6787: # unless field is in $candelete array ref.
6788: #
6789:
6790: my @fields = ('firstname','middlename','lastname','generation',
6791: 'permanentemail','id');
6792: my %newvalues;
6793: if (ref($candelete) eq 'ARRAY') {
6794: foreach my $field (@fields) {
6795: if (grep(/^\Q$field\E$/,@{$candelete})) {
6796: if ($field eq 'firstname') {
6797: $names{$field} = $first;
6798: } elsif ($field eq 'middlename') {
6799: $names{$field} = $middle;
6800: } elsif ($field eq 'lastname') {
6801: $names{$field} = $last;
6802: } elsif ($field eq 'generation') {
6803: $names{$field} = $gene;
6804: } elsif ($field eq 'permanentemail') {
6805: $names{$field} = $email;
6806: } elsif ($field eq 'id') {
6807: $names{$field} = $uid;
6808: }
6809: }
6810: }
6811: }
1.388 www 6812: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6813: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6814: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6815: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6816: if ($email) {
6817: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6818: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6819: }
1.899 raeburn 6820: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6821: if (defined($inststatus)) {
6822: $names{'inststatus'} = '';
6823: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6824: if (ref($usertypes) eq 'HASH') {
6825: my @okstatuses;
6826: foreach my $item (split(/:/,$inststatus)) {
6827: if (defined($usertypes->{$item})) {
6828: push(@okstatuses,$item);
6829: }
6830: }
6831: if (@okstatuses) {
6832: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6833: }
6834: }
6835: }
1.1075 raeburn 6836: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 6837: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 6838: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 6839: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6840: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6841: } else {
6842: $logmsg .= ' during self creation';
6843: }
1.1075 raeburn 6844: my $changed;
6845: if ($newuser) {
6846: $changed = 1;
6847: } else {
6848: foreach my $field (@fields) {
6849: if ($names{$field} ne $oldnames{$field}) {
6850: $changed = 1;
6851: last;
6852: }
6853: }
6854: }
6855: unless ($changed) {
6856: $logmsg = 'No changes in user information needed for: '.$logmsg;
6857: &logthis($logmsg);
6858: return 'ok';
6859: }
6860: my $reply = &put('environment', \%names, $udom,$uname);
6861: if ($reply ne 'ok') {
6862: return 'error: '.$reply;
6863: }
6864: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
6865: &devalidate_cache_new('namescache',$uname.':'.$udom);
6866: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 6867: &logthis($logmsg);
1.134 albertel 6868: return 'ok';
1.80 www 6869: }
6870:
1.81 www 6871: # -------------------------------------------------------------- Modify student
1.80 www 6872:
1.81 www 6873: sub modifystudent {
6874: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6875: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6876: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6877: if (!$cid) {
1.620 albertel 6878: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6879: return 'not_in_class';
6880: }
1.80 www 6881: }
6882: # --------------------------------------------------------------- Make the user
1.81 www 6883: my $reply=&modifyuser
1.209 matthew 6884: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6885: $desiredhome,$email,$inststatus);
1.80 www 6886: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6887: # This will cause &modify_student_enrollment to get the uid from the
6888: # students environment
6889: $uid = undef if (!$forceid);
1.455 albertel 6890: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 6891: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 6892: return $reply;
6893: }
6894:
6895: sub modify_student_enrollment {
1.957 raeburn 6896: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 6897: my ($cdom,$cnum,$chome);
6898: if (!$cid) {
1.620 albertel 6899: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6900: return 'not_in_class';
6901: }
1.620 albertel 6902: $cdom=$env{'course.'.$cid.'.domain'};
6903: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 6904: } else {
6905: ($cdom,$cnum)=split(/_/,$cid);
6906: }
1.620 albertel 6907: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 6908: if (!$chome) {
1.457 raeburn 6909: $chome=&homeserver($cnum,$cdom);
1.297 matthew 6910: }
1.455 albertel 6911: if (!$chome) { return 'unknown_course'; }
1.297 matthew 6912: # Make sure the user exists
1.81 www 6913: my $uhome=&homeserver($uname,$udom);
6914: if (($uhome eq '') || ($uhome eq 'no_host')) {
6915: return 'error: no such user';
6916: }
1.297 matthew 6917: # Get student data if we were not given enough information
6918: if (!defined($first) || $first eq '' ||
6919: !defined($last) || $last eq '' ||
6920: !defined($uid) || $uid eq '' ||
6921: !defined($middle) || $middle eq '' ||
6922: !defined($gene) || $gene eq '') {
1.294 matthew 6923: # They did not supply us with enough data to enroll the student, so
6924: # we need to pick up more information.
1.297 matthew 6925: my %tmp = &get('environment',
1.294 matthew 6926: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 6927: ,$udom,$uname);
6928:
1.800 albertel 6929: #foreach my $key (keys(%tmp)) {
6930: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 6931: #}
1.294 matthew 6932: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6933: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6934: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 6935: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 6936: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6937: }
1.556 albertel 6938: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 6939: my $reply=cput('classlist',
6940: {"$uname:$udom" =>
1.515 raeburn 6941: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 6942: $cdom,$cnum);
1.81 www 6943: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6944: return 'error: '.$reply;
1.652 albertel 6945: } else {
6946: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 6947: }
1.297 matthew 6948: # Add student role to user
1.83 www 6949: my $uurl='/'.$cid;
1.81 www 6950: $uurl=~s/\_/\//g;
6951: if ($usec) {
6952: $uurl.='/'.$usec;
6953: }
1.957 raeburn 6954: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 6955: }
6956:
1.556 albertel 6957: sub format_name {
6958: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6959: my $name;
6960: if ($first ne 'lastname') {
6961: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6962: } else {
6963: if ($lastname=~/\S/) {
6964: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6965: $name=~s/\s+,/,/;
6966: } else {
6967: $name.= $firstname.' '.$middlename.' '.$generation;
6968: }
6969: }
6970: $name=~s/^\s+//;
6971: $name=~s/\s+$//;
6972: $name=~s/\s+/ /g;
6973: return $name;
6974: }
6975:
1.84 www 6976: # ------------------------------------------------- Write to course preferences
6977:
6978: sub writecoursepref {
6979: my ($courseid,%prefs)=@_;
6980: $courseid=~s/^\///;
6981: $courseid=~s/\_/\//g;
6982: my ($cdomain,$cnum)=split(/\//,$courseid);
6983: my $chome=homeserver($cnum,$cdomain);
6984: if (($chome eq '') || ($chome eq 'no_host')) {
6985: return 'error: no such course';
6986: }
6987: my $cstring='';
1.800 albertel 6988: foreach my $pref (keys(%prefs)) {
6989: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 6990: }
1.84 www 6991: $cstring=~s/\&$//;
6992: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6993: }
6994:
6995: # ---------------------------------------------------------- Make/modify course
6996:
6997: sub createcourse {
1.741 raeburn 6998: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 6999: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7000: $url=&declutter($url);
7001: my $cid='';
1.1028 raeburn 7002: if ($context eq 'requestcourses') {
7003: my $can_create = 0;
7004: my ($ownername,$ownerdom) = split(':',$course_owner);
7005: if ($udom eq $ownerdom) {
7006: if (&usertools_access($ownername,$ownerdom,$category,undef,
7007: $context)) {
7008: $can_create = 1;
7009: }
7010: } else {
7011: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7012: $category);
7013: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7014: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7015: if (@curr > 0) {
7016: my @options = qw(approval validate autolimit);
7017: my $optregex = join('|',@options);
7018: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7019: $can_create = 1;
7020: }
7021: }
7022: }
7023: }
7024: if ($can_create) {
7025: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7026: unless (&allowed('ccc',$udom)) {
7027: return 'refused';
7028: }
1.1017 raeburn 7029: }
7030: } else {
7031: return 'refused';
7032: }
1.1028 raeburn 7033: } elsif (!&allowed('ccc',$udom)) {
7034: return 'refused';
1.84 www 7035: }
1.1011 raeburn 7036: # --------------------------------------------------------------- Get Unique ID
7037: my $uname;
7038: if ($cnum =~ /^$match_courseid$/) {
7039: my $chome=&homeserver($cnum,$udom,'true');
7040: if (($chome eq '') || ($chome eq 'no_host')) {
7041: $uname = $cnum;
7042: } else {
1.1038 raeburn 7043: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7044: }
7045: } else {
1.1038 raeburn 7046: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7047: }
7048: return $uname if ($uname =~ /^error/);
7049: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7050: if (!defined($course_server)) {
7051: if (defined(&domain($udom,'primary'))) {
7052: $course_server = &domain($udom,'primary');
7053: } else {
7054: $course_server = $env{'user.home'};
7055: }
7056: }
7057: my %host_servers =
7058: &Apache::lonnet::get_servers($udom,'library');
7059: unless ($host_servers{$course_server}) {
7060: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7061: }
1.84 www 7062: # ------------------------------------------------------------- Make the course
7063: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7064: $course_server);
1.84 www 7065: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7066: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7067: if (($uhome eq '') || ($uhome eq 'no_host')) {
7068: return 'error: no such course';
7069: }
1.271 www 7070: # ----------------------------------------------------------------- Course made
1.516 raeburn 7071: # log existence
1.1029 raeburn 7072: my $now = time;
1.918 raeburn 7073: my $newcourse = {
7074: $udom.'_'.$uname => {
1.921 raeburn 7075: description => $description,
7076: inst_code => $inst_code,
7077: owner => $course_owner,
7078: type => $crstype,
1.1029 raeburn 7079: creator => $env{'user.name'}.':'.
7080: $env{'user.domain'},
7081: created => $now,
7082: context => $context,
1.918 raeburn 7083: },
7084: };
1.921 raeburn 7085: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7086: # set toplevel url
1.271 www 7087: my $topurl=$url;
7088: unless ($nonstandard) {
7089: # ------------------------------------------ For standard courses, make top url
7090: my $mapurl=&clutter($url);
1.278 www 7091: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7092: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7093: <map>
7094: <resource id="1" type="start"></resource>
7095: <resource id="2" src="$mapurl"></resource>
7096: <resource id="3" type="finish"></resource>
7097: <link index="1" from="1" to="2"></link>
7098: <link index="2" from="2" to="3"></link>
7099: </map>
7100: ENDINITMAP
7101: $topurl=&declutter(
1.638 albertel 7102: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7103: );
7104: }
7105: # ----------------------------------------------------------- Write preferences
1.84 www 7106: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7107: ('description' => $description,
7108: 'url' => $topurl,
7109: 'internal.creator' => $env{'user.name'}.':'.
7110: $env{'user.domain'},
7111: 'internal.created' => $now,
7112: 'internal.creationcontext' => $context)
7113: );
1.84 www 7114: return '/'.$udom.'/'.$uname;
7115: }
7116:
1.1011 raeburn 7117: # ------------------------------------------------------------------- Create ID
7118: sub generate_coursenum {
1.1038 raeburn 7119: my ($udom,$crstype) = @_;
1.1011 raeburn 7120: my $domdesc = &domain($udom);
7121: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7122: my $first;
7123: if ($crstype eq 'Community') {
7124: $first = '0';
7125: } else {
7126: $first = int(1+rand(9));
7127: }
7128: my $uname=$first.
1.1011 raeburn 7129: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7130: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7131: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7132: # ----------------------------------------------- Make sure that does not exist
7133: my $uhome=&homeserver($uname,$udom,'true');
7134: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7135: if ($crstype eq 'Community') {
7136: $first = '0';
7137: } else {
7138: $first = int(1+rand(9));
7139: }
7140: $uname=$first.
1.1011 raeburn 7141: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7142: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7143: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7144: $uhome=&homeserver($uname,$udom,'true');
7145: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7146: return 'error: unable to generate unique course-ID';
7147: }
7148: }
7149: return $uname;
7150: }
7151:
1.813 albertel 7152: sub is_course {
7153: my ($cdom,$cnum) = @_;
7154: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7155: undef,'.');
1.813 albertel 7156: if (exists($courses{$cdom.'_'.$cnum})) {
7157: return 1;
7158: }
7159: return 0;
7160: }
7161:
1.1015 raeburn 7162: sub store_userdata {
7163: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7164: my $result;
1.1016 raeburn 7165: if ($datakey ne '') {
1.1013 raeburn 7166: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7167: if ($udom eq '' || $uname eq '') {
7168: $udom = $env{'user.domain'};
7169: $uname = $env{'user.name'};
7170: }
7171: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7172: if (($uhome eq '') || ($uhome eq 'no_host')) {
7173: $result = 'error: no_host';
7174: } else {
7175: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7176: $storehash->{'host'} = $perlvar{'lonHostID'};
7177:
7178: my $namevalue='';
7179: foreach my $key (keys(%{$storehash})) {
7180: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7181: }
7182: $namevalue=~s/\&$//;
7183: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 raeburn 7184: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 7185: }
7186: } else {
7187: $result = 'error: data to store was not a hash reference';
7188: }
7189: } else {
7190: $result= 'error: invalid requestkey';
7191: }
7192: return $result;
7193: }
7194:
1.21 www 7195: # ---------------------------------------------------------- Assign Custom Role
7196:
7197: sub assigncustomrole {
1.957 raeburn 7198: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7199: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7200: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7201: }
7202:
7203: # ----------------------------------------------------------------- Revoke Role
7204:
7205: sub revokerole {
1.957 raeburn 7206: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7207: my $now=time;
1.965 raeburn 7208: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7209: }
7210:
7211: # ---------------------------------------------------------- Revoke Custom Role
7212:
7213: sub revokecustomrole {
1.957 raeburn 7214: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7215: my $now=time;
1.357 www 7216: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7217: $deleteflag,$selfenroll,$context);
1.17 www 7218: }
7219:
1.533 banghart 7220: # ------------------------------------------------------------ Disk usage
1.535 albertel 7221: sub diskusage {
1.955 raeburn 7222: my ($udom,$uname,$directorypath,$getpropath)=@_;
7223: $directorypath =~ s/\/$//;
7224: my $listing=&reply('du2:'.&escape($directorypath).':'
7225: .&escape($getpropath).':'.&escape($uname).':'
7226: .&escape($udom),homeserver($uname,$udom));
7227: if ($listing eq 'unknown_cmd') {
7228: if ($getpropath) {
7229: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7230: }
7231: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7232: }
1.514 albertel 7233: return $listing;
1.512 banghart 7234: }
7235:
1.566 banghart 7236: sub is_locked {
7237: my ($file_name, $domain, $user) = @_;
7238: my @check;
7239: my $is_locked;
7240: push @check, $file_name;
1.613 albertel 7241: my %locked = &get('file_permissions',\@check,
1.620 albertel 7242: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7243: my ($tmp)=keys(%locked);
7244: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7245:
1.566 banghart 7246: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7247: $is_locked = 'false';
7248: foreach my $entry (@{$locked{$file_name}}) {
7249: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7250: $is_locked = 'true';
7251: last;
1.745 raeburn 7252: }
7253: }
1.566 banghart 7254: } else {
7255: $is_locked = 'false';
7256: }
7257: }
7258:
1.759 albertel 7259: sub declutter_portfile {
7260: my ($file) = @_;
1.833 albertel 7261: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7262: return $file;
7263: }
7264:
1.559 banghart 7265: # ------------------------------------------------------------- Mark as Read Only
7266:
7267: sub mark_as_readonly {
7268: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7269: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7270: my ($tmp)=keys(%current_permissions);
7271: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7272: foreach my $file (@{$files}) {
1.759 albertel 7273: $file = &declutter_portfile($file);
1.561 banghart 7274: push(@{$current_permissions{$file}},$what);
1.559 banghart 7275: }
1.613 albertel 7276: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7277: return;
7278: }
7279:
1.572 banghart 7280: # ------------------------------------------------------------Save Selected Files
7281:
7282: sub save_selected_files {
7283: my ($user, $path, @files) = @_;
7284: my $filename = $user."savedfiles";
1.573 banghart 7285: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7286: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7287: foreach my $file (@files) {
1.620 albertel 7288: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7289: }
7290: foreach my $file (@other_files) {
1.574 banghart 7291: print (OUT $file."\n");
1.572 banghart 7292: }
1.574 banghart 7293: close (OUT);
1.572 banghart 7294: return 'ok';
7295: }
7296:
1.574 banghart 7297: sub clear_selected_files {
7298: my ($user) = @_;
7299: my $filename = $user."savedfiles";
7300: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7301: print (OUT undef);
7302: close (OUT);
7303: return ("ok");
7304: }
7305:
1.572 banghart 7306: sub files_in_path {
7307: my ($user, $path) = @_;
7308: my $filename = $user."savedfiles";
7309: my %return_files;
1.574 banghart 7310: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7311: while (my $line_in = <IN>) {
1.574 banghart 7312: chomp ($line_in);
7313: my @paths_and_file = split (m!/!, $line_in);
7314: my $file_part = pop (@paths_and_file);
7315: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7316: $path_part.='/';
7317: my $path_and_file = $path_part.$file_part;
7318: if ($path_part eq $path) {
7319: $return_files{$file_part}= 'selected';
7320: }
7321: }
1.574 banghart 7322: close (IN);
7323: return (\%return_files);
1.572 banghart 7324: }
7325:
7326: # called in portfolio select mode, to show files selected NOT in current directory
7327: sub files_not_in_path {
7328: my ($user, $path) = @_;
7329: my $filename = $user."savedfiles";
7330: my @return_files;
7331: my $path_part;
1.800 albertel 7332: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7333: while (my $line = <IN>) {
1.572 banghart 7334: #ok, I know it's clunky, but I want it to work
1.800 albertel 7335: my @paths_and_file = split(m|/|, $line);
7336: my $file_part = pop(@paths_and_file);
7337: chomp($file_part);
7338: my $path_part = join('/', @paths_and_file);
1.572 banghart 7339: $path_part .= '/';
7340: my $path_and_file = $path_part.$file_part;
7341: if ($path_part ne $path) {
1.800 albertel 7342: push(@return_files, ($path_and_file));
1.572 banghart 7343: }
7344: }
1.800 albertel 7345: close(OUT);
1.574 banghart 7346: return (@return_files);
1.572 banghart 7347: }
7348:
1.745 raeburn 7349: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7350:
1.745 raeburn 7351: sub get_portfile_permissions {
7352: my ($domain,$user) = @_;
1.613 albertel 7353: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7354: my ($tmp)=keys(%current_permissions);
7355: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7356: return \%current_permissions;
7357: }
7358:
7359: #---------------------------------------------Get portfolio file access controls
7360:
1.749 raeburn 7361: sub get_access_controls {
1.745 raeburn 7362: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7363: my %access;
7364: my $real_file = $file;
7365: $file =~ s/\.meta$//;
1.745 raeburn 7366: if (defined($file)) {
1.749 raeburn 7367: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7368: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7369: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7370: }
7371: }
1.745 raeburn 7372: } else {
1.749 raeburn 7373: foreach my $key (keys(%{$current_permissions})) {
7374: if ($key =~ /\0accesscontrol$/) {
7375: if (defined($group)) {
7376: if ($key !~ m-^\Q$group\E/-) {
7377: next;
7378: }
7379: }
7380: my ($fullpath) = split(/\0/,$key);
7381: if (ref($$current_permissions{$key}) eq 'HASH') {
7382: foreach my $control (keys(%{$$current_permissions{$key}})) {
7383: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7384: }
7385: }
7386: }
7387: }
7388: }
7389: return %access;
7390: }
7391:
7392: sub modify_access_controls {
7393: my ($file_name,$changes,$domain,$user)=@_;
7394: my ($outcome,$deloutcome);
7395: my %store_permissions;
7396: my %new_values;
7397: my %new_control;
7398: my %translation;
7399: my @deletions = ();
7400: my $now = time;
7401: if (exists($$changes{'activate'})) {
7402: if (ref($$changes{'activate'}) eq 'HASH') {
7403: my @newitems = sort(keys(%{$$changes{'activate'}}));
7404: my $numnew = scalar(@newitems);
7405: for (my $i=0; $i<$numnew; $i++) {
7406: my $newkey = $newitems[$i];
7407: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7408: if ($newkey =~ /^\d+:/) {
7409: $newkey =~ s/^(\d+)/$newid/;
7410: $translation{$1} = $newid;
7411: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7412: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7413: $translation{$1} = $newid;
7414: }
1.749 raeburn 7415: $new_values{$file_name."\0".$newkey} =
7416: $$changes{'activate'}{$newitems[$i]};
7417: $new_control{$newkey} = $now;
7418: }
7419: }
7420: }
7421: my %todelete;
7422: my %changed_items;
7423: foreach my $action ('delete','update') {
7424: if (exists($$changes{$action})) {
7425: if (ref($$changes{$action}) eq 'HASH') {
7426: foreach my $key (keys(%{$$changes{$action}})) {
7427: my ($itemnum) = ($key =~ /^([^:]+):/);
7428: if ($action eq 'delete') {
7429: $todelete{$itemnum} = 1;
7430: } else {
7431: $changed_items{$itemnum} = $key;
7432: }
7433: }
1.745 raeburn 7434: }
7435: }
1.749 raeburn 7436: }
7437: # get lock on access controls for file.
7438: my $lockhash = {
7439: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7440: ':'.$env{'user.domain'},
7441: };
7442: my $tries = 0;
7443: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7444:
7445: while (($gotlock ne 'ok') && $tries <3) {
7446: $tries ++;
7447: sleep 1;
7448: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7449: }
7450: if ($gotlock eq 'ok') {
7451: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7452: my ($tmp)=keys(%curr_permissions);
7453: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7454: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7455: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7456: if (ref($curr_controls) eq 'HASH') {
7457: foreach my $control_item (keys(%{$curr_controls})) {
7458: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7459: if (defined($todelete{$itemnum})) {
7460: push(@deletions,$file_name."\0".$control_item);
7461: } else {
7462: if (defined($changed_items{$itemnum})) {
7463: $new_control{$changed_items{$itemnum}} = $now;
7464: push(@deletions,$file_name."\0".$control_item);
7465: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7466: } else {
7467: $new_control{$control_item} = $$curr_controls{$control_item};
7468: }
7469: }
1.745 raeburn 7470: }
7471: }
7472: }
1.970 raeburn 7473: my ($group);
7474: if (&is_course($domain,$user)) {
7475: ($group,my $file) = split(/\//,$file_name,2);
7476: }
1.749 raeburn 7477: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7478: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7479: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7480: # remove lock
7481: my @del_lock = ($file_name."\0".'locked_access_records');
7482: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7483: my $sqlresult =
1.970 raeburn 7484: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7485: $group);
1.749 raeburn 7486: } else {
7487: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7488: }
1.749 raeburn 7489: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7490: }
7491:
1.827 raeburn 7492: sub make_public_indefinitely {
7493: my ($requrl) = @_;
7494: my $now = time;
7495: my $action = 'activate';
7496: my $aclnum = 0;
7497: if (&is_portfolio_url($requrl)) {
7498: my (undef,$udom,$unum,$file_name,$group) =
7499: &parse_portfolio_url($requrl);
7500: my $current_perms = &get_portfile_permissions($udom,$unum);
7501: my %access_controls = &get_access_controls($current_perms,
7502: $group,$file_name);
7503: foreach my $key (keys(%{$access_controls{$file_name}})) {
7504: my ($num,$scope,$end,$start) =
7505: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7506: if ($scope eq 'public') {
7507: if ($start <= $now && $end == 0) {
7508: $action = 'none';
7509: } else {
7510: $action = 'update';
7511: $aclnum = $num;
7512: }
7513: last;
7514: }
7515: }
7516: if ($action eq 'none') {
7517: return 'ok';
7518: } else {
7519: my %changes;
7520: my $newend = 0;
7521: my $newstart = $now;
7522: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7523: $changes{$action}{$newkey} = {
7524: type => 'public',
7525: time => {
7526: start => $newstart,
7527: end => $newend,
7528: },
7529: };
7530: my ($outcome,$deloutcome,$new_values,$translation) =
7531: &modify_access_controls($file_name,\%changes,$udom,$unum);
7532: return $outcome;
7533: }
7534: } else {
7535: return 'invalid';
7536: }
7537: }
7538:
1.745 raeburn 7539: #------------------------------------------------------Get Marked as Read Only
7540:
7541: sub get_marked_as_readonly {
7542: my ($domain,$user,$what,$group) = @_;
7543: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7544: my @readonly_files;
1.629 banghart 7545: my $cmp1=$what;
7546: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7547: while (my ($file_name,$value) = each(%{$current_permissions})) {
7548: if (defined($group)) {
7549: if ($file_name !~ m-^\Q$group\E/-) {
7550: next;
7551: }
7552: }
1.561 banghart 7553: if (ref($value) eq "ARRAY"){
7554: foreach my $stored_what (@{$value}) {
1.629 banghart 7555: my $cmp2=$stored_what;
1.759 albertel 7556: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7557: $cmp2=join('',@{$stored_what});
1.745 raeburn 7558: }
1.629 banghart 7559: if ($cmp1 eq $cmp2) {
1.561 banghart 7560: push(@readonly_files, $file_name);
1.745 raeburn 7561: last;
1.563 banghart 7562: } elsif (!defined($what)) {
7563: push(@readonly_files, $file_name);
1.745 raeburn 7564: last;
1.561 banghart 7565: }
7566: }
1.745 raeburn 7567: }
1.561 banghart 7568: }
7569: return @readonly_files;
7570: }
1.577 banghart 7571: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7572:
1.577 banghart 7573: sub get_marked_as_readonly_hash {
1.745 raeburn 7574: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7575: my %readonly_files;
1.745 raeburn 7576: while (my ($file_name,$value) = each(%{$current_permissions})) {
7577: if (defined($group)) {
7578: if ($file_name !~ m-^\Q$group\E/-) {
7579: next;
7580: }
7581: }
1.577 banghart 7582: if (ref($value) eq "ARRAY"){
7583: foreach my $stored_what (@{$value}) {
1.745 raeburn 7584: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7585: foreach my $lock_descriptor(@{$stored_what}) {
7586: if ($lock_descriptor eq 'graded') {
7587: $readonly_files{$file_name} = 'graded';
7588: } elsif ($lock_descriptor eq 'handback') {
7589: $readonly_files{$file_name} = 'handback';
7590: } else {
7591: if (!exists($readonly_files{$file_name})) {
7592: $readonly_files{$file_name} = 'locked';
7593: }
7594: }
1.745 raeburn 7595: }
1.750 banghart 7596: }
1.577 banghart 7597: }
7598: }
7599: }
7600: return %readonly_files;
7601: }
1.559 banghart 7602: # ------------------------------------------------------------ Unmark as Read Only
7603:
7604: sub unmark_as_readonly {
1.629 banghart 7605: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7606: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7607: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7608: $file_name = &declutter_portfile($file_name);
1.634 albertel 7609: my $symb_crs = $what;
7610: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7611: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7612: my ($tmp)=keys(%current_permissions);
7613: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7614: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7615: foreach my $file (@readonly_files) {
1.759 albertel 7616: my $clean_file = &declutter_portfile($file);
7617: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7618: my $current_locks = $current_permissions{$file};
1.563 banghart 7619: my @new_locks;
7620: my @del_keys;
7621: if (ref($current_locks) eq "ARRAY"){
7622: foreach my $locker (@{$current_locks}) {
1.632 albertel 7623: my $compare=$locker;
1.749 raeburn 7624: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7625: $compare=join('',@{$locker});
1.746 raeburn 7626: if ($compare ne $symb_crs) {
7627: push(@new_locks, $locker);
7628: }
1.563 banghart 7629: }
7630: }
1.650 albertel 7631: if (scalar(@new_locks) > 0) {
1.563 banghart 7632: $current_permissions{$file} = \@new_locks;
7633: } else {
7634: push(@del_keys, $file);
1.613 albertel 7635: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7636: delete($current_permissions{$file});
1.563 banghart 7637: }
7638: }
1.561 banghart 7639: }
1.613 albertel 7640: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7641: return;
7642: }
1.512 banghart 7643:
1.17 www 7644: # ------------------------------------------------------------ Directory lister
7645:
7646: sub dirlist {
1.955 raeburn 7647: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7648: $uri=~s/^\///;
7649: $uri=~s/\/$//;
1.253 stredwic 7650: my ($udom, $uname);
1.955 raeburn 7651: if ($getuserdir) {
1.253 stredwic 7652: $udom = $userdomain;
7653: $uname = $username;
1.955 raeburn 7654: } else {
7655: (undef,$udom,$uname)=split(/\//,$uri);
7656: if(defined($userdomain)) {
7657: $udom = $userdomain;
7658: }
7659: if(defined($username)) {
7660: $uname = $username;
7661: }
1.253 stredwic 7662: }
1.955 raeburn 7663: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7664:
1.955 raeburn 7665: $dirRoot = $perlvar{'lonDocRoot'};
7666: if (defined($getpropath)) {
7667: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7668: $dirRoot =~ s/\/$//;
1.955 raeburn 7669: } elsif (defined($getuserdir)) {
7670: my $subdir=$uname.'__';
7671: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7672: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7673: ."/$udom/$subdir/$uname";
7674: } elsif (defined($alternateRoot)) {
7675: $dirRoot = $alternateRoot;
1.751 banghart 7676: }
1.253 stredwic 7677:
7678: if($udom) {
7679: if($uname) {
1.955 raeburn 7680: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7681: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7682: .':'.&escape($uname).':'.&escape($udom),
7683: &homeserver($uname,$udom));
7684: if ($listing eq 'unknown_cmd') {
7685: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7686: &homeserver($uname,$udom));
7687: } else {
7688: @listing_results = map { &unescape($_); } split(/:/,$listing);
7689: }
1.605 matthew 7690: if ($listing eq 'unknown_cmd') {
1.800 albertel 7691: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7692: &homeserver($uname,$udom));
1.605 matthew 7693: @listing_results = split(/:/,$listing);
7694: } else {
7695: @listing_results = map { &unescape($_); } split(/:/,$listing);
7696: }
7697: return @listing_results;
1.955 raeburn 7698: } elsif(!$alternateRoot) {
1.800 albertel 7699: my %allusers;
1.841 albertel 7700: my %servers = &get_servers($udom,'library');
1.955 raeburn 7701: foreach my $tryserver (keys(%servers)) {
7702: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7703: &escape($udom),$tryserver);
7704: if ($listing eq 'unknown_cmd') {
7705: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7706: $udom, $tryserver);
7707: } else {
7708: @listing_results = map { &unescape($_); } split(/:/,$listing);
7709: }
1.841 albertel 7710: if ($listing eq 'unknown_cmd') {
7711: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7712: $udom, $tryserver);
7713: @listing_results = split(/:/,$listing);
7714: } else {
7715: @listing_results =
7716: map { &unescape($_); } split(/:/,$listing);
7717: }
7718: if ($listing_results[0] ne 'no_such_dir' &&
7719: $listing_results[0] ne 'empty' &&
7720: $listing_results[0] ne 'con_lost') {
7721: foreach my $line (@listing_results) {
7722: my ($entry) = split(/&/,$line,2);
7723: $allusers{$entry} = 1;
7724: }
7725: }
1.253 stredwic 7726: }
7727: my $alluserstr='';
1.800 albertel 7728: foreach my $user (sort(keys(%allusers))) {
7729: $alluserstr.=$user.'&user:';
1.253 stredwic 7730: }
7731: $alluserstr=~s/:$//;
7732: return split(/:/,$alluserstr);
7733: } else {
1.800 albertel 7734: return ('missing user name');
1.253 stredwic 7735: }
1.955 raeburn 7736: } elsif(!defined($getpropath)) {
1.841 albertel 7737: my @all_domains = sort(&all_domains());
1.955 raeburn 7738: foreach my $domain (@all_domains) {
7739: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7740: }
7741: return @all_domains;
7742: } else {
1.800 albertel 7743: return ('missing domain');
1.275 stredwic 7744: }
7745: }
7746:
7747: # --------------------------------------------- GetFileTimestamp
7748: # This function utilizes dirlist and returns the date stamp for
7749: # when it was last modified. It will also return an error of -1
7750: # if an error occurs
7751:
7752: sub GetFileTimestamp {
1.955 raeburn 7753: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7754: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7755: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7756: my ($fileStat) =
7757: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7758: undef,$getuserdir);
1.275 stredwic 7759: my @stats = split('&', $fileStat);
7760: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7761: # @stats contains first the filename, then the stat output
7762: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7763: } else {
7764: return -1;
1.253 stredwic 7765: }
1.26 www 7766: }
7767:
1.712 albertel 7768: sub stat_file {
7769: my ($uri) = @_;
1.787 albertel 7770: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7771:
1.955 raeburn 7772: my ($udom,$uname,$file);
1.712 albertel 7773: if ($uri =~ m-^/(uploaded|editupload)/-) {
7774: ($udom,$uname,$file) =
1.811 albertel 7775: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7776: $file = 'userfiles/'.$file;
7777: }
7778: if ($uri =~ m-^/res/-) {
7779: ($udom,$uname) =
1.807 albertel 7780: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7781: $file = $uri;
7782: }
7783:
7784: if (!$udom || !$uname || !$file) {
7785: # unable to handle the uri
7786: return ();
7787: }
1.956 raeburn 7788: my $getpropath;
7789: if ($file =~ /^userfiles\//) {
7790: $getpropath = 1;
7791: }
1.955 raeburn 7792: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7793: my @stats = split('&', $result);
1.721 banghart 7794:
1.712 albertel 7795: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7796: shift(@stats); #filename is first
7797: return @stats;
7798: }
7799: return ();
7800: }
7801:
1.26 www 7802: # -------------------------------------------------------- Value of a Condition
7803:
1.713 albertel 7804: # gets the value of a specific preevaluated condition
7805: # stored in the string $env{user.state.<cid>}
7806: # or looks up a condition reference in the bighash and if if hasn't
7807: # already been evaluated recurses into docondval to get the value of
7808: # the condition, then memoizing it to
7809: # $env{user.state.<cid>.<condition>}
1.40 www 7810: sub directcondval {
7811: my $number=shift;
1.620 albertel 7812: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7813: &Apache::lonuserstate::evalstate();
7814: }
1.713 albertel 7815: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7816: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7817: } elsif ($number =~ /^_/) {
7818: my $sub_condition;
7819: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7820: &GDBM_READER(),0640)) {
7821: $sub_condition=$bighash{'conditions'.$number};
7822: untie(%bighash);
7823: }
7824: my $value = &docondval($sub_condition);
1.949 raeburn 7825: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7826: return $value;
7827: }
1.620 albertel 7828: if ($env{'user.state.'.$env{'request.course.id'}}) {
7829: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7830: } else {
7831: return 2;
7832: }
7833: }
7834:
1.713 albertel 7835: # get the collection of conditions for this resource
1.26 www 7836: sub condval {
7837: my $condidx=shift;
1.54 www 7838: my $allpathcond='';
1.713 albertel 7839: foreach my $cond (split(/\|/,$condidx)) {
7840: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7841: $allpathcond.=
7842: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7843: }
1.191 harris41 7844: }
1.54 www 7845: $allpathcond=~s/\|$//;
1.713 albertel 7846: return &docondval($allpathcond);
7847: }
7848:
7849: #evaluates an expression of conditions
7850: sub docondval {
7851: my ($allpathcond) = @_;
7852: my $result=0;
7853: if ($env{'request.course.id'}
7854: && defined($allpathcond)) {
7855: my $operand='|';
7856: my @stack;
7857: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7858: if ($chunk eq '(') {
7859: push @stack,($operand,$result);
7860: } elsif ($chunk eq ')') {
7861: my $before=pop @stack;
7862: if (pop @stack eq '&') {
7863: $result=$result>$before?$before:$result;
7864: } else {
7865: $result=$result>$before?$result:$before;
7866: }
7867: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7868: $operand=$chunk;
7869: } else {
7870: my $new=directcondval($chunk);
7871: if ($operand eq '&') {
7872: $result=$result>$new?$new:$result;
7873: } else {
7874: $result=$result>$new?$result:$new;
7875: }
7876: }
7877: }
1.26 www 7878: }
7879: return $result;
1.421 albertel 7880: }
7881:
7882: # ---------------------------------------------------- Devalidate courseresdata
7883:
7884: sub devalidatecourseresdata {
7885: my ($coursenum,$coursedomain)=@_;
7886: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7887: &devalidate_cache_new('courseres',$hashid);
1.28 www 7888: }
7889:
1.763 www 7890:
1.200 www 7891: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 7892: #
7893: # Parameters:
7894: # $coursenum - Number of the course.
7895: # $coursedomain - Domain at which the course was created.
7896: # Returns:
7897: # A hash of the course parameters along (I think) with timestamps
7898: # and version info.
1.877 foxr 7899:
1.624 albertel 7900: sub get_courseresdata {
7901: my ($coursenum,$coursedomain)=@_;
1.200 www 7902: my $coursehom=&homeserver($coursenum,$coursedomain);
7903: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7904: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 7905: my %dumpreply;
1.417 albertel 7906: unless (defined($cached)) {
1.624 albertel 7907: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 7908: $result=\%dumpreply;
1.251 albertel 7909: my ($tmp) = keys(%dumpreply);
7910: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 7911: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 7912: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7913: return $tmp;
1.416 albertel 7914: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 7915: $result=undef;
1.599 albertel 7916: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 7917: }
7918: }
1.624 albertel 7919: return $result;
7920: }
7921:
1.633 albertel 7922: sub devalidateuserresdata {
7923: my ($uname,$udom)=@_;
7924: my $hashid="$udom:$uname";
7925: &devalidate_cache_new('userres',$hashid);
7926: }
7927:
1.624 albertel 7928: sub get_userresdata {
7929: my ($uname,$udom)=@_;
7930: #most student don\'t have any data set, check if there is some data
7931: if (&EXT_cache_status($udom,$uname)) { return undef; }
7932:
7933: my $hashid="$udom:$uname";
7934: my ($result,$cached)=&is_cached_new('userres',$hashid);
7935: if (!defined($cached)) {
7936: my %resourcedata=&dump('resourcedata',$udom,$uname);
7937: $result=\%resourcedata;
7938: &do_cache_new('userres',$hashid,$result,600);
7939: }
7940: my ($tmp)=keys(%$result);
7941: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7942: return $result;
7943: }
7944: #error 2 occurs when the .db doesn't exist
7945: if ($tmp!~/error: 2 /) {
1.672 albertel 7946: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 7947: " Trying to get resource data for ".
7948: $uname." at ".$udom.": ".
7949: $tmp."</font>");
7950: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 7951: #&EXT_cache_set($udom,$uname);
7952: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 7953: undef($tmp); # not really an error so don't send it back
1.624 albertel 7954: }
7955: return $tmp;
7956: }
1.879 foxr 7957: #----------------------------------------------- resdata - return resource data
7958: # Purpose:
7959: # Return resource data for either users or for a course.
7960: # Parameters:
7961: # $name - Course/user name.
7962: # $domain - Name of the domain the user/course is registered on.
7963: # $type - Type of thing $name is (must be 'course' or 'user'
7964: # @which - Array of names of resources desired.
7965: # Returns:
7966: # The value of the first reasource in @which that is found in the
7967: # resource hash.
7968: # Exceptional Conditions:
7969: # If the $type passed in is not valid (not the string 'course' or
7970: # 'user', an undefined reference is returned.
7971: # If none of the resources are found, an undef is returned
1.624 albertel 7972: sub resdata {
7973: my ($name,$domain,$type,@which)=@_;
7974: my $result;
7975: if ($type eq 'course') {
7976: $result=&get_courseresdata($name,$domain);
7977: } elsif ($type eq 'user') {
7978: $result=&get_userresdata($name,$domain);
7979: }
7980: if (!ref($result)) { return $result; }
1.251 albertel 7981: foreach my $item (@which) {
1.927 albertel 7982: if (defined($result->{$item->[0]})) {
7983: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 7984: }
1.250 albertel 7985: }
1.291 albertel 7986: return undef;
1.200 www 7987: }
7988:
1.379 matthew 7989: #
7990: # EXT resource caching routines
7991: #
7992:
7993: sub clear_EXT_cache_status {
1.383 albertel 7994: &delenv('cache.EXT.');
1.379 matthew 7995: }
7996:
7997: sub EXT_cache_status {
7998: my ($target_domain,$target_user) = @_;
1.383 albertel 7999: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8000: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8001: # We know already the user has no data
8002: return 1;
8003: } else {
8004: return 0;
8005: }
8006: }
8007:
8008: sub EXT_cache_set {
8009: my ($target_domain,$target_user) = @_;
1.383 albertel 8010: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8011: #&appenv({$cachename => time});
1.379 matthew 8012: }
8013:
1.28 www 8014: # --------------------------------------------------------- Value of a Variable
1.58 www 8015: sub EXT {
1.715 albertel 8016:
1.395 albertel 8017: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8018: unless ($varname) { return ''; }
1.218 albertel 8019: #get real user name/domain, courseid and symb
8020: my $courseid;
1.359 albertel 8021: my $publicuser;
1.427 www 8022: if ($symbparm) {
8023: $symbparm=&get_symb_from_alias($symbparm);
8024: }
1.218 albertel 8025: if (!($uname && $udom)) {
1.790 albertel 8026: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8027: if (!$symbparm) { $symbparm=$cursymb; }
8028: } else {
1.620 albertel 8029: $courseid=$env{'request.course.id'};
1.218 albertel 8030: }
1.48 www 8031: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8032: my $rest;
1.320 albertel 8033: if (defined($therest[0])) {
1.48 www 8034: $rest=join('.',@therest);
8035: } else {
8036: $rest='';
8037: }
1.320 albertel 8038:
1.57 www 8039: my $qualifierrest=$qualifier;
8040: if ($rest) { $qualifierrest.='.'.$rest; }
8041: my $spacequalifierrest=$space;
8042: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8043: if ($realm eq 'user') {
1.48 www 8044: # --------------------------------------------------------------- user.resource
8045: if ($space eq 'resource') {
1.651 albertel 8046: if ( (defined($Apache::lonhomework::parsing_a_problem)
8047: || defined($Apache::lonhomework::parsing_a_task))
8048: &&
1.744 albertel 8049: ($symbparm eq &symbread()) ) {
8050: # if we are in the middle of processing the resource the
8051: # get the value we are planning on committing
8052: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8053: return $Apache::lonhomework::results{$qualifierrest};
8054: } else {
8055: return $Apache::lonhomework::history{$qualifierrest};
8056: }
1.335 albertel 8057: } else {
1.359 albertel 8058: my %restored;
1.620 albertel 8059: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8060: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8061: } else {
8062: %restored=&restore($symbparm,$courseid,$udom,$uname);
8063: }
1.335 albertel 8064: return $restored{$qualifierrest};
8065: }
1.48 www 8066: # ----------------------------------------------------------------- user.access
8067: } elsif ($space eq 'access') {
1.218 albertel 8068: # FIXME - not supporting calls for a specific user
1.48 www 8069: return &allowed($qualifier,$rest);
8070: # ------------------------------------------ user.preferences, user.environment
8071: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8072: if (($uname eq $env{'user.name'}) &&
8073: ($udom eq $env{'user.domain'})) {
8074: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8075: } else {
1.359 albertel 8076: my %returnhash;
8077: if (!$publicuser) {
8078: %returnhash=&userenvironment($udom,$uname,
8079: $qualifierrest);
8080: }
1.218 albertel 8081: return $returnhash{$qualifierrest};
8082: }
1.48 www 8083: # ----------------------------------------------------------------- user.course
8084: } elsif ($space eq 'course') {
1.218 albertel 8085: # FIXME - not supporting calls for a specific user
1.620 albertel 8086: return $env{join('.',('request.course',$qualifier))};
1.48 www 8087: # ------------------------------------------------------------------- user.role
8088: } elsif ($space eq 'role') {
1.218 albertel 8089: # FIXME - not supporting calls for a specific user
1.620 albertel 8090: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8091: if ($qualifier eq 'value') {
8092: return $role;
8093: } elsif ($qualifier eq 'extent') {
8094: return $where;
8095: }
8096: # ----------------------------------------------------------------- user.domain
8097: } elsif ($space eq 'domain') {
1.218 albertel 8098: return $udom;
1.48 www 8099: # ------------------------------------------------------------------- user.name
8100: } elsif ($space eq 'name') {
1.218 albertel 8101: return $uname;
1.48 www 8102: # ---------------------------------------------------- Any other user namespace
1.29 www 8103: } else {
1.359 albertel 8104: my %reply;
8105: if (!$publicuser) {
8106: %reply=&get($space,[$qualifierrest],$udom,$uname);
8107: }
8108: return $reply{$qualifierrest};
1.48 www 8109: }
1.236 www 8110: } elsif ($realm eq 'query') {
8111: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8112: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8113: [$spacequalifierrest]);
1.620 albertel 8114: return $env{'form.'.$spacequalifierrest};
1.236 www 8115: } elsif ($realm eq 'request') {
1.48 www 8116: # ------------------------------------------------------------- request.browser
8117: if ($space eq 'browser') {
1.430 www 8118: if ($qualifier eq 'textremote') {
1.676 albertel 8119: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8120: return 1;
8121: } else {
8122: return 0;
8123: }
8124: } else {
1.620 albertel 8125: return $env{'browser.'.$qualifier};
1.430 www 8126: }
1.57 www 8127: # ------------------------------------------------------------ request.filename
8128: } else {
1.620 albertel 8129: return $env{'request.'.$spacequalifierrest};
1.29 www 8130: }
1.28 www 8131: } elsif ($realm eq 'course') {
1.48 www 8132: # ---------------------------------------------------------- course.description
1.620 albertel 8133: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8134: } elsif ($realm eq 'resource') {
1.165 www 8135:
1.620 albertel 8136: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8137: if (!$symbparm) { $symbparm=&symbread(); }
8138: }
1.693 albertel 8139:
8140: if ($space eq 'title') {
8141: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8142: return &gettitle($symbparm);
8143: }
8144:
8145: if ($space eq 'map') {
8146: my ($map) = &decode_symb($symbparm);
8147: return &symbread($map);
8148: }
1.905 albertel 8149: if ($space eq 'filename') {
8150: if ($symbparm) {
8151: return &clutter((&decode_symb($symbparm))[2]);
8152: }
8153: return &hreflocation('',$env{'request.filename'});
8154: }
1.693 albertel 8155:
8156: my ($section, $group, @groups);
1.593 albertel 8157: my ($courselevelm,$courselevel);
1.539 albertel 8158: if ($symbparm && defined($courseid) &&
1.620 albertel 8159: $courseid eq $env{'request.course.id'}) {
1.165 www 8160:
1.218 albertel 8161: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8162:
1.60 www 8163: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8164: my $symbp=$symbparm;
1.735 albertel 8165: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8166:
8167: my $symbparm=$symbp.'.'.$spacequalifierrest;
8168: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8169:
1.620 albertel 8170: if (($env{'user.name'} eq $uname) &&
8171: ($env{'user.domain'} eq $udom)) {
8172: $section=$env{'request.course.sec'};
1.733 raeburn 8173: @groups = split(/:/,$env{'request.course.groups'});
8174: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8175: } else {
1.539 albertel 8176: if (! defined($usection)) {
1.551 albertel 8177: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8178: } else {
8179: $section = $usection;
8180: }
1.733 raeburn 8181: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8182: }
8183:
8184: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8185: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8186: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8187:
1.593 albertel 8188: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8189: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8190: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8191:
1.60 www 8192: # ----------------------------------------------------------- first, check user
1.624 albertel 8193:
8194: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8195: ([$courselevelr,'resource'],
8196: [$courselevelm,'map' ],
8197: [$courselevel, 'course' ]));
1.931 albertel 8198: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8199:
1.594 albertel 8200: # ------------------------------------------------ second, check some of course
1.684 raeburn 8201: my $coursereply;
1.691 raeburn 8202: if (@groups > 0) {
8203: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8204: $mapparm,$spacequalifierrest);
1.927 albertel 8205: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8206: }
1.96 www 8207:
1.684 raeburn 8208: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8209: $env{'course.'.$courseid.'.domain'},
8210: 'course',
8211: ([$seclevelr, 'resource'],
8212: [$seclevelm, 'map' ],
8213: [$seclevel, 'course' ],
8214: [$courselevelr,'resource']));
8215: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8216:
1.60 www 8217: # ------------------------------------------------------ third, check map parms
1.218 albertel 8218: my %parmhash=();
8219: my $thisparm='';
8220: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8221: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8222: &GDBM_READER(),0640)) {
1.218 albertel 8223: $thisparm=$parmhash{$symbparm};
8224: untie(%parmhash);
8225: }
1.927 albertel 8226: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8227: }
1.594 albertel 8228: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8229:
1.218 albertel 8230: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8231: my $filename;
8232: if (!$symbparm) { $symbparm=&symbread(); }
8233: if ($symbparm) {
1.409 www 8234: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8235: } else {
1.620 albertel 8236: $filename=$env{'request.filename'};
1.282 albertel 8237: }
8238: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8239: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8240: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8241: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8242:
1.927 albertel 8243: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8244: if ($symbparm && defined($courseid) &&
1.620 albertel 8245: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8246: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8247: $env{'course.'.$courseid.'.domain'},
8248: 'course',
1.927 albertel 8249: ([$courselevelm,'map' ],
8250: [$courselevel, 'course']));
8251: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8252: }
1.145 www 8253: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8254: unless ($space eq '0') {
1.336 albertel 8255: my @parts=split(/_/,$space);
8256: my $id=pop(@parts);
8257: my $part=join('_',@parts);
8258: if ($part eq '') { $part='0'; }
1.927 albertel 8259: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8260: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8261: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8262: }
1.395 albertel 8263: if ($recurse) { return undef; }
8264: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8265: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8266: # ---------------------------------------------------- Any other user namespace
8267: } elsif ($realm eq 'environment') {
8268: # ----------------------------------------------------------------- environment
1.620 albertel 8269: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8270: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8271: } else {
1.770 albertel 8272: if ($uname eq 'anonymous' && $udom eq '') {
8273: return '';
8274: }
1.219 albertel 8275: my %returnhash=&userenvironment($udom,$uname,
8276: $spacequalifierrest);
8277: return $returnhash{$spacequalifierrest};
8278: }
1.28 www 8279: } elsif ($realm eq 'system') {
1.48 www 8280: # ----------------------------------------------------------------- system.time
8281: if ($space eq 'time') {
8282: return time;
8283: }
1.696 albertel 8284: } elsif ($realm eq 'server') {
8285: # ----------------------------------------------------------------- system.time
8286: if ($space eq 'name') {
8287: return $ENV{'SERVER_NAME'};
8288: }
1.28 www 8289: }
1.48 www 8290: return '';
1.61 www 8291: }
8292:
1.927 albertel 8293: sub get_reply {
8294: my ($reply_value) = @_;
1.940 raeburn 8295: if (ref($reply_value) eq 'ARRAY') {
8296: if (wantarray) {
8297: return @$reply_value;
8298: }
8299: return $reply_value->[0];
8300: } else {
8301: return $reply_value;
1.927 albertel 8302: }
8303: }
8304:
1.691 raeburn 8305: sub check_group_parms {
8306: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8307: my @groupitems = ();
8308: my $resultitem;
1.927 albertel 8309: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8310: foreach my $group (@{$groups}) {
8311: foreach my $level (@levels) {
1.927 albertel 8312: my $item = $courseid.'.['.$group.'].'.$level->[0];
8313: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8314: }
8315: }
8316: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8317: $env{'course.'.$courseid.'.domain'},
8318: 'course',@groupitems);
8319: return $coursereply;
8320: }
8321:
8322: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8323: my ($courseid,@groups) = @_;
8324: @groups = sort(@groups);
1.691 raeburn 8325: return @groups;
8326: }
8327:
1.395 albertel 8328: sub packages_tab_default {
8329: my ($uri,$varname)=@_;
8330: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8331:
8332: my (@extension,@specifics,$do_default);
8333: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8334: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8335: if ($pack_type eq 'default') {
8336: $do_default=1;
8337: } elsif ($pack_type eq 'extension') {
8338: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8339: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8340: # only look at packages defaults for packages that this id is
1.738 albertel 8341: push(@specifics,[$package,$pack_type,$pack_part]);
8342: }
8343: }
8344: # first look for a package that matches the requested part id
8345: foreach my $package (@specifics) {
8346: my (undef,$pack_type,$pack_part)=@{$package};
8347: next if ($pack_part ne $part);
8348: if (defined($packagetab{"$pack_type&$name&default"})) {
8349: return $packagetab{"$pack_type&$name&default"};
8350: }
8351: }
8352: # look for any possible matching non extension_ package
8353: foreach my $package (@specifics) {
8354: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8355: if (defined($packagetab{"$pack_type&$name&default"})) {
8356: return $packagetab{"$pack_type&$name&default"};
8357: }
1.585 albertel 8358: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8359: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8360: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8361: }
8362: }
1.738 albertel 8363: # look for any posible extension_ match
8364: foreach my $package (@extension) {
8365: my ($package,$pack_type)=@{$package};
8366: if (defined($packagetab{"$pack_type&$name&default"})) {
8367: return $packagetab{"$pack_type&$name&default"};
8368: }
8369: if (defined($packagetab{$package."&$name&default"})) {
8370: return $packagetab{$package."&$name&default"};
8371: }
8372: }
8373: # look for a global default setting
8374: if ($do_default && defined($packagetab{"default&$name&default"})) {
8375: return $packagetab{"default&$name&default"};
8376: }
1.395 albertel 8377: return undef;
8378: }
8379:
1.334 albertel 8380: sub add_prefix_and_part {
8381: my ($prefix,$part)=@_;
8382: my $keyroot;
8383: if (defined($prefix) && $prefix !~ /^__/) {
8384: # prefix that has a part already
8385: $keyroot=$prefix;
8386: } elsif (defined($prefix)) {
8387: # prefix that is missing a part
8388: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8389: } else {
8390: # no prefix at all
8391: if (defined($part)) { $keyroot='_'.$part; }
8392: }
8393: return $keyroot;
8394: }
8395:
1.71 www 8396: # ---------------------------------------------------------------- Get metadata
8397:
1.599 albertel 8398: my %metaentry;
1.1070 www 8399: my %importedpartids;
1.71 www 8400: sub metadata {
1.176 www 8401: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8402: $uri=&declutter($uri);
1.288 albertel 8403: # if it is a non metadata possible uri return quickly
1.529 albertel 8404: if (($uri eq '') ||
8405: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8406: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 8407: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
8408: return undef;
8409: }
8410: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8411: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8412: return undef;
1.288 albertel 8413: }
1.73 www 8414: my $filename=$uri;
8415: $uri=~s/\.meta$//;
1.172 www 8416: #
8417: # Is the metadata already cached?
1.177 www 8418: # Look at timestamp of caching
1.172 www 8419: # Everything is cached by the main uri, libraries are never directly cached
8420: #
1.428 albertel 8421: if (!defined($liburi)) {
1.599 albertel 8422: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8423: if (defined($cached)) { return $result->{':'.$what}; }
8424: }
8425: {
1.1069 www 8426: # Imported parts would go here
1.1070 www 8427: my %importedids=();
8428: my @origfileimportpartids=();
1.1069 www 8429: my $importedparts=0;
1.172 www 8430: #
8431: # Is this a recursive call for a library?
8432: #
1.599 albertel 8433: # if (! exists($metacache{$uri})) {
8434: # $metacache{$uri}={};
8435: # }
1.924 albertel 8436: my $cachetime = 60*60;
1.171 www 8437: if ($liburi) {
8438: $liburi=&declutter($liburi);
8439: $filename=$liburi;
1.401 bowersj2 8440: } else {
1.599 albertel 8441: &devalidate_cache_new('meta',$uri);
8442: undef(%metaentry);
1.401 bowersj2 8443: }
1.140 www 8444: my %metathesekeys=();
1.73 www 8445: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8446: my $metastring;
1.924 albertel 8447: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8448: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8449: $metastring =
1.929 albertel 8450: &Apache::lonnet::ssi_body($which,
1.924 albertel 8451: ('grade_target' => 'meta'));
8452: $cachetime = 1; # only want this cached in the child not long term
8453: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8454: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8455: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8456: $metastring=&getfile($file);
1.489 albertel 8457: }
1.208 albertel 8458: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8459: my $token;
1.140 www 8460: undef %metathesekeys;
1.71 www 8461: while ($token=$parser->get_token) {
1.339 albertel 8462: if ($token->[0] eq 'S') {
8463: if (defined($token->[2]->{'package'})) {
1.172 www 8464: #
8465: # This is a package - get package info
8466: #
1.339 albertel 8467: my $package=$token->[2]->{'package'};
8468: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8469: if (defined($token->[2]->{'id'})) {
8470: $keyroot.='_'.$token->[2]->{'id'};
8471: }
1.599 albertel 8472: if ($metaentry{':packages'}) {
8473: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8474: } else {
1.599 albertel 8475: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8476: }
1.736 albertel 8477: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8478: my $part=$keyroot;
8479: $part=~s/^\_//;
1.736 albertel 8480: if ($pack_entry=~/^\Q$package\E\&/ ||
8481: $pack_entry=~/^\Q$package\E_0\&/) {
8482: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8483: # ignore package.tab specified default values
8484: # here &package_tab_default() will fetch those
8485: if ($subp eq 'default') { next; }
1.736 albertel 8486: my $value=$packagetab{$pack_entry};
1.432 albertel 8487: my $unikey;
8488: if ($pack =~ /_0$/) {
8489: $unikey='parameter_0_'.$name;
8490: $part=0;
8491: } else {
8492: $unikey='parameter'.$keyroot.'_'.$name;
8493: }
1.339 albertel 8494: if ($subp eq 'display') {
8495: $value.=' [Part: '.$part.']';
8496: }
1.599 albertel 8497: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8498: $metathesekeys{$unikey}=1;
1.599 albertel 8499: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8500: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8501: }
1.599 albertel 8502: if (defined($metaentry{':'.$unikey.'.default'})) {
8503: $metaentry{':'.$unikey}=
8504: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8505: }
1.339 albertel 8506: }
8507: }
8508: } else {
1.172 www 8509: #
8510: # This is not a package - some other kind of start tag
1.339 albertel 8511: #
8512: my $entry=$token->[1];
1.1068 www 8513: my $unikey='';
1.175 www 8514:
1.339 albertel 8515: if ($entry eq 'import') {
1.175 www 8516: #
8517: # Importing a library here
1.339 albertel 8518: #
1.1067 www 8519: my $location=$parser->get_text('/import');
8520: my $dir=$filename;
8521: $dir=~s|[^/]*$||;
8522: $location=&filelocation($dir,$location);
1.1069 www 8523:
1.1068 www 8524: my $importmode=$token->[2]->{'importmode'};
8525: if ($importmode eq 'problem') {
1.1069 www 8526: # Import as problem/response
1.1068 www 8527: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8528: } elsif ($importmode eq 'part') {
8529: # Import as part(s)
1.1069 www 8530: $importedparts=1;
8531: # We need to get the original file and the imported file to get the part order correct
8532: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
8533: # Load and inspect original file
1.1070 www 8534: if ($#origfileimportpartids<0) {
8535: undef(%importedpartids);
8536: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
8537: my $origfile=&getfile($origfilelocation);
8538: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8539: }
8540:
1.1069 www 8541: # Load and inspect imported file
8542: my $impfile=&getfile($location);
8543: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8544: if ($#impfilepartids>=0) {
8545: # This problem had parts
1.1070 www 8546: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 8547: } else {
8548: # Importing by turning a single problem into a problem part
8549: # It gets the import-tags ID as part-ID
8550: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 8551: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 8552: }
1.1068 www 8553: } else {
8554: # Normal import
8555: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8556: if (defined($token->[2]->{'id'})) {
8557: $unikey.='_'.$token->[2]->{'id'};
8558: }
1.1067 www 8559: }
8560:
1.339 albertel 8561: if ($depthcount<20) {
1.736 albertel 8562: my $metadata =
8563: &metadata($uri,'keys', $location,$unikey,
8564: $depthcount+1);
8565: foreach my $meta (split(',',$metadata)) {
8566: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8567: $metathesekeys{$meta}=1;
1.339 albertel 8568: }
1.1068 www 8569:
8570: }
1.1067 www 8571: } else {
8572: #
8573: # Not importing, some other kind of non-package, non-library start tag
8574: #
8575: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
8576: if (defined($token->[2]->{'id'})) {
8577: $unikey.='_'.$token->[2]->{'id'};
8578: }
1.339 albertel 8579: if (defined($token->[2]->{'name'})) {
8580: $unikey.='_'.$token->[2]->{'name'};
8581: }
8582: $metathesekeys{$unikey}=1;
1.736 albertel 8583: foreach my $param (@{$token->[3]}) {
8584: $metaentry{':'.$unikey.'.'.$param} =
8585: $token->[2]->{$param};
1.339 albertel 8586: }
8587: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8588: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8589: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8590: # only ws inside the tag, and not in default, so use default
8591: # as value
1.599 albertel 8592: $metaentry{':'.$unikey}=$default;
1.908 albertel 8593: } elsif ( $internaltext =~ /\S/ ) {
8594: # something interesting inside the tag
8595: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8596: } else {
1.908 albertel 8597: # no interesting values, don't set a default
1.339 albertel 8598: }
1.172 www 8599: # end of not-a-package not-a-library import
1.339 albertel 8600: }
1.172 www 8601: # end of not-a-package start tag
1.339 albertel 8602: }
1.172 www 8603: # the next is the end of "start tag"
1.339 albertel 8604: }
8605: }
1.483 albertel 8606: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8607: $extension = lc($extension);
8608: if ($extension eq 'htm') { $extension='html'; }
8609:
1.737 albertel 8610: foreach my $key (keys(%packagetab)) {
1.483 albertel 8611: #no specific packages #how's our extension
8612: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8613: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8614: \%metathesekeys);
8615: }
1.883 albertel 8616:
8617: if (!exists($metaentry{':packages'})
8618: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8619: foreach my $key (keys(%packagetab)) {
1.483 albertel 8620: #no specific packages well let's get default then
8621: if ($key!~/^default&/) { next; }
1.488 albertel 8622: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8623: \%metathesekeys);
8624: }
8625: }
1.338 www 8626: # are there custom rights to evaluate
1.599 albertel 8627: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8628:
1.338 www 8629: #
8630: # Importing a rights file here
1.339 albertel 8631: #
8632: unless ($depthcount) {
1.599 albertel 8633: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8634: my $dir=$filename;
8635: $dir=~s|[^/]*$||;
8636: $location=&filelocation($dir,$location);
1.736 albertel 8637: my $rights_metadata =
8638: &metadata($uri,'keys',$location,'_rights',
8639: $depthcount+1);
8640: foreach my $rights (split(',',$rights_metadata)) {
8641: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8642: $metathesekeys{$rights}=1;
1.339 albertel 8643: }
8644: }
8645: }
1.737 albertel 8646: # uniqifiy package listing
8647: my %seen;
8648: my @uniq_packages =
8649: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8650: $metaentry{':packages'} = join(',',@uniq_packages);
8651:
1.1070 www 8652: if ($importedparts) {
8653: # We had imported parts and need to rebuild partorder
8654: $metaentry{':partorder'}='';
8655: $metathesekeys{'partorder'}=1;
8656: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
8657: if ($origfileimportpartids[$index] eq 'part') {
8658: # original part, part of the problem
8659: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
8660: } else {
8661: # we have imported parts at this position
8662: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
8663: }
8664: }
8665: $metaentry{':partorder'}=~s/^\,//;
8666: }
8667:
1.737 albertel 8668: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8669: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8670: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8671: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8672: # this is the end of "was not already recently cached
1.71 www 8673: }
1.599 albertel 8674: return $metaentry{':'.$what};
1.261 albertel 8675: }
8676:
1.488 albertel 8677: sub metadata_create_package_def {
1.483 albertel 8678: my ($uri,$key,$package,$metathesekeys)=@_;
8679: my ($pack,$name,$subp)=split(/\&/,$key);
8680: if ($subp eq 'default') { next; }
8681:
1.599 albertel 8682: if (defined($metaentry{':packages'})) {
8683: $metaentry{':packages'}.=','.$package;
1.483 albertel 8684: } else {
1.599 albertel 8685: $metaentry{':packages'}=$package;
1.483 albertel 8686: }
8687: my $value=$packagetab{$key};
8688: my $unikey;
8689: $unikey='parameter_0_'.$name;
1.599 albertel 8690: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8691: $$metathesekeys{$unikey}=1;
1.599 albertel 8692: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8693: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8694: }
1.599 albertel 8695: if (defined($metaentry{':'.$unikey.'.default'})) {
8696: $metaentry{':'.$unikey}=
8697: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8698: }
8699: }
8700:
1.261 albertel 8701: sub metadata_generate_part0 {
8702: my ($metadata,$metacache,$uri) = @_;
8703: my %allnames;
1.737 albertel 8704: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8705: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8706: my $part=$$metacache{':'.$metakey.'.part'};
8707: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8708: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8709: $allnames{$name}=$part;
8710: }
8711: }
8712: }
8713: foreach my $name (keys(%allnames)) {
8714: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8715: my $key=":parameter_0_$name";
1.261 albertel 8716: $$metacache{"$key.part"}='0';
8717: $$metacache{"$key.name"}=$name;
1.428 albertel 8718: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8719: $allnames{$name}.'_'.$name.
8720: '.type'};
1.428 albertel 8721: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8722: '.display'};
1.644 www 8723: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8724: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8725: $$metacache{"$key.display"}=$olddis;
8726: }
1.71 www 8727: }
8728:
1.764 albertel 8729: # ------------------------------------------------------ Devalidate title cache
8730:
8731: sub devalidate_title_cache {
8732: my ($url)=@_;
8733: if (!$env{'request.course.id'}) { return; }
8734: my $symb=&symbread($url);
8735: if (!$symb) { return; }
8736: my $key=$env{'request.course.id'}."\0".$symb;
8737: &devalidate_cache_new('title',$key);
8738: }
8739:
1.1014 droeschl 8740: # ------------------------------------------------- Get the title of a course
8741:
8742: sub current_course_title {
8743: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8744: }
1.301 www 8745: # ------------------------------------------------- Get the title of a resource
8746:
8747: sub gettitle {
8748: my $urlsymb=shift;
8749: my $symb=&symbread($urlsymb);
1.534 albertel 8750: if ($symb) {
1.620 albertel 8751: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8752: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8753: if (defined($cached)) {
8754: return $result;
8755: }
1.534 albertel 8756: my ($map,$resid,$url)=&decode_symb($symb);
8757: my $title='';
1.907 albertel 8758: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8759: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8760: } else {
8761: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8762: &GDBM_READER(),0640)) {
8763: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8764: $title=$bighash{'title_'.$mapid.'.'.$resid};
8765: untie(%bighash);
8766: }
1.534 albertel 8767: }
8768: $title=~s/\&colon\;/\:/gs;
8769: if ($title) {
1.599 albertel 8770: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8771: }
8772: $urlsymb=$url;
8773: }
8774: my $title=&metadata($urlsymb,'title');
8775: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8776: return $title;
1.301 www 8777: }
1.613 albertel 8778:
1.614 albertel 8779: sub get_slot {
8780: my ($which,$cnum,$cdom)=@_;
8781: if (!$cnum || !$cdom) {
1.790 albertel 8782: (undef,my $courseid)=&whichuser();
1.620 albertel 8783: $cdom=$env{'course.'.$courseid.'.domain'};
8784: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8785: }
1.703 albertel 8786: my $key=join("\0",'slots',$cdom,$cnum,$which);
8787: my %slotinfo;
8788: if (exists($remembered{$key})) {
8789: $slotinfo{$which} = $remembered{$key};
8790: } else {
8791: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8792: &Apache::lonhomework::showhash(%slotinfo);
8793: my ($tmp)=keys(%slotinfo);
8794: if ($tmp=~/^error:/) { return (); }
8795: $remembered{$key} = $slotinfo{$which};
8796: }
1.616 albertel 8797: if (ref($slotinfo{$which}) eq 'HASH') {
8798: return %{$slotinfo{$which}};
8799: }
8800: return $slotinfo{$which};
1.614 albertel 8801: }
1.31 www 8802: # ------------------------------------------------- Update symbolic store links
8803:
8804: sub symblist {
8805: my ($mapname,%newhash)=@_;
1.438 www 8806: $mapname=&deversion(&declutter($mapname));
1.31 www 8807: my %hash;
1.620 albertel 8808: if (($env{'request.course.fn'}) && (%newhash)) {
8809: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8810: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8811: foreach my $url (keys(%newhash)) {
1.711 albertel 8812: next if ($url eq 'last_known'
8813: && $env{'form.no_update_last_known'});
8814: $hash{declutter($url)}=&encode_symb($mapname,
8815: $newhash{$url}->[1],
8816: $newhash{$url}->[0]);
1.191 harris41 8817: }
1.31 www 8818: if (untie(%hash)) {
8819: return 'ok';
8820: }
8821: }
8822: }
8823: return 'error';
1.212 www 8824: }
8825:
8826: # --------------------------------------------------------------- Verify a symb
8827:
8828: sub symbverify {
1.510 www 8829: my ($symb,$thisurl)=@_;
8830: my $thisfn=$thisurl;
1.439 www 8831: $thisfn=&declutter($thisfn);
1.215 www 8832: # direct jump to resource in page or to a sequence - will construct own symbs
8833: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8834: # check URL part
1.409 www 8835: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8836:
1.431 www 8837: unless ($url eq $thisfn) { return 0; }
1.213 www 8838:
1.216 www 8839: $symb=&symbclean($symb);
1.510 www 8840: $thisurl=&deversion($thisurl);
1.439 www 8841: $thisfn=&deversion($thisfn);
1.213 www 8842:
8843: my %bighash;
8844: my $okay=0;
1.431 www 8845:
1.620 albertel 8846: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8847: &GDBM_READER(),0640)) {
1.1032 raeburn 8848: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8849: $thisurl =~ s/\?.+$//;
8850: }
1.510 www 8851: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8852: unless ($ids) {
1.510 www 8853: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8854: }
8855: if ($ids) {
8856: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8857: foreach my $id (split(/\,/,$ids)) {
8858: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 8859: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8860: $symb =~ s/\?.+$//;
8861: }
1.216 www 8862: if (
8863: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8864: eq $symb) {
1.620 albertel 8865: if (($env{'request.role.adv'}) ||
1.800 albertel 8866: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8867: $okay=1;
8868: }
8869: }
1.216 www 8870: }
8871: }
1.213 www 8872: untie(%bighash);
8873: }
8874: return $okay;
1.31 www 8875: }
8876:
1.210 www 8877: # --------------------------------------------------------------- Clean-up symb
8878:
8879: sub symbclean {
8880: my $symb=shift;
1.568 albertel 8881: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8882: # remove version from map
8883: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8884:
1.210 www 8885: # remove version from URL
8886: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8887:
1.507 www 8888: # remove wrapper
8889:
1.510 www 8890: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8891: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8892: return $symb;
1.409 www 8893: }
8894:
8895: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8896:
8897: sub encode_symb {
8898: my ($map,$resid,$url)=@_;
8899: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8900: }
1.409 www 8901:
8902: sub decode_symb {
1.568 albertel 8903: my $symb=shift;
8904: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8905: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 8906: return (&fixversion($map),$resid,&fixversion($url));
8907: }
8908:
8909: sub fixversion {
8910: my $fn=shift;
1.609 banghart 8911: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 8912: my %bighash;
8913: my $uri=&clutter($fn);
1.620 albertel 8914: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 8915: # is this cached?
1.599 albertel 8916: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 8917: if (defined($cached)) { return $result; }
8918: # unfortunately not cached, or expired
1.620 albertel 8919: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 8920: &GDBM_READER(),0640)) {
8921: if ($bighash{'version_'.$uri}) {
8922: my $version=$bighash{'version_'.$uri};
1.444 www 8923: unless (($version eq 'mostrecent') ||
8924: ($version==&getversion($uri))) {
1.440 www 8925: $uri=~s/\.(\w+)$/\.$version\.$1/;
8926: }
8927: }
8928: untie %bighash;
1.413 www 8929: }
1.599 albertel 8930: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 8931: }
8932:
8933: sub deversion {
8934: my $url=shift;
8935: $url=~s/\.\d+\.(\w+)$/\.$1/;
8936: return $url;
1.210 www 8937: }
8938:
1.31 www 8939: # ------------------------------------------------------ Return symb list entry
8940:
8941: sub symbread {
1.249 www 8942: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 8943: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 8944: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 8945: # no filename provided? try from environment
1.44 www 8946: unless ($thisfn) {
1.620 albertel 8947: if ($env{'request.symb'}) {
8948: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 8949: }
1.620 albertel 8950: $thisfn=$env{'request.filename'};
1.44 www 8951: }
1.569 albertel 8952: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 8953: # is that filename actually a symb? Verify, clean, and return
8954: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 8955: if (&symbverify($thisfn,$1)) {
1.620 albertel 8956: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 8957: }
1.242 www 8958: }
1.44 www 8959: $thisfn=declutter($thisfn);
1.31 www 8960: my %hash;
1.37 www 8961: my %bighash;
8962: my $syval='';
1.620 albertel 8963: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 8964: my $targetfn = $thisfn;
1.609 banghart 8965: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 8966: $targetfn = 'adm/wrapper/'.$thisfn;
8967: }
1.687 albertel 8968: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8969: $targetfn=$1;
8970: }
1.620 albertel 8971: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8972: &GDBM_READER(),0640)) {
1.481 raeburn 8973: $syval=$hash{$targetfn};
1.37 www 8974: untie(%hash);
8975: }
8976: # ---------------------------------------------------------- There was an entry
8977: if ($syval) {
1.601 albertel 8978: #unless ($syval=~/\_\d+$/) {
1.620 albertel 8979: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 8980: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8981: #return $env{$cache_str}='';
1.601 albertel 8982: #}
8983: #$syval.=$1;
8984: #}
1.37 www 8985: } else {
8986: # ------------------------------------------------------- Was not in symb table
1.620 albertel 8987: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8988: &GDBM_READER(),0640)) {
1.37 www 8989: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 8990: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 8991: unless ($ids) {
8992: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 8993: }
8994: unless ($ids) {
8995: # alias?
8996: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 8997: }
1.37 www 8998: if ($ids) {
8999: # ------------------------------------------------------------------- Has ID(s)
9000: my @possibilities=split(/\,/,$ids);
1.39 www 9001: if ($#possibilities==0) {
9002: # ----------------------------------------------- There is only one possibility
1.37 www 9003: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9004: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9005: $resid,$thisfn);
1.249 www 9006: } elsif (!$donotrecurse) {
1.39 www 9007: # ------------------------------------------ There is more than one possibility
9008: my $realpossible=0;
1.800 albertel 9009: foreach my $id (@possibilities) {
9010: my $file=$bighash{'src_'.$id};
1.39 www 9011: if (&allowed('bre',$file)) {
1.800 albertel 9012: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9013: if ($bighash{'map_type_'.$mapid} ne 'page') {
9014: $realpossible++;
1.626 albertel 9015: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9016: $resid,$thisfn);
1.39 www 9017: }
9018: }
1.191 harris41 9019: }
1.39 www 9020: if ($realpossible!=1) { $syval=''; }
1.249 www 9021: } else {
9022: $syval='';
1.37 www 9023: }
9024: }
9025: untie(%bighash)
1.481 raeburn 9026: }
1.31 www 9027: }
1.62 www 9028: if ($syval) {
1.620 albertel 9029: return $env{$cache_str}=$syval;
1.62 www 9030: }
1.31 www 9031: }
1.949 raeburn 9032: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9033: return $env{$cache_str}='';
1.31 www 9034: }
9035:
9036: # ---------------------------------------------------------- Return random seed
9037:
1.32 www 9038: sub numval {
9039: my $txt=shift;
9040: $txt=~tr/A-J/0-9/;
9041: $txt=~tr/a-j/0-9/;
9042: $txt=~tr/K-T/0-9/;
9043: $txt=~tr/k-t/0-9/;
9044: $txt=~tr/U-Z/0-5/;
9045: $txt=~tr/u-z/0-5/;
9046: $txt=~s/\D//g;
1.564 albertel 9047: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9048: return int($txt);
1.368 albertel 9049: }
9050:
1.484 albertel 9051: sub numval2 {
9052: my $txt=shift;
9053: $txt=~tr/A-J/0-9/;
9054: $txt=~tr/a-j/0-9/;
9055: $txt=~tr/K-T/0-9/;
9056: $txt=~tr/k-t/0-9/;
9057: $txt=~tr/U-Z/0-5/;
9058: $txt=~tr/u-z/0-5/;
9059: $txt=~s/\D//g;
9060: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9061: my $total;
9062: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9063: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9064: return int($total);
9065: }
9066:
1.575 albertel 9067: sub numval3 {
9068: use integer;
9069: my $txt=shift;
9070: $txt=~tr/A-J/0-9/;
9071: $txt=~tr/a-j/0-9/;
9072: $txt=~tr/K-T/0-9/;
9073: $txt=~tr/k-t/0-9/;
9074: $txt=~tr/U-Z/0-5/;
9075: $txt=~tr/u-z/0-5/;
9076: $txt=~s/\D//g;
9077: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9078: my $total;
9079: foreach my $val (@txts) { $total+=$val; }
9080: if ($_64bit) { $total=(($total<<32)>>32); }
9081: return $total;
9082: }
9083:
1.675 albertel 9084: sub digest {
9085: my ($data)=@_;
9086: my $digest=&Digest::MD5::md5($data);
9087: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9088: my ($e,$f);
9089: {
9090: use integer;
9091: $e=($a+$b);
9092: $f=($c+$d);
9093: if ($_64bit) {
9094: $e=(($e<<32)>>32);
9095: $f=(($f<<32)>>32);
9096: }
9097: }
9098: if (wantarray) {
9099: return ($e,$f);
9100: } else {
9101: my $g;
9102: {
9103: use integer;
9104: $g=($e+$f);
9105: if ($_64bit) {
9106: $g=(($g<<32)>>32);
9107: }
9108: }
9109: return $g;
9110: }
9111: }
9112:
1.368 albertel 9113: sub latest_rnd_algorithm_id {
1.675 albertel 9114: return '64bit5';
1.366 albertel 9115: }
1.32 www 9116:
1.503 albertel 9117: sub get_rand_alg {
9118: my ($courseid)=@_;
1.790 albertel 9119: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9120: if ($courseid) {
1.620 albertel 9121: return $env{"course.$courseid.rndseed"};
1.503 albertel 9122: }
9123: return &latest_rnd_algorithm_id();
9124: }
9125:
1.562 albertel 9126: sub validCODE {
9127: my ($CODE)=@_;
9128: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9129: return 0;
9130: }
9131:
1.491 albertel 9132: sub getCODE {
1.620 albertel 9133: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9134: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9135: defined($Apache::lonhomework::parsing_a_task) ) &&
9136: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9137: return $Apache::lonhomework::history{'resource.CODE'};
9138: }
9139: return undef;
9140: }
9141:
1.31 www 9142: sub rndseed {
1.155 albertel 9143: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9144: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9145: if (!defined($symb)) {
1.366 albertel 9146: unless ($symb=$wsymb) { return time; }
9147: }
9148: if (!$courseid) { $courseid=$wcourseid; }
9149: if (!$domain) { $domain=$wdomain; }
9150: if (!$username) { $username=$wusername }
1.503 albertel 9151: my $which=&get_rand_alg();
1.803 albertel 9152:
1.491 albertel 9153: if (defined(&getCODE())) {
1.675 albertel 9154: if ($which eq '64bit5') {
9155: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9156: } elsif ($which eq '64bit4') {
1.575 albertel 9157: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9158: } else {
9159: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9160: }
1.675 albertel 9161: } elsif ($which eq '64bit5') {
9162: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9163: } elsif ($which eq '64bit4') {
9164: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9165: } elsif ($which eq '64bit3') {
9166: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9167: } elsif ($which eq '64bit2') {
9168: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9169: } elsif ($which eq '64bit') {
9170: return &rndseed_64bit($symb,$courseid,$domain,$username);
9171: }
9172: return &rndseed_32bit($symb,$courseid,$domain,$username);
9173: }
9174:
9175: sub rndseed_32bit {
9176: my ($symb,$courseid,$domain,$username)=@_;
9177: {
9178: use integer;
9179: my $symbchck=unpack("%32C*",$symb) << 27;
9180: my $symbseed=numval($symb) << 22;
9181: my $namechck=unpack("%32C*",$username) << 17;
9182: my $nameseed=numval($username) << 12;
9183: my $domainseed=unpack("%32C*",$domain) << 7;
9184: my $courseseed=unpack("%32C*",$courseid);
9185: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9186: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9187: #&logthis("rndseed :$num:$symb");
1.564 albertel 9188: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9189: return $num;
9190: }
9191: }
9192:
9193: sub rndseed_64bit {
9194: my ($symb,$courseid,$domain,$username)=@_;
9195: {
9196: use integer;
9197: my $symbchck=unpack("%32S*",$symb) << 21;
9198: my $symbseed=numval($symb) << 10;
9199: my $namechck=unpack("%32S*",$username);
9200:
9201: my $nameseed=numval($username) << 21;
9202: my $domainseed=unpack("%32S*",$domain) << 10;
9203: my $courseseed=unpack("%32S*",$courseid);
9204:
9205: my $num1=$symbchck+$symbseed+$namechck;
9206: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9207: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9208: #&logthis("rndseed :$num:$symb");
1.564 albertel 9209: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9210: return "$num1,$num2";
1.155 albertel 9211: }
1.366 albertel 9212: }
9213:
1.443 albertel 9214: sub rndseed_64bit2 {
9215: my ($symb,$courseid,$domain,$username)=@_;
9216: {
9217: use integer;
9218: # strings need to be an even # of cahracters long, it it is odd the
9219: # last characters gets thrown away
9220: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9221: my $symbseed=numval($symb) << 10;
9222: my $namechck=unpack("%32S*",$username.' ');
9223:
9224: my $nameseed=numval($username) << 21;
1.501 albertel 9225: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9226: my $courseseed=unpack("%32S*",$courseid.' ');
9227:
9228: my $num1=$symbchck+$symbseed+$namechck;
9229: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9230: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9231: #&logthis("rndseed :$num:$symb");
1.803 albertel 9232: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9233: return "$num1,$num2";
9234: }
9235: }
9236:
9237: sub rndseed_64bit3 {
9238: my ($symb,$courseid,$domain,$username)=@_;
9239: {
9240: use integer;
9241: # strings need to be an even # of cahracters long, it it is odd the
9242: # last characters gets thrown away
9243: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9244: my $symbseed=numval2($symb) << 10;
9245: my $namechck=unpack("%32S*",$username.' ');
9246:
9247: my $nameseed=numval2($username) << 21;
1.443 albertel 9248: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9249: my $courseseed=unpack("%32S*",$courseid.' ');
9250:
9251: my $num1=$symbchck+$symbseed+$namechck;
9252: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9253: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9254: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9255: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9256:
1.503 albertel 9257: return "$num1:$num2";
1.443 albertel 9258: }
9259: }
9260:
1.575 albertel 9261: sub rndseed_64bit4 {
9262: my ($symb,$courseid,$domain,$username)=@_;
9263: {
9264: use integer;
9265: # strings need to be an even # of cahracters long, it it is odd the
9266: # last characters gets thrown away
9267: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9268: my $symbseed=numval3($symb) << 10;
9269: my $namechck=unpack("%32S*",$username.' ');
9270:
9271: my $nameseed=numval3($username) << 21;
9272: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9273: my $courseseed=unpack("%32S*",$courseid.' ');
9274:
9275: my $num1=$symbchck+$symbseed+$namechck;
9276: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9277: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9278: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9279: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9280:
9281: return "$num1:$num2";
9282: }
9283: }
9284:
1.675 albertel 9285: sub rndseed_64bit5 {
9286: my ($symb,$courseid,$domain,$username)=@_;
9287: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9288: return "$num1:$num2";
9289: }
9290:
1.366 albertel 9291: sub rndseed_CODE_64bit {
9292: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9293: {
1.366 albertel 9294: use integer;
1.443 albertel 9295: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9296: my $symbseed=numval2($symb);
1.491 albertel 9297: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9298: my $CODEseed=numval(&getCODE());
1.443 albertel 9299: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9300: my $num1=$symbseed+$CODEchck;
9301: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9302: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9303: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9304: if ($_64bit) { $num1=(($num1<<32)>>32); }
9305: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9306: return "$num1:$num2";
1.366 albertel 9307: }
9308: }
9309:
1.575 albertel 9310: sub rndseed_CODE_64bit4 {
9311: my ($symb,$courseid,$domain,$username)=@_;
9312: {
9313: use integer;
9314: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9315: my $symbseed=numval3($symb);
9316: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9317: my $CODEseed=numval3(&getCODE());
9318: my $courseseed=unpack("%32S*",$courseid.' ');
9319: my $num1=$symbseed+$CODEchck;
9320: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9321: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9322: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9323: if ($_64bit) { $num1=(($num1<<32)>>32); }
9324: if ($_64bit) { $num2=(($num2<<32)>>32); }
9325: return "$num1:$num2";
9326: }
9327: }
9328:
1.675 albertel 9329: sub rndseed_CODE_64bit5 {
9330: my ($symb,$courseid,$domain,$username)=@_;
9331: my $code = &getCODE();
9332: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9333: return "$num1:$num2";
9334: }
9335:
1.366 albertel 9336: sub setup_random_from_rndseed {
9337: my ($rndseed)=@_;
1.503 albertel 9338: if ($rndseed =~/([,:])/) {
9339: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9340: &Math::Random::random_set_seed(abs($num1),abs($num2));
9341: } else {
9342: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9343: }
1.36 albertel 9344: }
9345:
1.474 albertel 9346: sub latest_receipt_algorithm_id {
1.835 albertel 9347: return 'receipt3';
1.474 albertel 9348: }
9349:
1.480 www 9350: sub recunique {
9351: my $fucourseid=shift;
9352: my $unique;
1.835 albertel 9353: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9354: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9355: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9356: } else {
9357: $unique=$perlvar{'lonReceipt'};
9358: }
9359: return unpack("%32C*",$unique);
9360: }
9361:
9362: sub recprefix {
9363: my $fucourseid=shift;
9364: my $prefix;
1.835 albertel 9365: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9366: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9367: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9368: } else {
9369: $prefix=$perlvar{'lonHostID'};
9370: }
9371: return unpack("%32C*",$prefix);
9372: }
9373:
1.76 www 9374: sub ireceipt {
1.474 albertel 9375: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9376:
9377: my $return =&recprefix($fucourseid).'-';
9378:
9379: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9380: $env{'request.state'} eq 'construct') {
9381: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9382: return $return;
9383: }
9384:
1.76 www 9385: my $cuname=unpack("%32C*",$funame);
9386: my $cudom=unpack("%32C*",$fudom);
9387: my $cucourseid=unpack("%32C*",$fucourseid);
9388: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9389: my $cunique=&recunique($fucourseid);
1.474 albertel 9390: my $cpart=unpack("%32S*",$part);
1.835 albertel 9391: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9392:
1.790 albertel 9393: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9394:
9395: $return.= ($cunique%$cuname+
9396: $cunique%$cudom+
9397: $cusymb%$cuname+
9398: $cusymb%$cudom+
9399: $cucourseid%$cuname+
9400: $cucourseid%$cudom+
9401: $cpart%$cuname+
9402: $cpart%$cudom);
9403: } else {
9404: $return.= ($cunique%$cuname+
9405: $cunique%$cudom+
9406: $cusymb%$cuname+
9407: $cusymb%$cudom+
9408: $cucourseid%$cuname+
9409: $cucourseid%$cudom);
9410: }
9411: return $return;
1.76 www 9412: }
9413:
9414: sub receipt {
1.474 albertel 9415: my ($part)=@_;
1.790 albertel 9416: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9417: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9418: }
1.260 ng 9419:
1.790 albertel 9420: sub whichuser {
9421: my ($passedsymb)=@_;
9422: my ($symb,$courseid,$domain,$name,$publicuser);
9423: if (defined($env{'form.grade_symb'})) {
9424: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9425: my $allowed=&allowed('vgr',$tmp_courseid);
9426: if (!$allowed &&
9427: exists($env{'request.course.sec'}) &&
9428: $env{'request.course.sec'} !~ /^\s*$/) {
9429: $allowed=&allowed('vgr',$tmp_courseid.
9430: '/'.$env{'request.course.sec'});
9431: }
9432: if ($allowed) {
9433: ($symb)=&get_env_multiple('form.grade_symb');
9434: $courseid=$tmp_courseid;
9435: ($domain)=&get_env_multiple('form.grade_domain');
9436: ($name)=&get_env_multiple('form.grade_username');
9437: return ($symb,$courseid,$domain,$name,$publicuser);
9438: }
9439: }
9440: if (!$passedsymb) {
9441: $symb=&symbread();
9442: } else {
9443: $symb=$passedsymb;
9444: }
9445: $courseid=$env{'request.course.id'};
9446: $domain=$env{'user.domain'};
9447: $name=$env{'user.name'};
9448: if ($name eq 'public' && $domain eq 'public') {
9449: if (!defined($env{'form.username'})) {
9450: $env{'form.username'}.=time.rand(10000000);
9451: }
9452: $name.=$env{'form.username'};
9453: }
9454: return ($symb,$courseid,$domain,$name,$publicuser);
9455:
9456: }
9457:
1.36 albertel 9458: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9459: # returns either the contents of the file or
9460: # -1 if the file doesn't exist
1.481 raeburn 9461: #
9462: # if the target is a file that was uploaded via DOCS,
9463: # a check will be made to see if a current copy exists on the local server,
9464: # if it does this will be served, otherwise a copy will be retrieved from
9465: # the home server for the course and stored in /home/httpd/html/userfiles on
9466: # the local server.
1.472 albertel 9467:
1.36 albertel 9468: sub getfile {
1.538 albertel 9469: my ($file) = @_;
1.609 banghart 9470: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9471: &repcopy($file);
9472: return &readfile($file);
9473: }
9474:
9475: sub repcopy_userfile {
9476: my ($file)=@_;
1.609 banghart 9477: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9478: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9479: my ($cdom,$cnum,$filename) =
1.811 albertel 9480: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9481: my $uri="/uploaded/$cdom/$cnum/$filename";
9482: if (-e "$file") {
1.828 www 9483: # we already have a local copy, check it out
1.538 albertel 9484: my @fileinfo = stat($file);
1.828 www 9485: my $rtncode;
9486: my $info;
1.538 albertel 9487: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9488: if ($lwpresp ne 'ok') {
1.828 www 9489: # there is no such file anymore, even though we had a local copy
1.482 albertel 9490: if ($rtncode eq '404') {
1.538 albertel 9491: unlink($file);
1.482 albertel 9492: }
9493: return -1;
9494: }
9495: if ($info < $fileinfo[9]) {
1.828 www 9496: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9497: return 'ok';
1.828 www 9498: } else {
9499: # the file is outdated, get rid of it
9500: unlink($file);
1.482 albertel 9501: }
1.828 www 9502: }
9503: # one way or the other, at this point, we don't have the file
9504: # construct the correct path for the file
9505: my @parts = ($cdom,$cnum);
9506: if ($filename =~ m|^(.+)/[^/]+$|) {
9507: push @parts, split(/\//,$1);
9508: }
9509: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9510: foreach my $part (@parts) {
9511: $path .= '/'.$part;
9512: if (!-e $path) {
9513: mkdir($path,0770);
1.482 albertel 9514: }
9515: }
1.828 www 9516: # now the path exists for sure
9517: # get a user agent
9518: my $ua=new LWP::UserAgent;
9519: my $transferfile=$file.'.in.transfer';
9520: # FIXME: this should flock
9521: if (-e $transferfile) { return 'ok'; }
9522: my $request;
9523: $uri=~s/^\///;
1.980 raeburn 9524: my $homeserver = &homeserver($cnum,$cdom);
9525: my $protocol = $protocol{$homeserver};
9526: $protocol = 'http' if ($protocol ne 'https');
9527: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9528: my $response=$ua->request($request,$transferfile);
9529: # did it work?
9530: if ($response->is_error()) {
9531: unlink($transferfile);
9532: &logthis("Userfile repcopy failed for $uri");
9533: return -1;
9534: }
9535: # worked, rename the transfer file
9536: rename($transferfile,$file);
1.607 raeburn 9537: return 'ok';
1.481 raeburn 9538: }
9539:
1.517 albertel 9540: sub tokenwrapper {
9541: my $uri=shift;
1.980 raeburn 9542: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9543: $uri=~s|^/||;
1.620 albertel 9544: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9545: my $token=$1;
1.552 albertel 9546: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9547: if ($udom && $uname && $file) {
9548: $file=~s|(\?\.*)*$||;
1.949 raeburn 9549: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9550: my $homeserver = &homeserver($uname,$udom);
9551: my $protocol = $protocol{$homeserver};
9552: $protocol = 'http' if ($protocol ne 'https');
9553: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9554: (($uri=~/\?/)?'&':'?').'token='.$token.
9555: '&tokenissued='.$perlvar{'lonHostID'};
9556: } else {
9557: return '/adm/notfound.html';
9558: }
9559: }
9560:
1.828 www 9561: # call with reqtype HEAD: get last modification time
9562: # call with reqtype GET: get the file contents
9563: # Do not call this with reqtype GET for large files! It loads everything into memory
9564: #
1.481 raeburn 9565: sub getuploaded {
9566: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9567: $uri=~s/^\///;
1.980 raeburn 9568: my $homeserver = &homeserver($cnum,$cdom);
9569: my $protocol = $protocol{$homeserver};
9570: $protocol = 'http' if ($protocol ne 'https');
9571: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9572: my $ua=new LWP::UserAgent;
9573: my $request=new HTTP::Request($reqtype,$uri);
9574: my $response=$ua->request($request);
9575: $$rtncode = $response->code;
1.482 albertel 9576: if (! $response->is_success()) {
9577: return 'failed';
9578: }
9579: if ($reqtype eq 'HEAD') {
1.486 www 9580: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9581: } elsif ($reqtype eq 'GET') {
9582: $$info = $response->content;
1.472 albertel 9583: }
1.482 albertel 9584: return 'ok';
1.36 albertel 9585: }
9586:
1.481 raeburn 9587: sub readfile {
9588: my $file = shift;
9589: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9590: my $fh;
9591: open($fh,"<$file");
9592: my $a='';
1.800 albertel 9593: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9594: return $a;
9595: }
9596:
1.36 albertel 9597: sub filelocation {
1.590 banghart 9598: my ($dir,$file) = @_;
9599: my $location;
9600: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9601:
9602: if ($file =~ m-^/adm/-) {
9603: $file=~s-^/adm/wrapper/-/-;
9604: $file=~s-^/adm/coursedocs/showdoc/-/-;
9605: }
1.882 albertel 9606:
1.590 banghart 9607: if ($file=~m:^/~:) { # is a contruction space reference
9608: $location = $file;
9609: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9610: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9611: # is a correct contruction space reference
9612: $location = $file;
1.956 raeburn 9613: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9614: $location = $file;
1.609 banghart 9615: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9616: my ($udom,$uname,$filename)=
1.811 albertel 9617: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9618: my $home=&homeserver($uname,$udom);
9619: my $is_me=0;
9620: my @ids=¤t_machine_ids();
9621: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9622: if ($is_me) {
1.955 raeburn 9623: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9624: } else {
9625: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9626: $udom.'/'.$uname.'/'.$filename;
9627: }
1.882 albertel 9628: } elsif ($file =~ m-^/adm/-) {
9629: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9630: } else {
9631: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9632: $file=~s:^/res/:/:;
9633: if ( !( $file =~ m:^/:) ) {
9634: $location = $dir. '/'.$file;
9635: } else {
9636: $location = '/home/httpd/html/res'.$file;
9637: }
1.59 albertel 9638: }
1.590 banghart 9639: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9640: while ($location=~m{/\.\./}) {
9641: if ($location =~ m{/[^/]+/\.\./}) {
9642: $location=~ s{/[^/]+/\.\./}{/}g;
9643: } else {
9644: $location=~ s{/\.\./}{/}g;
9645: }
9646: } #remove dir/..
1.590 banghart 9647: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9648: return $location;
1.46 www 9649: }
1.36 albertel 9650:
1.46 www 9651: sub hreflocation {
9652: my ($dir,$file)=@_;
1.980 raeburn 9653: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9654: $file=filelocation($dir,$file);
1.700 albertel 9655: } elsif ($file=~m-^/adm/-) {
9656: $file=~s-^/adm/wrapper/-/-;
9657: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9658: }
9659: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9660: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9661: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9662: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9663: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9664: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9665: -/uploaded/$1/$2/-x;
1.46 www 9666: }
1.913 albertel 9667: if ($file=~ m{^/userfiles/}) {
9668: $file =~ s{^/userfiles/}{/uploaded/};
9669: }
1.462 albertel 9670: return $file;
1.465 albertel 9671: }
9672:
9673: sub current_machine_domains {
1.853 albertel 9674: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9675: }
9676:
9677: sub machine_domains {
9678: my ($hostname) = @_;
1.465 albertel 9679: my @domains;
1.838 albertel 9680: my %hostname = &all_hostnames();
1.465 albertel 9681: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9682: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9683: if ($hostname eq $name) {
1.844 albertel 9684: push(@domains,&host_domain($id));
1.465 albertel 9685: }
9686: }
9687: return @domains;
9688: }
9689:
9690: sub current_machine_ids {
1.853 albertel 9691: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9692: }
9693:
9694: sub machine_ids {
9695: my ($hostname) = @_;
9696: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9697: my @ids;
1.888 albertel 9698: my %name_to_host = &all_names();
1.889 albertel 9699: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9700: return @{ $name_to_host{$hostname} };
9701: }
9702: return;
1.31 www 9703: }
9704:
1.824 raeburn 9705: sub additional_machine_domains {
9706: my @domains;
9707: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9708: while( my $line = <$fh>) {
9709: $line =~ s/\s//g;
9710: push(@domains,$line);
9711: }
9712: return @domains;
9713: }
9714:
9715: sub default_login_domain {
9716: my $domain = $perlvar{'lonDefDomain'};
9717: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9718: foreach my $posdom (¤t_machine_domains(),
9719: &additional_machine_domains()) {
9720: if (lc($posdom) eq lc($testdomain)) {
9721: $domain=$posdom;
9722: last;
9723: }
9724: }
9725: return $domain;
9726: }
9727:
1.31 www 9728: # ------------------------------------------------------------- Declutters URLs
9729:
9730: sub declutter {
9731: my $thisfn=shift;
1.569 albertel 9732: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9733: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9734: $thisfn=~s/^\///;
1.697 albertel 9735: $thisfn=~s|^adm/wrapper/||;
9736: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9737: $thisfn=~s/^res\///;
1.1032 raeburn 9738: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9739: $thisfn=~s/\?.+$//;
9740: }
1.268 www 9741: return $thisfn;
9742: }
9743:
9744: # ------------------------------------------------------------- Clutter up URLs
9745:
9746: sub clutter {
9747: my $thisfn='/'.&declutter(shift);
1.887 albertel 9748: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9749: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9750: $thisfn='/res'.$thisfn;
9751: }
1.1031 raeburn 9752: if ($thisfn !~m|^/adm|) {
9753: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9754: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9755: } else {
9756: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9757: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9758: if ($embstyle eq 'ssi'
9759: || ($embstyle eq 'hdn')
9760: || ($embstyle eq 'rat')
9761: || ($embstyle eq 'prv')
9762: || ($embstyle eq 'ign')) {
9763: #do nothing with these
9764: } elsif (($embstyle eq 'img')
1.695 albertel 9765: || ($embstyle eq 'emb')
9766: || ($embstyle eq 'wrp')) {
9767: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9768: } elsif ($embstyle eq 'unk'
9769: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9770: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9771: } else {
1.718 www 9772: # &logthis("Got a blank emb style");
1.695 albertel 9773: }
1.694 albertel 9774: }
9775: }
1.31 www 9776: return $thisfn;
1.12 www 9777: }
9778:
1.787 albertel 9779: sub clutter_with_no_wrapper {
9780: my $uri = &clutter(shift);
9781: if ($uri =~ m-^/adm/-) {
9782: $uri =~ s-^/adm/wrapper/-/-;
9783: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9784: }
9785: return $uri;
9786: }
9787:
1.557 albertel 9788: sub freeze_escape {
9789: my ($value)=@_;
9790: if (ref($value)) {
9791: $value=&nfreeze($value);
9792: return '__FROZEN__'.&escape($value);
9793: }
9794: return &escape($value);
9795: }
9796:
1.11 www 9797:
1.557 albertel 9798: sub thaw_unescape {
9799: my ($value)=@_;
9800: if ($value =~ /^__FROZEN__/) {
9801: substr($value,0,10,undef);
9802: $value=&unescape($value);
9803: return &thaw($value);
9804: }
9805: return &unescape($value);
9806: }
9807:
1.436 albertel 9808: sub correct_line_ends {
9809: my ($result)=@_;
9810: $$result =~s/\r\n/\n/mg;
9811: $$result =~s/\r/\n/mg;
1.415 albertel 9812: }
1.1 albertel 9813: # ================================================================ Main Program
9814:
1.184 www 9815: sub goodbye {
1.204 albertel 9816: &logthis("Starting Shut down");
1.443 albertel 9817: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9818: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9819: #converted
1.599 albertel 9820: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9821: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9822: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9823: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9824: #1.1 only
1.870 albertel 9825: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9826: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9827: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9828: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9829: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9830: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9831: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9832: &flushcourselogs();
9833: &logthis("Shutting down");
9834: }
9835:
1.852 albertel 9836: sub get_dns {
1.869 albertel 9837: my ($url,$func,$ignore_cache) = @_;
9838: if (!$ignore_cache) {
9839: my ($content,$cached)=
9840: &Apache::lonnet::is_cached_new('dns',$url);
9841: if ($cached) {
9842: &$func($content);
9843: return;
9844: }
9845: }
9846:
9847: my %alldns;
1.852 albertel 9848: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9849: foreach my $dns (<$config>) {
9850: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9851: my $line = $1;
9852: my ($host,$protocol) = split(/:/,$line);
9853: if ($protocol ne 'https') {
9854: $protocol = 'http';
9855: }
9856: $alldns{$host} = $protocol;
1.869 albertel 9857: }
9858: while (%alldns) {
9859: my ($dns) = keys(%alldns);
1.852 albertel 9860: my $ua=new LWP::UserAgent;
1.979 raeburn 9861: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9862: my $response=$ua->request($request);
1.979 raeburn 9863: delete($alldns{$dns});
1.852 albertel 9864: next if ($response->is_error());
9865: my @content = split("\n",$response->content);
1.869 albertel 9866: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9867: &$func(\@content);
1.869 albertel 9868: return;
1.852 albertel 9869: }
9870: close($config);
1.871 albertel 9871: my $which = (split('/',$url))[3];
9872: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9873: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9874: my @content = <$config>;
9875: &$func(\@content);
9876: return;
1.852 albertel 9877: }
1.327 albertel 9878: # ------------------------------------------------------------ Read domain file
9879: {
1.852 albertel 9880: my $loaded;
1.846 albertel 9881: my %domain;
9882:
1.852 albertel 9883: sub parse_domain_tab {
9884: my ($lines) = @_;
9885: foreach my $line (@$lines) {
9886: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9887:
1.846 albertel 9888: chomp($line);
1.852 albertel 9889: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9890: my %this_domain;
9891: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9892: 'lang_def', 'city', 'longi', 'lati',
9893: 'primary') {
9894: $this_domain{$field} = shift(@elements);
9895: }
9896: $domain{$name} = \%this_domain;
1.852 albertel 9897: }
9898: }
1.864 albertel 9899:
9900: sub reset_domain_info {
9901: undef($loaded);
9902: undef(%domain);
9903: }
9904:
1.852 albertel 9905: sub load_domain_tab {
1.869 albertel 9906: my ($ignore_cache) = @_;
9907: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 9908: my $fh;
9909: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9910: my @lines = <$fh>;
9911: &parse_domain_tab(\@lines);
1.448 albertel 9912: }
1.852 albertel 9913: close($fh);
9914: $loaded = 1;
1.327 albertel 9915: }
1.846 albertel 9916:
9917: sub domain {
1.852 albertel 9918: &load_domain_tab() if (!$loaded);
9919:
1.846 albertel 9920: my ($name,$what) = @_;
9921: return if ( !exists($domain{$name}) );
9922:
9923: if (!$what) {
9924: return $domain{$name}{'description'};
9925: }
9926: return $domain{$name}{$what};
9927: }
1.974 raeburn 9928:
9929: sub domain_info {
9930: &load_domain_tab() if (!$loaded);
9931: return %domain;
9932: }
9933:
1.327 albertel 9934: }
9935:
9936:
1.1 albertel 9937: # ------------------------------------------------------------- Read hosts file
9938: {
1.838 albertel 9939: my %hostname;
1.844 albertel 9940: my %hostdom;
1.845 albertel 9941: my %libserv;
1.852 albertel 9942: my $loaded;
1.888 albertel 9943: my %name_to_host;
1.1074 raeburn 9944: my %internetdom;
1.852 albertel 9945:
9946: sub parse_hosts_tab {
9947: my ($file) = @_;
9948: foreach my $configline (@$file) {
9949: next if ($configline =~ /^(\#|\s*$ )/x);
9950: next if ($configline =~ /^\^/);
9951: chomp($configline);
1.1074 raeburn 9952: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 9953: $name=~s/\s//g;
9954: if ($id && $domain && $role && $name) {
9955: $hostname{$id}=$name;
1.888 albertel 9956: push(@{$name_to_host{$name}}, $id);
1.852 albertel 9957: $hostdom{$id}=$domain;
9958: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 9959: if (defined($protocol)) {
9960: if ($protocol eq 'https') {
9961: $protocol{$id} = $protocol;
9962: } else {
9963: $protocol{$id} = 'http';
9964: }
1.968 raeburn 9965: } else {
1.969 raeburn 9966: $protocol{$id} = 'http';
1.968 raeburn 9967: }
1.1074 raeburn 9968: if (defined($intdom)) {
9969: $internetdom{$id} = $intdom;
9970: }
1.852 albertel 9971: }
9972: }
9973: }
1.864 albertel 9974:
9975: sub reset_hosts_info {
1.897 albertel 9976: &purge_remembered();
1.864 albertel 9977: &reset_domain_info();
9978: &reset_hosts_ip_info();
1.892 albertel 9979: undef(%name_to_host);
1.864 albertel 9980: undef(%hostname);
9981: undef(%hostdom);
9982: undef(%libserv);
9983: undef($loaded);
9984: }
1.1 albertel 9985:
1.852 albertel 9986: sub load_hosts_tab {
1.869 albertel 9987: my ($ignore_cache) = @_;
9988: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 9989: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9990: my @config = <$config>;
9991: &parse_hosts_tab(\@config);
9992: close($config);
9993: $loaded=1;
1.1 albertel 9994: }
1.852 albertel 9995:
1.838 albertel 9996: sub hostname {
1.852 albertel 9997: &load_hosts_tab() if (!$loaded);
9998:
1.838 albertel 9999: my ($lonid) = @_;
10000: return $hostname{$lonid};
10001: }
1.845 albertel 10002:
1.838 albertel 10003: sub all_hostnames {
1.852 albertel 10004: &load_hosts_tab() if (!$loaded);
10005:
1.838 albertel 10006: return %hostname;
10007: }
1.845 albertel 10008:
1.888 albertel 10009: sub all_names {
10010: &load_hosts_tab() if (!$loaded);
10011:
10012: return %name_to_host;
10013: }
10014:
1.974 raeburn 10015: sub all_host_domain {
10016: &load_hosts_tab() if (!$loaded);
10017: return %hostdom;
10018: }
10019:
1.845 albertel 10020: sub is_library {
1.852 albertel 10021: &load_hosts_tab() if (!$loaded);
10022:
1.845 albertel 10023: return exists($libserv{$_[0]});
10024: }
10025:
10026: sub all_library {
1.852 albertel 10027: &load_hosts_tab() if (!$loaded);
10028:
1.845 albertel 10029: return %libserv;
10030: }
10031:
1.1062 droeschl 10032: sub unique_library {
10033: #2x reverse removes all hostnames that appear more than once
10034: my %unique = reverse &all_library();
10035: return reverse %unique;
10036: }
10037:
1.841 albertel 10038: sub get_servers {
1.852 albertel 10039: &load_hosts_tab() if (!$loaded);
10040:
1.841 albertel 10041: my ($domain,$type) = @_;
10042: my %possible_hosts = ($type eq 'library') ? %libserv
10043: : %hostname;
10044: my %result;
1.842 albertel 10045: if (ref($domain) eq 'ARRAY') {
10046: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10047: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10048: $result{$host} = $hostname;
10049: }
10050: }
10051: } else {
10052: while ( my ($host,$hostname) = each(%possible_hosts)) {
10053: if ($hostdom{$host} eq $domain) {
10054: $result{$host} = $hostname;
10055: }
1.841 albertel 10056: }
10057: }
10058: return %result;
10059: }
1.845 albertel 10060:
1.1062 droeschl 10061: sub get_unique_servers {
10062: my %unique = reverse &get_servers(@_);
10063: return reverse %unique;
10064: }
10065:
1.844 albertel 10066: sub host_domain {
1.852 albertel 10067: &load_hosts_tab() if (!$loaded);
10068:
1.844 albertel 10069: my ($lonid) = @_;
10070: return $hostdom{$lonid};
10071: }
10072:
1.841 albertel 10073: sub all_domains {
1.852 albertel 10074: &load_hosts_tab() if (!$loaded);
10075:
1.841 albertel 10076: my %seen;
10077: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10078: return @uniq;
10079: }
1.1074 raeburn 10080:
10081: sub internet_dom {
10082: &load_hosts_tab() if (!$loaded);
10083:
10084: my ($lonid) = @_;
10085: return $internetdom{$lonid};
10086: }
1.1 albertel 10087: }
10088:
1.847 albertel 10089: {
10090: my %iphost;
1.856 albertel 10091: my %name_to_ip;
10092: my %lonid_to_ip;
1.869 albertel 10093:
1.847 albertel 10094: sub get_hosts_from_ip {
10095: my ($ip) = @_;
10096: my %iphosts = &get_iphost();
10097: if (ref($iphosts{$ip})) {
10098: return @{$iphosts{$ip}};
10099: }
10100: return;
1.839 albertel 10101: }
1.864 albertel 10102:
10103: sub reset_hosts_ip_info {
10104: undef(%iphost);
10105: undef(%name_to_ip);
10106: undef(%lonid_to_ip);
10107: }
1.856 albertel 10108:
10109: sub get_host_ip {
10110: my ($lonid) = @_;
10111: if (exists($lonid_to_ip{$lonid})) {
10112: return $lonid_to_ip{$lonid};
10113: }
10114: my $name=&hostname($lonid);
10115: my $ip = gethostbyname($name);
10116: return if (!$ip || length($ip) ne 4);
10117: $ip=inet_ntoa($ip);
10118: $name_to_ip{$name} = $ip;
10119: $lonid_to_ip{$lonid} = $ip;
10120: return $ip;
10121: }
1.847 albertel 10122:
10123: sub get_iphost {
1.869 albertel 10124: my ($ignore_cache) = @_;
1.894 albertel 10125:
1.869 albertel 10126: if (!$ignore_cache) {
10127: if (%iphost) {
10128: return %iphost;
10129: }
10130: my ($ip_info,$cached)=
10131: &Apache::lonnet::is_cached_new('iphost','iphost');
10132: if ($cached) {
10133: %iphost = %{$ip_info->[0]};
10134: %name_to_ip = %{$ip_info->[1]};
10135: %lonid_to_ip = %{$ip_info->[2]};
10136: return %iphost;
10137: }
10138: }
1.894 albertel 10139:
10140: # get yesterday's info for fallback
10141: my %old_name_to_ip;
10142: my ($ip_info,$cached)=
10143: &Apache::lonnet::is_cached_new('iphost','iphost');
10144: if ($cached) {
10145: %old_name_to_ip = %{$ip_info->[1]};
10146: }
10147:
1.888 albertel 10148: my %name_to_host = &all_names();
10149: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10150: my $ip;
10151: if (!exists($name_to_ip{$name})) {
10152: $ip = gethostbyname($name);
10153: if (!$ip || length($ip) ne 4) {
1.894 albertel 10154: if (defined($old_name_to_ip{$name})) {
10155: $ip = $old_name_to_ip{$name};
10156: &logthis("Can't find $name defaulting to old $ip");
10157: } else {
10158: &logthis("Name $name no IP found");
10159: next;
10160: }
10161: } else {
10162: $ip=inet_ntoa($ip);
1.847 albertel 10163: }
10164: $name_to_ip{$name} = $ip;
10165: } else {
10166: $ip = $name_to_ip{$name};
1.653 albertel 10167: }
1.888 albertel 10168: foreach my $id (@{ $name_to_host{$name} }) {
10169: $lonid_to_ip{$id} = $ip;
10170: }
10171: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10172: }
1.869 albertel 10173: &Apache::lonnet::do_cache_new('iphost','iphost',
10174: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10175: 48*60*60);
1.869 albertel 10176:
1.847 albertel 10177: return %iphost;
1.598 albertel 10178: }
10179:
1.992 raeburn 10180: #
10181: # Given a DNS returns the loncapa host name for that DNS
10182: #
10183: sub host_from_dns {
10184: my ($dns) = @_;
10185: my @hosts;
10186: my $ip;
10187:
1.993 raeburn 10188: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10189: $ip = $name_to_ip{$dns};
10190: }
10191: if (!$ip) {
10192: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10193: if (length($ip) == 4) {
10194: $ip = &IO::Socket::inet_ntoa($ip);
10195: }
10196: }
10197: if ($ip) {
10198: @hosts = get_hosts_from_ip($ip);
10199: return $hosts[0];
10200: }
10201: return undef;
1.986 foxr 10202: }
1.992 raeburn 10203:
1.1074 raeburn 10204: sub get_internet_names {
10205: my ($lonid) = @_;
10206: return if ($lonid eq '');
10207: my ($idnref,$cached)=
10208: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10209: if ($cached) {
10210: return $idnref;
10211: }
10212: my $ip = &get_host_ip($lonid);
10213: my @hosts = &get_hosts_from_ip($ip);
10214: my %iphost = &get_iphost();
10215: my (@idns,%seen);
10216: foreach my $id (@hosts) {
10217: my $dom = &host_domain($id);
10218: my $prim_id = &domain($dom,'primary');
10219: my $prim_ip = &get_host_ip($prim_id);
10220: next if ($seen{$prim_ip});
10221: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10222: foreach my $id (@{$iphost{$prim_ip}}) {
10223: my $intdom = &internet_dom($id);
10224: unless (grep(/^\Q$intdom\E$/,@idns)) {
10225: push(@idns,$intdom);
10226: }
10227: }
10228: }
10229: $seen{$prim_ip} = 1;
10230: }
10231: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10232: }
10233:
1.986 foxr 10234: }
10235:
1.1079 raeburn 10236: sub all_loncaparevs {
10237: 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);
10238: }
10239:
1.862 albertel 10240: BEGIN {
10241:
10242: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10243: unless ($readit) {
10244: {
10245: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10246: %perlvar = (%perlvar,%{$configvars});
10247: }
10248:
10249:
1.1 albertel 10250: # ------------------------------------------------------ Read spare server file
10251: {
1.448 albertel 10252: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10253:
10254: while (my $configline=<$config>) {
10255: chomp($configline);
1.284 matthew 10256: if ($configline) {
1.784 albertel 10257: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10258: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10259: push(@{ $spareid{$type} }, $host);
1.1 albertel 10260: }
10261: }
1.448 albertel 10262: close($config);
1.1 albertel 10263: }
1.11 www 10264: # ------------------------------------------------------------ Read permissions
10265: {
1.448 albertel 10266: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10267:
10268: while (my $configline=<$config>) {
1.448 albertel 10269: chomp($configline);
10270: if ($configline) {
10271: my ($role,$perm)=split(/ /,$configline);
10272: if ($perm ne '') { $pr{$role}=$perm; }
10273: }
1.11 www 10274: }
1.448 albertel 10275: close($config);
1.11 www 10276: }
10277:
10278: # -------------------------------------------- Read plain texts for permissions
10279: {
1.448 albertel 10280: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10281:
10282: while (my $configline=<$config>) {
1.448 albertel 10283: chomp($configline);
10284: if ($configline) {
1.742 raeburn 10285: my ($short,@plain)=split(/:/,$configline);
10286: %{$prp{$short}} = ();
10287: if (@plain > 0) {
10288: $prp{$short}{'std'} = $plain[0];
10289: for (my $i=1; $i<@plain; $i++) {
10290: $prp{$short}{'alt'.$i} = $plain[$i];
10291: }
10292: }
1.448 albertel 10293: }
1.135 www 10294: }
1.448 albertel 10295: close($config);
1.135 www 10296: }
10297:
10298: # ---------------------------------------------------------- Read package table
10299: {
1.448 albertel 10300: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10301:
10302: while (my $configline=<$config>) {
1.483 albertel 10303: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10304: chomp($configline);
10305: my ($short,$plain)=split(/:/,$configline);
10306: my ($pack,$name)=split(/\&/,$short);
10307: if ($plain ne '') {
10308: $packagetab{$pack.'&'.$name.'&name'}=$name;
10309: $packagetab{$short}=$plain;
10310: }
1.11 www 10311: }
1.448 albertel 10312: close($config);
1.329 matthew 10313: }
10314:
1.1073 raeburn 10315: # ---------------------------------------------------------- Read loncaparev table
10316: {
10317: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10318: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10319: while (my $configline=<$config>) {
10320: chomp($configline);
10321: my ($hostid,$loncaparev)=split(/:/,$configline);
10322: $loncaparevs{$hostid}=$loncaparev;
10323: }
10324: close($config);
10325: }
10326: }
10327: }
10328:
1.1074 raeburn 10329: # ---------------------------------------------------------- Read serverhostID table
10330: {
10331: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10332: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10333: while (my $configline=<$config>) {
10334: chomp($configline);
10335: my ($name,$id)=split(/:/,$configline);
10336: $serverhomeIDs{$name}=$id;
10337: }
10338: close($config);
10339: }
10340: }
10341: }
10342:
1.1079 raeburn 10343: {
10344: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10345: if (-e $file) {
10346: my $parser = HTML::LCParser->new($file);
10347: while (my $token = $parser->get_token()) {
10348: if ($token->[0] eq 'S') {
10349: my $item = $token->[1];
10350: my $name = $token->[2]{'name'};
10351: my $value = $token->[2]{'value'};
10352: if ($item ne '' && $name ne '' && $value ne '') {
10353: my $release = $parser->get_text();
10354: $release =~ s/(^\s*|\s*$ )//gx;
10355: $needsrelease{$item.':'.$name.':'.$value} = $release;
10356: }
10357: }
10358: }
10359: }
1.1073 raeburn 10360: }
10361:
1.329 matthew 10362: # ------------- set up temporary directory
10363: {
10364: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10365:
1.11 www 10366: }
10367:
1.794 albertel 10368: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10369: 'compress_threshold'=> 20_000,
10370: });
1.185 www 10371:
1.281 www 10372: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10373: $dumpcount=0;
1.958 www 10374: $locknum=0;
1.22 www 10375:
1.163 harris41 10376: &logtouch();
1.672 albertel 10377: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10378: $readit=1;
1.564 albertel 10379: {
10380: use integer;
10381: my $test=(2**32)+1;
1.568 albertel 10382: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10383: &logthis(" Detected 64bit platform ($_64bit)");
10384: }
1.195 www 10385: }
1.1 albertel 10386: }
1.179 www 10387:
1.1 albertel 10388: 1;
1.191 harris41 10389: __END__
10390:
1.243 albertel 10391: =pod
10392:
1.191 harris41 10393: =head1 NAME
10394:
1.243 albertel 10395: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10396:
10397: =head1 SYNOPSIS
10398:
1.243 albertel 10399: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10400:
10401: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10402:
1.243 albertel 10403: Common parameters:
10404:
10405: =over 4
10406:
10407: =item *
10408:
10409: $uname : an internal username (if $cname expecting a course Id specifically)
10410:
10411: =item *
10412:
10413: $udom : a domain (if $cdom expecting a course's domain specifically)
10414:
10415: =item *
10416:
10417: $symb : a resource instance identifier
10418:
10419: =item *
10420:
10421: $namespace : the name of a .db file that contains the data needed or
10422: being set.
10423:
10424: =back
10425:
1.394 bowersj2 10426: =head1 OVERVIEW
1.191 harris41 10427:
1.394 bowersj2 10428: lonnet provides subroutines which interact with the
10429: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10430: about classes, users, and resources.
1.243 albertel 10431:
10432: For many of these objects you can also use this to store data about
10433: them or modify them in various ways.
1.191 harris41 10434:
1.394 bowersj2 10435: =head2 Symbs
1.191 harris41 10436:
1.394 bowersj2 10437: To identify a specific instance of a resource, LON-CAPA uses symbols
10438: or "symbs"X<symb>. These identifiers are built from the URL of the
10439: map, the resource number of the resource in the map, and the URL of
10440: the resource itself. The latter is somewhat redundant, but might help
10441: if maps change.
10442:
10443: An example is
10444:
10445: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10446:
10447: The respective map entry is
10448:
10449: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10450: title="Problem 2">
10451: </resource>
10452:
10453: Symbs are used by the random number generator, as well as to store and
10454: restore data specific to a certain instance of for example a problem.
10455:
10456: =head2 Storing And Retrieving Data
10457:
10458: X<store()>X<cstore()>X<restore()>Three of the most important functions
10459: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10460: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10461: is is the non-critical message twin of cstore. These functions are for
10462: handlers to store a perl hash to a user's permanent data space in an
10463: easy manner, and to retrieve it again on another call. It is expected
10464: that a handler would use this once at the beginning to retrieve data,
10465: and then again once at the end to send only the new data back.
10466:
10467: The data is stored in the user's data directory on the user's
10468: homeserver under the ID of the course.
10469:
10470: The hash that is returned by restore will have all of the previous
10471: value for all of the elements of the hash.
10472:
10473: Example:
10474:
10475: #creating a hash
10476: my %hash;
10477: $hash{'foo'}='bar';
10478:
10479: #storing it
10480: &Apache::lonnet::cstore(\%hash);
10481:
10482: #changing a value
10483: $hash{'foo'}='notbar';
10484:
10485: #adding a new value
10486: $hash{'bar'}='foo';
10487: &Apache::lonnet::cstore(\%hash);
10488:
10489: #retrieving the hash
10490: my %history=&Apache::lonnet::restore();
10491:
10492: #print the hash
10493: foreach my $key (sort(keys(%history))) {
10494: print("\%history{$key} = $history{$key}");
10495: }
10496:
10497: Will print out:
1.191 harris41 10498:
1.394 bowersj2 10499: %history{1:foo} = bar
10500: %history{1:keys} = foo:timestamp
10501: %history{1:timestamp} = 990455579
10502: %history{2:bar} = foo
10503: %history{2:foo} = notbar
10504: %history{2:keys} = foo:bar:timestamp
10505: %history{2:timestamp} = 990455580
10506: %history{bar} = foo
10507: %history{foo} = notbar
10508: %history{timestamp} = 990455580
10509: %history{version} = 2
10510:
10511: Note that the special hash entries C<keys>, C<version> and
10512: C<timestamp> were added to the hash. C<version> will be equal to the
10513: total number of versions of the data that have been stored. The
10514: C<timestamp> attribute will be the UNIX time the hash was
10515: stored. C<keys> is available in every historical section to list which
10516: keys were added or changed at a specific historical revision of a
10517: hash.
10518:
10519: B<Warning>: do not store the hash that restore returns directly. This
10520: will cause a mess since it will restore the historical keys as if the
10521: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10522:
1.394 bowersj2 10523: Calling convention:
1.191 harris41 10524:
1.394 bowersj2 10525: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10526: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10527:
1.394 bowersj2 10528: For more detailed information, see lonnet specific documentation.
1.191 harris41 10529:
1.394 bowersj2 10530: =head1 RETURN MESSAGES
1.191 harris41 10531:
1.394 bowersj2 10532: =over 4
1.191 harris41 10533:
1.394 bowersj2 10534: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10535:
1.394 bowersj2 10536: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10537: when the connection is brought back up
1.191 harris41 10538:
1.394 bowersj2 10539: =item * B<con_failed>: unable to contact remote host and unable to save message
10540: for later delivery
1.191 harris41 10541:
1.967 bisitz 10542: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10543:
1.394 bowersj2 10544: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10545: that was requested
1.191 harris41 10546:
1.243 albertel 10547: =back
1.191 harris41 10548:
1.243 albertel 10549: =head1 PUBLIC SUBROUTINES
1.191 harris41 10550:
1.243 albertel 10551: =head2 Session Environment Functions
1.191 harris41 10552:
1.243 albertel 10553: =over 4
1.191 harris41 10554:
1.394 bowersj2 10555: =item *
10556: X<appenv()>
1.949 raeburn 10557: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10558: the user envirnoment file, and will be restored for each access this
1.620 albertel 10559: user makes during this session, also modifies the %env for the current
1.949 raeburn 10560: process. Optional rolesarrayref - if defined contains a reference to an array
10561: of roles which are exempt from the restriction on modifying user.role entries
10562: in the user's environment.db and in %env.
1.191 harris41 10563:
10564: =item *
1.394 bowersj2 10565: X<delenv()>
1.987 raeburn 10566: B<delenv($delthis,$regexp)>: removes all items from the session
10567: environment file that begin with $delthis. If the
10568: optional second arg - $regexp - is true, $delthis is treated as a
10569: regular expression, otherwise \Q$delthis\E is used.
10570: The values are also deleted from the current processes %env.
1.191 harris41 10571:
1.795 albertel 10572: =item * get_env_multiple($name)
10573:
10574: gets $name from the %env hash, it seemlessly handles the cases where multiple
10575: values may be defined and end up as an array ref.
10576:
10577: returns an array of values
10578:
1.243 albertel 10579: =back
10580:
10581: =head2 User Information
1.191 harris41 10582:
1.243 albertel 10583: =over 4
1.191 harris41 10584:
10585: =item *
1.394 bowersj2 10586: X<queryauthenticate()>
10587: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10588: authentication scheme
10589:
10590: =item *
1.394 bowersj2 10591: X<authenticate()>
1.1073 raeburn 10592: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 10593: authenticate user from domain's lib servers (first use the current
10594: one). C<$upass> should be the users password.
1.1073 raeburn 10595: $checkdefauth is optional (value is 1 if a check should be made to
10596: authenticate user using default authentication method, and allow
10597: account creation if username does not have account in the domain).
10598: $clientcancheckhost is optional (value is 1 if checking whether the
10599: server can host will occur on the client side in lonauth.pm).
1.191 harris41 10600:
10601: =item *
1.394 bowersj2 10602: X<homeserver()>
10603: B<homeserver($uname,$udom)>: find the server which has
10604: the user's directory and files (there must be only one), this caches
10605: the answer, and also caches if there is a borken connection.
1.191 harris41 10606:
10607: =item *
1.394 bowersj2 10608: X<idget()>
10609: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10610: (IDs are a unique resource in a domain, there must be only 1 ID per
10611: username, and only 1 username per ID in a specific domain) (returns
10612: hash: id=>name,id=>name)
1.191 harris41 10613:
10614: =item *
1.394 bowersj2 10615: X<idrget()>
10616: B<idrget($udom,@unames)>: find the IDs behind a list of
10617: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10618:
10619: =item *
1.394 bowersj2 10620: X<idput()>
10621: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10622:
10623: =item *
1.394 bowersj2 10624: X<rolesinit()>
10625: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10626:
10627: =item *
1.551 albertel 10628: X<getsection()>
10629: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10630: course $cname, return section name/number or '' for "not in course"
10631: and '-1' for "no section"
10632:
10633: =item *
1.394 bowersj2 10634: X<userenvironment()>
10635: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10636: passed in @what from the requested user's environment, returns a hash
10637:
1.858 raeburn 10638: =item *
10639: X<userlog_query()>
1.859 albertel 10640: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10641: activity.log file. %filters defines filters applied when parsing the
10642: log file. These can be start or end timestamps, or the type of action
10643: - log to look for Login or Logout events, check for Checkin or
10644: Checkout, role for role selection. The response is in the form
10645: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10646: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10647:
1.243 albertel 10648: =back
10649:
10650: =head2 User Roles
10651:
10652: =over 4
10653:
10654: =item *
10655:
1.810 raeburn 10656: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10657: F: full access
10658: U,I,K: authentication modes (cxx only)
10659: '': forbidden
10660: 1: user needs to choose course
10661: 2: browse allowed
1.766 albertel 10662: A: passphrase authentication needed
1.243 albertel 10663:
10664: =item *
10665:
10666: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10667: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10668: and course level
10669:
10670: =item *
10671:
1.988 raeburn 10672: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10673: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10674: $type is Course (default) or Community.
1.988 raeburn 10675: If $forcedefault evaluates to true, text returned will be default
10676: text for $type. Otherwise, if this is a course, the text returned
10677: will be a custom name for the role (if defined in the course's
10678: environment). If no custom name is defined the default is returned.
10679:
1.832 raeburn 10680: =item *
10681:
1.935 raeburn 10682: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10683: All arguments are optional. Returns a hash of a roles, either for
10684: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10685: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10686: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10687: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10688: For each key, value is set to colon-separated start and end times for
10689: the role. If no username and domain are specified, will default to
1.934 raeburn 10690: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10691: of role statuses (active, future or previous), roles
10692: (e.g., cc,in, st etc.) and domains of the roles which can be used
10693: to restrict the list of roles reported. If no array ref is
10694: provided for types, will default to return only active roles.
1.834 albertel 10695:
1.243 albertel 10696: =back
10697:
10698: =head2 User Modification
10699:
10700: =over 4
10701:
10702: =item *
10703:
1.957 raeburn 10704: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10705: user for the level given by URL. Optional start and end dates (leave empty
10706: string or zero for "no date")
1.191 harris41 10707:
10708: =item *
10709:
1.243 albertel 10710: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10711: change a users, password, possible return values are: ok,
10712: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10713: refused
1.191 harris41 10714:
10715: =item *
10716:
1.243 albertel 10717: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10718:
10719: =item *
10720:
1.1058 raeburn 10721: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10722: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10723:
10724: will update user information (firstname,middlename,lastname,generation,
10725: permanentemail), and if forceid is true, student/employee ID also.
10726: A user's institutional affiliation(s) can also be updated.
10727: User information fields will not be overwritten with empty entries
10728: unless the field is included in the $candelete array reference.
10729: This array is included when a single user is modified via "Manage Users",
10730: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10731:
10732: =item *
10733:
1.286 matthew 10734: modifystudent
10735:
1.957 raeburn 10736: modify a student's enrollment and identification information.
1.286 matthew 10737: The course id is resolved based on the current users environment.
10738: This means the envoking user must be a course coordinator or otherwise
10739: associated with a course.
10740:
1.297 matthew 10741: This call is essentially a wrapper for lonnet::modifyuser and
10742: lonnet::modify_student_enrollment
1.286 matthew 10743:
10744: Inputs:
10745:
10746: =over 4
10747:
1.957 raeburn 10748: =item B<$udom> Student's loncapa domain
1.286 matthew 10749:
1.957 raeburn 10750: =item B<$uname> Student's loncapa login name
1.286 matthew 10751:
1.964 bisitz 10752: =item B<$uid> Student/Employee ID
1.286 matthew 10753:
1.957 raeburn 10754: =item B<$umode> Student's authentication mode
1.286 matthew 10755:
1.957 raeburn 10756: =item B<$upass> Student's password
1.286 matthew 10757:
1.957 raeburn 10758: =item B<$first> Student's first name
1.286 matthew 10759:
1.957 raeburn 10760: =item B<$middle> Student's middle name
1.286 matthew 10761:
1.957 raeburn 10762: =item B<$last> Student's last name
1.286 matthew 10763:
1.957 raeburn 10764: =item B<$gene> Student's generation
1.286 matthew 10765:
1.957 raeburn 10766: =item B<$usec> Student's section in course
1.286 matthew 10767:
10768: =item B<$end> Unix time of the roles expiration
10769:
10770: =item B<$start> Unix time of the roles start date
10771:
10772: =item B<$forceid> If defined, allow $uid to be changed
10773:
10774: =item B<$desiredhome> server to use as home server for student
10775:
1.957 raeburn 10776: =item B<$email> Student's permanent e-mail address
10777:
10778: =item B<$type> Type of enrollment (auto or manual)
10779:
1.963 raeburn 10780: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10781:
10782: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10783:
1.963 raeburn 10784: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10785:
1.963 raeburn 10786: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10787:
1.963 raeburn 10788: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10789:
1.286 matthew 10790: =back
1.297 matthew 10791:
10792: =item *
10793:
10794: modify_student_enrollment
10795:
10796: Change a students enrollment status in a class. The environment variable
10797: 'role.request.course' must be defined for this function to proceed.
10798:
10799: Inputs:
10800:
10801: =over 4
10802:
10803: =item $udom, students domain
10804:
10805: =item $uname, students name
10806:
10807: =item $uid, students user id
10808:
10809: =item $first, students first name
10810:
10811: =item $middle
10812:
10813: =item $last
10814:
10815: =item $gene
10816:
10817: =item $usec
10818:
10819: =item $end
10820:
10821: =item $start
10822:
1.957 raeburn 10823: =item $type
10824:
10825: =item $locktype
10826:
10827: =item $cid
10828:
10829: =item $selfenroll
10830:
10831: =item $context
10832:
1.297 matthew 10833: =back
10834:
1.191 harris41 10835:
10836: =item *
10837:
1.243 albertel 10838: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10839: custom role; give a custom role to a user for the level given by URL. Specify
10840: name and domain of role author, and role name
1.191 harris41 10841:
10842: =item *
10843:
1.243 albertel 10844: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10845:
10846: =item *
10847:
1.243 albertel 10848: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10849:
10850: =back
10851:
10852: =head2 Course Infomation
10853:
10854: =over 4
1.191 harris41 10855:
10856: =item *
10857:
1.631 albertel 10858: coursedescription($courseid) : returns a hash of information about the
10859: specified course id, including all environment settings for the
10860: course, the description of the course will be in the hash under the
10861: key 'description'
1.191 harris41 10862:
10863: =item *
10864:
1.624 albertel 10865: resdata($name,$domain,$type,@which) : request for current parameter
10866: setting for a specific $type, where $type is either 'course' or 'user',
10867: @what should be a list of parameters to ask about. This routine caches
10868: answers for 5 minutes.
1.243 albertel 10869:
1.877 foxr 10870: =item *
10871:
10872: get_courseresdata($courseid, $domain) : dump the entire course resource
10873: data base, returning a hash that is keyed by the resource name and has
10874: values that are the resource value. I believe that the timestamps and
10875: versions are also returned.
10876:
10877:
1.243 albertel 10878: =back
10879:
10880: =head2 Course Modification
10881:
10882: =over 4
1.191 harris41 10883:
10884: =item *
10885:
1.243 albertel 10886: writecoursepref($courseid,%prefs) : write preferences (environment
10887: database) for a course
1.191 harris41 10888:
10889: =item *
10890:
1.1011 raeburn 10891: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10892:
10893: =item *
10894:
1.1038 raeburn 10895: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 10896:
10897: =back
10898:
10899: =head2 Resource Subroutines
10900:
10901: =over 4
1.191 harris41 10902:
10903: =item *
10904:
1.243 albertel 10905: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 10906:
10907: =item *
10908:
1.243 albertel 10909: repcopy($filename) : subscribes to the requested file, and attempts to
10910: replicate from the owning library server, Might return
1.607 raeburn 10911: 'unavailable', 'not_found', 'forbidden', 'ok', or
10912: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 10913: resource. Expects the local filesystem pathname
10914: (/home/httpd/html/res/....)
10915:
10916: =back
10917:
10918: =head2 Resource Information
10919:
10920: =over 4
1.191 harris41 10921:
10922: =item *
10923:
1.243 albertel 10924: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10925: a vairety of different possible values, $varname should be a request
10926: string, and the other parameters can be used to specify who and what
10927: one is asking about.
10928:
10929: Possible values for $varname are environment.lastname (or other item
10930: from the envirnment hash), user.name (or someother aspect about the
10931: user), resource.0.maxtries (or some other part and parameter of a
10932: resource)
1.204 albertel 10933:
10934: =item *
10935:
1.243 albertel 10936: directcondval($number) : get current value of a condition; reads from a state
10937: string
1.204 albertel 10938:
10939: =item *
10940:
1.243 albertel 10941: condval($condidx) : value of condition index based on state
1.204 albertel 10942:
10943: =item *
10944:
1.243 albertel 10945: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10946: resource's metadata, $what should be either a specific key, or either
10947: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10948: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10949:
10950: this function automatically caches all requests
1.191 harris41 10951:
10952: =item *
10953:
1.243 albertel 10954: metadata_query($query,$custom,$customshow) : make a metadata query against the
10955: network of library servers; returns file handle of where SQL and regex results
10956: will be stored for query
1.191 harris41 10957:
10958: =item *
10959:
1.243 albertel 10960: symbread($filename) : return symbolic list entry (filename argument optional);
10961: returns the data handle
1.191 harris41 10962:
10963: =item *
10964:
1.243 albertel 10965: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 10966: a possible symb for the URL in $thisfn, and if is an encryypted
10967: resource that the user accessed using /enc/ returns a 1 on success, 0
10968: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 10969: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 10970:
1.191 harris41 10971:
10972: =item *
10973:
1.243 albertel 10974: symbclean($symb) : removes versions numbers from a symb, returns the
10975: cleaned symb
1.191 harris41 10976:
10977: =item *
10978:
1.243 albertel 10979: is_on_map($uri) : checks if the $uri is somewhere on the current
10980: course map, user must be in a course for it to work.
1.191 harris41 10981:
10982: =item *
10983:
1.243 albertel 10984: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 10985:
10986: =item *
10987:
1.243 albertel 10988: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10989: a random seed, all arguments are optional, if they aren't sent it uses the
10990: environment to derive them. Note: if symb isn't sent and it can't get one
10991: from &symbread it will use the current time as its return value
1.191 harris41 10992:
10993: =item *
10994:
1.243 albertel 10995: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10996: unfakeable, receipt
1.191 harris41 10997:
10998: =item *
10999:
1.620 albertel 11000: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 11001:
11002: =item *
11003:
1.243 albertel 11004: countacc($url) : count the number of accesses to a given URL
1.191 harris41 11005:
11006: =item *
11007:
1.243 albertel 11008: 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 11009:
11010: =item *
11011:
1.243 albertel 11012: 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 11013:
11014: =item *
11015:
1.243 albertel 11016: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11017:
11018: =item *
11019:
1.243 albertel 11020: devalidate($symb) : devalidate temporary spreadsheet calculations,
11021: forcing spreadsheet to reevaluate the resource scores next time.
11022:
11023: =back
11024:
11025: =head2 Storing/Retreiving Data
11026:
11027: =over 4
1.191 harris41 11028:
11029: =item *
11030:
1.243 albertel 11031: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11032: for this url; hashref needs to be given and should be a \%hashname; the
11033: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11034: be derived from the env
1.191 harris41 11035:
11036: =item *
11037:
1.243 albertel 11038: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11039: uses critical subroutine
1.191 harris41 11040:
11041: =item *
11042:
1.243 albertel 11043: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11044: all args are optional
1.191 harris41 11045:
11046: =item *
11047:
1.717 albertel 11048: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11049: dumps the complete (or key matching regexp) namespace into a hash
11050: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11051: normally &store()ed into
11052:
11053: $range should be either an integer '100' (give me the first 100
11054: matching records)
11055: or be two integers sperated by a - with no spaces
11056: '30-50' (give me the 30th through the 50th matching
11057: records)
11058:
11059:
11060: =item *
11061:
11062: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11063: replaces a &store() version of data with a replacement set of data
11064: for a particular resource in a namespace passed in the $storehash hash
11065: reference
11066:
11067: =item *
11068:
1.243 albertel 11069: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11070: works very similar to store/cstore, but all data is stored in a
11071: temporary location and can be reset using tmpreset, $storehash should
11072: be a hash reference, returns nothing on success
1.191 harris41 11073:
11074: =item *
11075:
1.243 albertel 11076: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11077: similar to restore, but all data is stored in a temporary location and
11078: can be reset using tmpreset. Returns a hash of values on success,
11079: error string otherwise.
1.191 harris41 11080:
11081: =item *
11082:
1.243 albertel 11083: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11084: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11085:
11086: =item *
11087:
1.243 albertel 11088: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11089: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11090:
11091: =item *
11092:
1.243 albertel 11093: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11094: namesp ($udom and $uname are optional)
1.191 harris41 11095:
11096: =item *
11097:
1.702 albertel 11098: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11099: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11100: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11101:
1.702 albertel 11102: $range should be either an integer '100' (give me the first 100
11103: matching records)
11104: or be two integers sperated by a - with no spaces
11105: '30-50' (give me the 30th through the 50th matching
11106: records)
1.449 matthew 11107: =item *
11108:
11109: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11110: $store can be a scalar, an array reference, or if the amount to be
11111: incremented is > 1, a hash reference.
11112:
11113: ($udom and $uname are optional)
1.191 harris41 11114:
11115: =item *
11116:
1.243 albertel 11117: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11118: ($udom and $uname are optional)
1.191 harris41 11119:
11120: =item *
11121:
1.243 albertel 11122: cput($namespace,$storehash,$udom,$uname) : critical put
11123: ($udom and $uname are optional)
1.191 harris41 11124:
11125: =item *
11126:
1.748 albertel 11127: newput($namespace,$storehash,$udom,$uname) :
11128:
11129: Attempts to store the items in the $storehash, but only if they don't
11130: currently exist, if this succeeds you can be certain that you have
11131: successfully created a new key value pair in the $namespace db.
11132:
11133:
11134: Args:
11135: $namespace: name of database to store values to
11136: $storehash: hashref to store to the db
11137: $udom: (optional) domain of user containing the db
11138: $uname: (optional) name of user caontaining the db
11139:
11140: Returns:
11141: 'ok' -> succeeded in storing all keys of $storehash
11142: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11143: least <key> already existed in the db (other
11144: requested keys may also already exist)
1.967 bisitz 11145: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11146: 'con_lost' -> unable to contact request server
11147: 'refused' -> action was not allowed by remote machine
11148:
11149:
11150: =item *
11151:
1.243 albertel 11152: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11153: reference filled in from namesp (encrypts the return communication)
11154: ($udom and $uname are optional)
1.191 harris41 11155:
11156: =item *
11157:
1.243 albertel 11158: log($udom,$name,$home,$message) : write to permanent log for user; use
11159: critical subroutine
11160:
1.806 raeburn 11161: =item *
11162:
1.860 raeburn 11163: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11164: array reference filled in from namespace found in domain level on either
11165: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11166:
11167: =item *
11168:
1.860 raeburn 11169: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11170: domain level either on specified domain server ($uhome) or primary domain
11171: server ($udom and $uhome are optional)
1.806 raeburn 11172:
1.943 raeburn 11173: =item *
11174:
11175: get_domain_defaults($target_domain) : returns hash with defaults for
11176: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11177: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11178: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11179: Values are retrieved from cache (if current), or from domain's configuration.db
11180: (if available), or lastly from values in lonTabs/dns_domain,tab,
11181: or lonTabs/domain.tab.
11182:
11183: %domdefaults = &get_auth_defaults($target_domain);
11184:
1.243 albertel 11185: =back
11186:
11187: =head2 Network Status Functions
11188:
11189: =over 4
1.191 harris41 11190:
11191: =item *
11192:
11193: dirlist($uri) : return directory list based on URI
11194:
11195: =item *
11196:
1.243 albertel 11197: spareserver() : find server with least workload from spare.tab
11198:
1.986 foxr 11199:
11200: =item *
11201:
11202: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11203: if there is no corresponding loncapa host.
11204:
1.243 albertel 11205: =back
11206:
1.986 foxr 11207:
1.243 albertel 11208: =head2 Apache Request
11209:
11210: =over 4
1.191 harris41 11211:
11212: =item *
11213:
1.243 albertel 11214: ssi($url,%hash) : server side include, does a complete request cycle on url to
11215: localhost, posts hash
11216:
11217: =back
11218:
11219: =head2 Data to String to Data
11220:
11221: =over 4
1.191 harris41 11222:
11223: =item *
11224:
1.243 albertel 11225: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11226: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11227:
11228: =item *
11229:
1.243 albertel 11230: hashref2str($hashref) : convert a hashref into a string complete with
11231: escaping and '=' and '&' separators, supports elements that are
11232: arrayrefs and hashrefs
1.191 harris41 11233:
11234: =item *
11235:
1.243 albertel 11236: arrayref2str($arrayref) : convert an arrayref into a string complete
11237: with escaping and '&' separators, supports elements that are arrayrefs
11238: and hashrefs
1.191 harris41 11239:
11240: =item *
11241:
1.243 albertel 11242: str2hash($string) : convert string to hash using unescaping and
11243: splitting on '=' and '&', supports elements that are arrayrefs and
11244: hashrefs
1.191 harris41 11245:
11246: =item *
11247:
1.243 albertel 11248: str2array($string) : convert string to hash using unescaping and
11249: splitting on '&', supports elements that are arrayrefs and hashrefs
11250:
11251: =back
11252:
11253: =head2 Logging Routines
11254:
11255: =over 4
11256:
11257: These routines allow one to make log messages in the lonnet.log and
11258: lonnet.perm logfiles.
1.191 harris41 11259:
11260: =item *
11261:
1.243 albertel 11262: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11263:
11264: =item *
11265:
1.243 albertel 11266: logthis() : append message to the normal lonnet.log file, it gets
11267: preiodically rolled over and deleted.
1.191 harris41 11268:
11269: =item *
11270:
1.243 albertel 11271: logperm() : append a permanent message to lonnet.perm.log, this log
11272: file never gets deleted by any automated portion of the system, only
11273: messages of critical importance should go in here.
11274:
11275: =back
11276:
11277: =head2 General File Helper Routines
11278:
11279: =over 4
1.191 harris41 11280:
11281: =item *
11282:
1.481 raeburn 11283: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11284: (a) files in /uploaded
11285: (i) If a local copy of the file exists -
11286: compares modification date of local copy with last-modified date for
11287: definitive version stored on home server for course. If local copy is
11288: stale, requests a new version from the home server and stores it.
11289: If the original has been removed from the home server, then local copy
11290: is unlinked.
11291: (ii) If local copy does not exist -
11292: requests the file from the home server and stores it.
11293:
11294: If $caller is 'uploadrep':
11295: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11296: for request for files originally uploaded via DOCS.
11297: - returns 'ok' if fresh local copy now available, -1 otherwise.
11298:
11299: Otherwise:
11300: This indicates a call from the content generation phase of the request.
11301: - returns the entire contents of the file or -1.
11302:
11303: (b) files in /res
11304: - returns the entire contents of a file or -1;
11305: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11306:
1.712 albertel 11307:
11308: =item *
11309:
11310: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11311: reference
11312:
11313: returns either a stat() list of data about the file or an empty list
11314: if the file doesn't exist or couldn't find out about it (connection
11315: problems or user unknown)
11316:
1.191 harris41 11317: =item *
11318:
1.243 albertel 11319: filelocation($dir,$file) : returns file system location of a file
11320: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11321: directory that relative $file lookups are to looked in ($dir of /a/dir
11322: and a file of ../bob will become /a/bob)
1.191 harris41 11323:
11324: =item *
11325:
11326: hreflocation($dir,$file) : returns file system location or a URL; same as
11327: filelocation except for hrefs
11328:
11329: =item *
11330:
11331: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11332:
1.243 albertel 11333: =back
11334:
1.608 albertel 11335: =head2 Usererfile file routines (/uploaded*)
11336:
11337: =over 4
11338:
11339: =item *
11340:
11341: userfileupload(): main rotine for putting a file in a user or course's
11342: filespace, arguments are,
11343:
1.620 albertel 11344: formname - required - this is the name of the element in $env where the
1.608 albertel 11345: filename, and the contents of the file to create/modifed exist
1.620 albertel 11346: the filename is in $env{'form.'.$formname.'.filename'} and the
11347: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 11348: coursedoc - if true, store the file in the course of the active role
11349: of the current user
11350: subdir - required - subdirectory to put the file in under ../userfiles/
11351: if undefined, it will be placed in "unknown"
11352:
11353: (This routine calls clean_filename() to remove any dangerous
11354: characters from the filename, and then calls finuserfileupload() to
11355: complete the transaction)
11356:
11357: returns either the url of the uploaded file (/uploaded/....) if successful
11358: and /adm/notfound.html if unsuccessful
11359:
11360: =item *
11361:
11362: clean_filename(): routine for cleaing a filename up for storage in
11363: userfile space, argument is:
11364:
11365: filename - proposed filename
11366:
11367: returns: the new clean filename
11368:
11369: =item *
11370:
11371: finishuserfileupload(): routine that creaes and sends the file to
11372: userspace, probably shouldn't be called directly
11373:
11374: docuname: username or courseid of destination for the file
11375: docudom: domain of user/course of destination for the file
11376: formname: same as for userfileupload()
11377: fname: filename (inculding subdirectories) for the file
11378:
11379: returns either the url of the uploaded file (/uploaded/....) if successful
11380: and /adm/notfound.html if unsuccessful
11381:
11382: =item *
11383:
11384: renameuserfile(): renames an existing userfile to a new name
11385:
11386: Args:
11387: docuname: username or courseid of destination for the file
11388: docudom: domain of user/course of destination for the file
11389: old: current file name (including any subdirs under userfiles)
11390: new: desired file name (including any subdirs under userfiles)
11391:
11392: =item *
11393:
11394: mkdiruserfile(): creates a directory is a userfiles dir
11395:
11396: Args:
11397: docuname: username or courseid of destination for the file
11398: docudom: domain of user/course of destination for the file
11399: dir: dir to create (including any subdirs under userfiles)
11400:
11401: =item *
11402:
11403: removeuserfile(): removes a file that exists in userfiles
11404:
11405: Args:
11406: docuname: username or courseid of destination for the file
11407: docudom: domain of user/course of destination for the file
11408: fname: filname to delete (including any subdirs under userfiles)
11409:
11410: =item *
11411:
11412: removeuploadedurl(): convience function for removeuserfile()
11413:
11414: Args:
11415: url: a full /uploaded/... url to delete
11416:
1.747 albertel 11417: =item *
11418:
11419: get_portfile_permissions():
11420: Args:
11421: domain: domain of user or course contain the portfolio files
11422: user: name of user or num of course contain the portfolio files
11423: Returns:
11424: hashref of a dump of the proper file_permissions.db
11425:
11426:
11427: =item *
11428:
11429: get_access_controls():
11430:
11431: Args:
11432: current_permissions: the hash ref returned from get_portfile_permissions()
11433: group: (optional) the group you want the files associated with
11434: file: (optional) the file you want access info on
11435:
11436: Returns:
1.749 raeburn 11437: a hash (keys are file names) of hashes containing
11438: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11439: values are XML containing access control settings (see below)
1.747 albertel 11440:
11441: Internal notes:
11442:
1.749 raeburn 11443: access controls are stored in file_permissions.db as key=value pairs.
11444: key -> path to file/file_name\0uniqueID:scope_end_start
11445: where scope -> public,guest,course,group,domains or users.
11446: end -> UNIX time for end of access (0 -> no end date)
11447: start -> UNIX time for start of access
11448:
11449: value -> XML description of access control
11450: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11451: <start></start>
11452: <end></end>
11453:
11454: <password></password> for scope type = guest
11455:
11456: <domain></domain> for scope type = course or group
11457: <number></number>
11458: <roles id="">
11459: <role></role>
11460: <access></access>
11461: <section></section>
11462: <group></group>
11463: </roles>
11464:
11465: <dom></dom> for scope type = domains
11466:
11467: <users> for scope type = users
11468: <user>
11469: <uname></uname>
11470: <udom></udom>
11471: </user>
11472: </users>
11473: </scope>
11474:
11475: Access data is also aggregated for each file in an additional key=value pair:
11476: key -> path to file/file_name\0accesscontrol
11477: value -> reference to hash
11478: hash contains key = value pairs
11479: where key = uniqueID:scope_end_start
11480: value = UNIX time record was last updated
11481:
11482: Used to improve speed of look-ups of access controls for each file.
11483:
11484: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11485:
11486: modify_access_controls():
11487:
11488: Modifies access controls for a portfolio file
11489: Args
11490: 1. file name
11491: 2. reference to hash of required changes,
11492: 3. domain
11493: 4. username
11494: where domain,username are the domain of the portfolio owner
11495: (either a user or a course)
11496:
11497: Returns:
11498: 1. result of additions or updates ('ok' or 'error', with error message).
11499: 2. result of deletions ('ok' or 'error', with error message).
11500: 3. reference to hash of any new or updated access controls.
11501: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11502: key = integer (inbound ID)
11503: value = uniqueID
1.747 albertel 11504:
1.608 albertel 11505: =back
11506:
1.243 albertel 11507: =head2 HTTP Helper Routines
11508:
11509: =over 4
11510:
1.191 harris41 11511: =item *
11512:
11513: escape() : unpack non-word characters into CGI-compatible hex codes
11514:
11515: =item *
11516:
11517: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11518:
1.243 albertel 11519: =back
11520:
11521: =head1 PRIVATE SUBROUTINES
11522:
11523: =head2 Underlying communication routines (Shouldn't call)
11524:
11525: =over 4
11526:
11527: =item *
11528:
11529: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11530:
11531: =item *
11532:
11533: reply() : uses subreply to send a message to remote machine, logs all failures
11534:
11535: =item *
11536:
11537: critical() : passes a critical message to another server; if cannot
11538: get through then place message in connection buffer directory and
11539: returns con_delayed, if incapable of saving message, returns
11540: con_failed
11541:
11542: =item *
11543:
11544: reconlonc() : tries to reconnect lonc client processes.
11545:
11546: =back
11547:
11548: =head2 Resource Access Logging
11549:
11550: =over 4
11551:
11552: =item *
11553:
11554: flushcourselogs() : flush (save) buffer logs and access logs
11555:
11556: =item *
11557:
11558: courselog($what) : save message for course in hash
11559:
11560: =item *
11561:
11562: courseacclog($what) : save message for course using &courselog(). Perform
11563: special processing for specific resource types (problems, exams, quizzes, etc).
11564:
1.191 harris41 11565: =item *
11566:
11567: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11568: as a PerlChildExitHandler
1.243 albertel 11569:
11570: =back
11571:
11572: =head2 Other
11573:
11574: =over 4
11575:
11576: =item *
11577:
11578: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11579:
11580: =back
11581:
11582: =cut
1.877 foxr 11583:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>