Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1084
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1084 ! raeburn 4: # $Id: lonnet.pm,v 1.1083 2010/08/25 16:34:36 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.817 raeburn 1736: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1737: foreach my $key (keys(%roleshash)) {
1.479 albertel 1738: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1739: my $section=$1;
1740: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1741: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1742: my $now=time;
1.548 albertel 1743: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1744: $Expired{$end}=$section;
1745: next;
1746: }
1.548 albertel 1747: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1748: $Pending{$start}=$section;
1749: next;
1750: }
1.599 albertel 1751: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1752: }
1753: #
1754: # Presumedly there will be few matching roles from the above
1755: # loop and the sorting time will be negligible.
1756: if (scalar(keys(%Pending))) {
1757: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1758: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1759: }
1760: if (scalar(keys(%Expired))) {
1761: my @sorted = sort {$a <=> $b} keys(%Expired);
1762: my $time = pop(@sorted);
1.599 albertel 1763: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1764: }
1.599 albertel 1765: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1766: }
1.70 www 1767:
1.599 albertel 1768: sub save_cache {
1769: &purge_remembered();
1.722 albertel 1770: #&Apache::loncommon::validate_page();
1.620 albertel 1771: undef(%env);
1.780 albertel 1772: undef($env_loaded);
1.599 albertel 1773: }
1.452 albertel 1774:
1.599 albertel 1775: my $to_remember=-1;
1776: my %remembered;
1777: my %accessed;
1778: my $kicks=0;
1779: my $hits=0;
1.849 albertel 1780: sub make_key {
1781: my ($name,$id) = @_;
1.872 albertel 1782: if (length($id) > 65
1783: && length(&escape($id)) > 200) {
1784: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1785: }
1.849 albertel 1786: return &escape($name.':'.$id);
1787: }
1788:
1.599 albertel 1789: sub devalidate_cache_new {
1790: my ($name,$id,$debug) = @_;
1791: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1792: $id=&make_key($name,$id);
1.599 albertel 1793: $memcache->delete($id);
1794: delete($remembered{$id});
1795: delete($accessed{$id});
1796: }
1797:
1798: sub is_cached_new {
1799: my ($name,$id,$debug) = @_;
1.849 albertel 1800: $id=&make_key($name,$id);
1.599 albertel 1801: if (exists($remembered{$id})) {
1802: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1803: $accessed{$id}=[&gettimeofday()];
1804: $hits++;
1805: return ($remembered{$id},1);
1806: }
1807: my $value = $memcache->get($id);
1808: if (!(defined($value))) {
1809: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1810: return (undef,undef);
1.416 albertel 1811: }
1.599 albertel 1812: if ($value eq '__undef__') {
1813: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1814: $value=undef;
1815: }
1816: &make_room($id,$value,$debug);
1817: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1818: return ($value,1);
1819: }
1820:
1821: sub do_cache_new {
1822: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1823: $id=&make_key($name,$id);
1.599 albertel 1824: my $setvalue=$value;
1825: if (!defined($setvalue)) {
1826: $setvalue='__undef__';
1827: }
1.623 albertel 1828: if (!defined($time) ) {
1829: $time=600;
1830: }
1.599 albertel 1831: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1832: my $result = $memcache->set($id,$setvalue,$time);
1833: if (! $result) {
1.872 albertel 1834: &logthis("caching of id -> $id failed");
1.910 albertel 1835: $memcache->disconnect_all();
1.872 albertel 1836: }
1.600 albertel 1837: # need to make a copy of $value
1.919 albertel 1838: &make_room($id,$value,$debug);
1.599 albertel 1839: return $value;
1840: }
1841:
1842: sub make_room {
1843: my ($id,$value,$debug)=@_;
1.919 albertel 1844:
1845: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1846: : $value;
1.599 albertel 1847: if ($to_remember<0) { return; }
1848: $accessed{$id}=[&gettimeofday()];
1849: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1850: my $to_kick;
1851: my $max_time=0;
1852: foreach my $other (keys(%accessed)) {
1853: if (&tv_interval($accessed{$other}) > $max_time) {
1854: $to_kick=$other;
1855: $max_time=&tv_interval($accessed{$other});
1856: }
1857: }
1858: delete($remembered{$to_kick});
1859: delete($accessed{$to_kick});
1860: $kicks++;
1861: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1862: return;
1863: }
1864:
1.599 albertel 1865: sub purge_remembered {
1.604 albertel 1866: #&logthis("Tossing ".scalar(keys(%remembered)));
1867: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1868: undef(%remembered);
1869: undef(%accessed);
1.428 albertel 1870: }
1.70 www 1871: # ------------------------------------- Read an entry from a user's environment
1872:
1873: sub userenvironment {
1874: my ($udom,$unam,@what)=@_;
1.976 raeburn 1875: my $items;
1876: foreach my $item (@what) {
1877: $items.=&escape($item).'&';
1878: }
1879: $items=~s/\&$//;
1.70 www 1880: my %returnhash=();
1.1009 raeburn 1881: my $uhome = &homeserver($unam,$udom);
1882: unless ($uhome eq 'no_host') {
1883: my @answer=split(/\&/,
1884: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1885: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1886: return %returnhash;
1887: }
1.1009 raeburn 1888: my $i;
1889: for ($i=0;$i<=$#what;$i++) {
1890: $returnhash{$what[$i]}=&unescape($answer[$i]);
1891: }
1.70 www 1892: }
1893: return %returnhash;
1.1 albertel 1894: }
1895:
1.617 albertel 1896: # ---------------------------------------------------------- Get a studentphoto
1897: sub studentphoto {
1898: my ($udom,$unam,$ext) = @_;
1899: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1900: if (defined($env{'request.course.id'})) {
1.708 raeburn 1901: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1902: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1903: return(&retrievestudentphoto($udom,$unam,$ext));
1904: } else {
1905: my ($result,$perm_reqd)=
1.707 albertel 1906: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1907: if ($result eq 'ok') {
1908: if (!($perm_reqd eq 'yes')) {
1909: return(&retrievestudentphoto($udom,$unam,$ext));
1910: }
1911: }
1912: }
1913: }
1914: } else {
1915: my ($result,$perm_reqd) =
1.707 albertel 1916: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1917: if ($result eq 'ok') {
1918: if (!($perm_reqd eq 'yes')) {
1919: return(&retrievestudentphoto($udom,$unam,$ext));
1920: }
1921: }
1922: }
1923: return '/adm/lonKaputt/lonlogo_broken.gif';
1924: }
1925:
1926: sub retrievestudentphoto {
1927: my ($udom,$unam,$ext,$type) = @_;
1928: my $home=&Apache::lonnet::homeserver($unam,$udom);
1929: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1930: if ($ret eq 'ok') {
1931: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1932: if ($type eq 'thumbnail') {
1933: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1934: }
1935: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1936: return $tokenurl;
1937: } else {
1938: if ($type eq 'thumbnail') {
1939: return '/adm/lonKaputt/genericstudent_tn.gif';
1940: } else {
1941: return '/adm/lonKaputt/lonlogo_broken.gif';
1942: }
1.617 albertel 1943: }
1944: }
1945:
1.263 www 1946: # -------------------------------------------------------------------- New chat
1947:
1948: sub chatsend {
1.724 raeburn 1949: my ($newentry,$anon,$group)=@_;
1.620 albertel 1950: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1951: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1952: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1953: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1954: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1955: &escape($newentry)).':'.$group,$chome);
1.292 www 1956: }
1957:
1958: # ------------------------------------------ Find current version of a resource
1959:
1960: sub getversion {
1961: my $fname=&clutter(shift);
1962: unless ($fname=~/^\/res\//) { return -1; }
1963: return ¤tversion(&filelocation('',$fname));
1964: }
1965:
1966: sub currentversion {
1967: my $fname=shift;
1.599 albertel 1968: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1969: if (defined($cached)) { return $result; }
1.292 www 1970: my $author=$fname;
1971: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1972: my ($udom,$uname)=split(/\//,$author);
1973: my $home=homeserver($uname,$udom);
1974: if ($home eq 'no_host') {
1975: return -1;
1976: }
1977: my $answer=reply("currentversion:$fname",$home);
1978: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1979: return -1;
1980: }
1.599 albertel 1981: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1982: }
1983:
1.1 albertel 1984: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1985:
1.1 albertel 1986: sub subscribe {
1987: my $fname=shift;
1.761 raeburn 1988: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1989: $fname=~s/[\n\r]//g;
1.1 albertel 1990: my $author=$fname;
1991: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1992: my ($udom,$uname)=split(/\//,$author);
1993: my $home=homeserver($uname,$udom);
1.335 albertel 1994: if ($home eq 'no_host') {
1995: return 'not_found';
1.1 albertel 1996: }
1997: my $answer=reply("sub:$fname",$home);
1.64 www 1998: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1999: $answer.=' by '.$home;
2000: }
1.1 albertel 2001: return $answer;
2002: }
2003:
1.8 www 2004: # -------------------------------------------------------------- Replicate file
2005:
2006: sub repcopy {
2007: my $filename=shift;
1.23 www 2008: $filename=~s/\/+/\//g;
1.607 raeburn 2009: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2010: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2011: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2012: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2013: return &repcopy_userfile($filename);
2014: }
1.532 albertel 2015: $filename=~s/[\n\r]//g;
1.8 www 2016: my $transname="$filename.in.transfer";
1.828 www 2017: # FIXME: this should flock
1.607 raeburn 2018: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2019: my $remoteurl=subscribe($filename);
1.64 www 2020: if ($remoteurl =~ /^con_lost by/) {
2021: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2022: return 'unavailable';
1.8 www 2023: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2024: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2025: return 'not_found';
1.64 www 2026: } elsif ($remoteurl =~ /^rejected by/) {
2027: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2028: return 'forbidden';
1.20 www 2029: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2030: return 'ok';
1.8 www 2031: } else {
1.290 www 2032: my $author=$filename;
2033: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2034: my ($udom,$uname)=split(/\//,$author);
2035: my $home=homeserver($uname,$udom);
2036: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2037: my @parts=split(/\//,$filename);
2038: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2039: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2040: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2041: return 'bad_request';
1.8 www 2042: }
2043: my $count;
2044: for ($count=5;$count<$#parts;$count++) {
2045: $path.="/$parts[$count]";
2046: if ((-e $path)!=1) {
2047: mkdir($path,0777);
2048: }
2049: }
2050: my $ua=new LWP::UserAgent;
2051: my $request=new HTTP::Request('GET',"$remoteurl");
2052: my $response=$ua->request($request,$transname);
2053: if ($response->is_error()) {
2054: unlink($transname);
2055: my $message=$response->status_line;
1.672 albertel 2056: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2057: ." LWP get: $message: $filename</font>");
1.607 raeburn 2058: return 'unavailable';
1.8 www 2059: } else {
1.16 www 2060: if ($remoteurl!~/\.meta$/) {
2061: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2062: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2063: if ($mresponse->is_error()) {
2064: unlink($filename.'.meta');
2065: &logthis(
1.672 albertel 2066: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2067: }
2068: }
1.8 www 2069: rename($transname,$filename);
1.607 raeburn 2070: return 'ok';
1.8 www 2071: }
1.290 www 2072: }
1.8 www 2073: }
1.330 www 2074: }
2075:
2076: # ------------------------------------------------ Get server side include body
2077: sub ssi_body {
1.381 albertel 2078: my ($filelink,%form)=@_;
1.606 matthew 2079: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2080: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2081: }
1.953 www 2082: my $output='';
2083: my $response;
1.980 raeburn 2084: if ($filelink=~/^https?\:/) {
1.954 raeburn 2085: ($output,$response)=&externalssi($filelink);
1.953 www 2086: } else {
1.1004 droeschl 2087: $filelink .= $filelink=~/\?/ ? '&' : '?';
2088: $filelink .= 'inhibitmenu=yes';
1.953 www 2089: ($output,$response)=&ssi($filelink,%form);
2090: }
1.778 albertel 2091: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2092: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2093: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2094: if (wantarray) {
2095: return ($output, $response);
2096: } else {
2097: return $output;
2098: }
1.8 www 2099: }
2100:
1.15 www 2101: # --------------------------------------------------------- Server Side Include
2102:
1.782 albertel 2103: sub absolute_url {
2104: my ($host_name) = @_;
2105: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2106: if ($host_name eq '') {
2107: $host_name = $ENV{'SERVER_NAME'};
2108: }
2109: return $protocol.$host_name;
2110: }
2111:
1.942 foxr 2112: #
2113: # Server side include.
2114: # Parameters:
2115: # fn Possibly encrypted resource name/id.
2116: # form Hash that describes how the rendering should be done
2117: # and other things.
1.944 foxr 2118: # Returns:
1.950 raeburn 2119: # Scalar context: The content of the response.
2120: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2121: #
1.15 www 2122: sub ssi {
2123:
1.944 foxr 2124: my ($fn,%form)=@_;
1.15 www 2125: my $ua=new LWP::UserAgent;
1.23 www 2126: my $request;
1.711 albertel 2127:
2128: $form{'no_update_last_known'}=1;
1.895 albertel 2129: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2130: if (%form) {
1.782 albertel 2131: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2132: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2133: } else {
1.782 albertel 2134: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2135: }
2136:
1.15 www 2137: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2138: my $response=$ua->request($request);
2139:
1.944 foxr 2140: if (wantarray) {
2141: return ($response->content, $response);
2142: } else {
2143: return $response->content;
1.942 foxr 2144: }
1.324 www 2145: }
2146:
2147: sub externalssi {
2148: my ($url)=@_;
2149: my $ua=new LWP::UserAgent;
2150: my $request=new HTTP::Request('GET',$url);
2151: my $response=$ua->request($request);
1.954 raeburn 2152: if (wantarray) {
2153: return ($response->content, $response);
2154: } else {
2155: return $response->content;
2156: }
1.15 www 2157: }
1.254 www 2158:
1.492 albertel 2159: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2160:
2161: sub allowuploaded {
2162: my ($srcurl,$url)=@_;
2163: $url=&clutter(&declutter($url));
2164: my $dir=$url;
2165: $dir=~s/\/[^\/]+$//;
2166: my %httpref=();
2167: my $httpurl=&hreflocation('',$url);
2168: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2169: &Apache::lonnet::appenv(\%httpref);
1.254 www 2170: }
1.477 raeburn 2171:
1.478 albertel 2172: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2173: # input: action, courseID, current domain, intended
1.637 raeburn 2174: # path to file, source of file, instruction to parse file for objects,
2175: # ref to hash for embedded objects,
2176: # ref to hash for codebase of java objects.
2177: #
1.485 raeburn 2178: # output: url to file (if action was uploaddoc),
2179: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2180: #
1.478 albertel 2181: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2182: # course.
1.477 raeburn 2183: #
1.478 albertel 2184: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2185: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2186: # course's home server.
1.477 raeburn 2187: #
1.478 albertel 2188: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2189: # be copied from $source (current location) to
2190: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2191: # and will then be copied to
2192: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2193: # course's home server.
1.485 raeburn 2194: #
1.481 raeburn 2195: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2196: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2197: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2198: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2199: # in course's home server.
1.637 raeburn 2200: #
1.477 raeburn 2201:
2202: sub process_coursefile {
1.638 albertel 2203: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 2204: my $fetchresult;
1.638 albertel 2205: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2206: if ($action eq 'propagate') {
1.638 albertel 2207: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2208: $home);
1.481 raeburn 2209: } else {
1.477 raeburn 2210: my $fpath = '';
2211: my $fname = $file;
1.478 albertel 2212: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2213: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2214: my $filepath = &build_filepath($fpath);
1.481 raeburn 2215: if ($action eq 'copy') {
2216: if ($source eq '') {
2217: $fetchresult = 'no source file';
2218: return $fetchresult;
2219: } else {
2220: my $destination = $filepath.'/'.$fname;
2221: rename($source,$destination);
2222: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2223: $home);
1.481 raeburn 2224: }
2225: } elsif ($action eq 'uploaddoc') {
2226: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2227: print $fh $env{'form.'.$source};
1.481 raeburn 2228: close($fh);
1.637 raeburn 2229: if ($parser eq 'parse') {
1.1024 raeburn 2230: my $mm = new File::MMagic;
2231: my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
2232: if ($mime_type eq 'text/html') {
2233: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2234: unless ($parse_result eq 'ok') {
2235: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2236: }
1.637 raeburn 2237: }
2238: }
1.477 raeburn 2239: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2240: $home);
1.481 raeburn 2241: if ($fetchresult eq 'ok') {
2242: return '/uploaded/'.$fpath.'/'.$fname;
2243: } else {
2244: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2245: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2246: return '/adm/notfound.html';
2247: }
1.477 raeburn 2248: }
2249: }
1.485 raeburn 2250: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2251: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2252: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2253: }
2254: return $fetchresult;
2255: }
2256:
1.637 raeburn 2257: sub build_filepath {
2258: my ($fpath) = @_;
2259: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2260: unless ($fpath eq '') {
2261: my @parts=split('/',$fpath);
2262: foreach my $part (@parts) {
2263: $filepath.= '/'.$part;
2264: if ((-e $filepath)!=1) {
2265: mkdir($filepath,0777);
2266: }
2267: }
2268: }
2269: return $filepath;
2270: }
2271:
2272: sub store_edited_file {
1.638 albertel 2273: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2274: my $file = $primary_url;
2275: $file =~ s#^/uploaded/$docudom/$docuname/##;
2276: my $fpath = '';
2277: my $fname = $file;
2278: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2279: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2280: my $filepath = &build_filepath($fpath);
2281: open(my $fh,'>'.$filepath.'/'.$fname);
2282: print $fh $content;
2283: close($fh);
1.638 albertel 2284: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2285: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2286: $home);
1.637 raeburn 2287: if ($$fetchresult eq 'ok') {
2288: return '/uploaded/'.$fpath.'/'.$fname;
2289: } else {
1.638 albertel 2290: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2291: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2292: return '/adm/notfound.html';
2293: }
2294: }
2295:
1.531 albertel 2296: sub clean_filename {
1.831 albertel 2297: my ($fname,$args)=@_;
1.315 www 2298: # Replace Windows backslashes by forward slashes
1.257 www 2299: $fname=~s/\\/\//g;
1.831 albertel 2300: if (!$args->{'keep_path'}) {
2301: # Get rid of everything but the actual filename
2302: $fname=~s/^.*\/([^\/]+)$/$1/;
2303: }
1.315 www 2304: # Replace spaces by underscores
2305: $fname=~s/\s+/\_/g;
2306: # Replace all other weird characters by nothing
1.831 albertel 2307: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2308: # Replace all .\d. sequences with _\d. so they no longer look like version
2309: # numbers
2310: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2311: return $fname;
2312: }
1.1051 raeburn 2313: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2314: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2315: # image with the same aspect ratio as the original, but with dimensions which do
2316: # not exceed $resizewidth and $resizeheight.
2317:
1.984 neumanie 2318: sub resizeImage {
1.1051 raeburn 2319: my ($img_path,$resizewidth,$resizeheight) = @_;
2320: my $ima = Image::Magick->new;
2321: my $resized;
2322: if (-e $img_path) {
2323: $ima->Read($img_path);
2324: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2325: my $width = $ima->Get('width');
2326: my $height = $ima->Get('height');
2327: if ($width > $resizewidth) {
2328: my $factor = $width/$resizewidth;
2329: my $newheight = $height/$factor;
2330: $ima->Scale(width=>$resizewidth,height=>$newheight);
2331: $resized = 1;
2332: }
2333: }
2334: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2335: my $width = $ima->Get('width');
2336: my $height = $ima->Get('height');
2337: if ($height > $resizeheight) {
2338: my $factor = $height/$resizeheight;
2339: my $newwidth = $width/$factor;
2340: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2341: $resized = 1;
2342: }
2343: }
2344: if ($resized) {
2345: $ima->Write($img_path);
2346: }
2347: }
2348: return;
1.977 amueller 2349: }
2350:
1.608 albertel 2351: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2352: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2353: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2354: # $coursedoc - if true up to the current course
2355: # if false
2356: # $subdir - directory in userfile to store the file into
1.858 raeburn 2357: # $parser - instruction to parse file for objects ($parser = parse)
2358: # $allfiles - reference to hash for embedded objects
2359: # $codebase - reference to hash for codebase of java objects
2360: # $desuname - username for permanent storage of uploaded file
2361: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2362: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2363: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2364: # $resizewidth - width (pixels) to which to resize uploaded image
2365: # $resizeheight - height (pixels) to which to resize uploaded image
1.858 raeburn 2366: #
1.686 albertel 2367: # output: url of file in userspace, or error: <message>
2368: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2369:
1.531 albertel 2370: sub userfileupload {
1.860 raeburn 2371: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051 raeburn 2372: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531 albertel 2373: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2374: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2375: $fname=&clean_filename($fname);
1.315 www 2376: # See if there is anything left
1.257 www 2377: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2378: chop($env{'form.'.$formname});
1.523 raeburn 2379: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2380: my $now = time;
2381: my $filepath = 'tmp/helprequests/'.$now;
2382: my @parts=split(/\//,$filepath);
2383: my $fullpath = $perlvar{'lonDaemons'};
2384: for (my $i=0;$i<@parts;$i++) {
2385: $fullpath .= '/'.$parts[$i];
2386: if ((-e $fullpath)!=1) {
2387: mkdir($fullpath,0777);
2388: }
2389: }
2390: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2391: print $fh $env{'form.'.$formname};
1.523 raeburn 2392: close($fh);
1.741 raeburn 2393: return $fullpath.'/'.$fname;
2394: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2395: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2396: '_'.$env{'user.domain'}.'/pending';
2397: my @parts=split(/\//,$filepath);
2398: my $fullpath = $perlvar{'lonDaemons'};
2399: for (my $i=0;$i<@parts;$i++) {
2400: $fullpath .= '/'.$parts[$i];
2401: if ((-e $fullpath)!=1) {
2402: mkdir($fullpath,0777);
2403: }
2404: }
2405: open(my $fh,'>'.$fullpath.'/'.$fname);
2406: print $fh $env{'form.'.$formname};
2407: close($fh);
2408: return $fullpath.'/'.$fname;
1.523 raeburn 2409: }
1.995 raeburn 2410: if ($subdir eq 'scantron') {
2411: $fname = 'scantron_orig_'.$fname;
2412: } else {
1.258 www 2413: # Create the directory if not present
1.995 raeburn 2414: $fname="$subdir/$fname";
2415: }
1.259 www 2416: if ($coursedoc) {
1.638 albertel 2417: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2418: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2419: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2420: return &finishuserfileupload($docuname,$docudom,
2421: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2422: $codebase,$thumbwidth,$thumbheight,
2423: $resizewidth,$resizeheight);
1.481 raeburn 2424: } else {
1.620 albertel 2425: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2426: return &process_coursefile('uploaddoc',$docuname,$docudom,
2427: $fname,$formname,$parser,
2428: $allfiles,$codebase);
1.481 raeburn 2429: }
1.719 banghart 2430: } elsif (defined($destuname)) {
2431: my $docuname=$destuname;
2432: my $docudom=$destudom;
1.860 raeburn 2433: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2434: $parser,$allfiles,$codebase,
1.1051 raeburn 2435: $thumbwidth,$thumbheight,
2436: $resizewidth,$resizeheight);
1.719 banghart 2437:
1.259 www 2438: } else {
1.638 albertel 2439: my $docuname=$env{'user.name'};
2440: my $docudom=$env{'user.domain'};
1.714 raeburn 2441: if (exists($env{'form.group'})) {
2442: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2443: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2444: }
1.860 raeburn 2445: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2446: $parser,$allfiles,$codebase,
1.1051 raeburn 2447: $thumbwidth,$thumbheight,
2448: $resizewidth,$resizeheight);
1.259 www 2449: }
1.271 www 2450: }
2451:
2452: sub finishuserfileupload {
1.860 raeburn 2453: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051 raeburn 2454: $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477 raeburn 2455: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2456: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2457:
1.860 raeburn 2458: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2459: $file=$fname;
2460: if ($fname=~m|/|) {
2461: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2462: $path.=$fnamepath.'/';
2463: }
1.259 www 2464: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2465: my $count;
2466: for ($count=4;$count<=$#parts;$count++) {
2467: $filepath.="/$parts[$count]";
2468: if ((-e $filepath)!=1) {
2469: mkdir($filepath,0777);
2470: }
2471: }
1.984 neumanie 2472:
1.258 www 2473: # Save the file
2474: {
1.701 albertel 2475: if (!open(FH,'>'.$filepath.'/'.$file)) {
2476: &logthis('Failed to create '.$filepath.'/'.$file);
2477: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2478: return '/adm/notfound.html';
2479: }
2480: if (!print FH ($env{'form.'.$formname})) {
2481: &logthis('Failed to write to '.$filepath.'/'.$file);
2482: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2483: return '/adm/notfound.html';
2484: }
1.570 albertel 2485: close(FH);
1.1051 raeburn 2486: if ($resizewidth && $resizeheight) {
2487: my $mm = new File::MMagic;
2488: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2489: if ($mime_type =~ m{^image/}) {
2490: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2491: }
1.977 amueller 2492: }
1.258 www 2493: }
1.637 raeburn 2494: if ($parser eq 'parse') {
1.1024 raeburn 2495: my $mm = new File::MMagic;
2496: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2497: if ($mime_type eq 'text/html') {
2498: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2499: $allfiles,$codebase);
2500: unless ($parse_result eq 'ok') {
2501: &logthis('Failed to parse '.$filepath.$file.
2502: ' for embedded media: '.$parse_result);
2503: }
1.637 raeburn 2504: }
2505: }
1.860 raeburn 2506: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2507: my $input = $filepath.'/'.$file;
2508: my $output = $filepath.'/'.'tn-'.$file;
2509: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2510: system("convert -sample $thumbsize $input $output");
2511: if (-e $filepath.'/'.'tn-'.$file) {
2512: $fetchthumb = 1;
2513: }
2514: }
1.858 raeburn 2515:
1.259 www 2516: # Notify homeserver to grep it
2517: #
1.984 neumanie 2518: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2519: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2520: if ($fetchresult eq 'ok') {
1.860 raeburn 2521: if ($fetchthumb) {
2522: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2523: if ($thumbresult ne 'ok') {
2524: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2525: $docuhome.': '.$thumbresult);
2526: }
2527: }
1.259 www 2528: #
1.258 www 2529: # Return the URL to it
1.494 albertel 2530: return '/uploaded/'.$path.$file;
1.263 www 2531: } else {
1.494 albertel 2532: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2533: ': '.$fetchresult);
1.263 www 2534: return '/adm/notfound.html';
1.858 raeburn 2535: }
1.493 albertel 2536: }
2537:
1.637 raeburn 2538: sub extract_embedded_items {
1.961 raeburn 2539: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2540: my @state = ();
2541: my %javafiles = (
2542: codebase => '',
2543: code => '',
2544: archive => ''
2545: );
2546: my %mediafiles = (
2547: src => '',
2548: movie => '',
2549: );
1.648 raeburn 2550: my $p;
2551: if ($content) {
2552: $p = HTML::LCParser->new($content);
2553: } else {
1.961 raeburn 2554: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2555: }
1.641 albertel 2556: while (my $t=$p->get_token()) {
1.640 albertel 2557: if ($t->[0] eq 'S') {
2558: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2559: push(@state, $tagname);
1.648 raeburn 2560: if (lc($tagname) eq 'allow') {
2561: &add_filetype($allfiles,$attr->{'src'},'src');
2562: }
1.640 albertel 2563: if (lc($tagname) eq 'img') {
2564: &add_filetype($allfiles,$attr->{'src'},'src');
2565: }
1.886 albertel 2566: if (lc($tagname) eq 'a') {
2567: &add_filetype($allfiles,$attr->{'href'},'href');
2568: }
1.645 raeburn 2569: if (lc($tagname) eq 'script') {
2570: if ($attr->{'archive'} =~ /\.jar$/i) {
2571: &add_filetype($allfiles,$attr->{'archive'},'archive');
2572: } else {
2573: &add_filetype($allfiles,$attr->{'src'},'src');
2574: }
2575: }
2576: if (lc($tagname) eq 'link') {
2577: if (lc($attr->{'rel'}) eq 'stylesheet') {
2578: &add_filetype($allfiles,$attr->{'href'},'href');
2579: }
2580: }
1.640 albertel 2581: if (lc($tagname) eq 'object' ||
2582: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2583: foreach my $item (keys(%javafiles)) {
2584: $javafiles{$item} = '';
2585: }
2586: }
2587: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2588: my $name = lc($attr->{'name'});
2589: foreach my $item (keys(%javafiles)) {
2590: if ($name eq $item) {
2591: $javafiles{$item} = $attr->{'value'};
2592: last;
2593: }
2594: }
2595: foreach my $item (keys(%mediafiles)) {
2596: if ($name eq $item) {
2597: &add_filetype($allfiles, $attr->{'value'}, 'value');
2598: last;
2599: }
2600: }
2601: }
2602: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2603: foreach my $item (keys(%javafiles)) {
2604: if ($attr->{$item}) {
2605: $javafiles{$item} = $attr->{$item};
2606: last;
2607: }
2608: }
2609: foreach my $item (keys(%mediafiles)) {
2610: if ($attr->{$item}) {
2611: &add_filetype($allfiles,$attr->{$item},$item);
2612: last;
2613: }
2614: }
2615: }
2616: } elsif ($t->[0] eq 'E') {
2617: my ($tagname) = ($t->[1]);
2618: if ($javafiles{'codebase'} ne '') {
2619: $javafiles{'codebase'} .= '/';
2620: }
2621: if (lc($tagname) eq 'applet' ||
2622: lc($tagname) eq 'object' ||
2623: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2624: ) {
2625: foreach my $item (keys(%javafiles)) {
2626: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2627: my $file=$javafiles{'codebase'}.$javafiles{$item};
2628: &add_filetype($allfiles,$file,$item);
2629: }
2630: }
2631: }
2632: pop @state;
2633: }
2634: }
1.637 raeburn 2635: return 'ok';
2636: }
2637:
1.639 albertel 2638: sub add_filetype {
2639: my ($allfiles,$file,$type)=@_;
2640: if (exists($allfiles->{$file})) {
2641: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2642: push(@{$allfiles->{$file}}, &escape($type));
2643: }
2644: } else {
2645: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2646: }
2647: }
2648:
1.493 albertel 2649: sub removeuploadedurl {
1.984 neumanie 2650: my ($url)=@_;
2651: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2652: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2653: }
2654:
2655: sub removeuserfile {
2656: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2657: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2658: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2659: if ($result eq 'ok') {
1.798 raeburn 2660: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2661: my $metafile = $fname.'.meta';
2662: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2663: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2664: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2665: my $sqlresult =
1.823 albertel 2666: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2667: 'portfolio_metadata',$group,
2668: 'delete');
1.798 raeburn 2669: }
2670: }
2671: return $result;
1.257 www 2672: }
1.15 www 2673:
1.530 albertel 2674: sub mkdiruserfile {
2675: my ($docuname,$docudom,$dir)=@_;
2676: my $home=&homeserver($docuname,$docudom);
2677: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2678: }
2679:
1.531 albertel 2680: sub renameuserfile {
2681: my ($docuname,$docudom,$old,$new)=@_;
2682: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2683: my $result = &reply("renameuserfile:$docudom:$docuname:".
2684: &escape("$old").':'.&escape("$new"),$home);
2685: if ($result eq 'ok') {
2686: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2687: my $oldmeta = $old.'.meta';
2688: my $newmeta = $new.'.meta';
2689: my $metaresult =
2690: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2691: my $url = "/uploaded/$docudom/$docuname/$old";
2692: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2693: my $sqlresult =
1.823 albertel 2694: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2695: 'portfolio_metadata',$group,
2696: 'delete');
1.798 raeburn 2697: }
2698: }
2699: return $result;
1.531 albertel 2700: }
2701:
1.14 www 2702: # ------------------------------------------------------------------------- Log
2703:
2704: sub log {
2705: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2706: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2707: }
2708:
2709: # ------------------------------------------------------------------ Course Log
1.352 www 2710: #
2711: # This routine flushes several buffers of non-mission-critical nature
2712: #
1.157 www 2713:
2714: sub flushcourselogs {
1.352 www 2715: &logthis('Flushing log buffers');
2716: #
2717: # course logs
2718: # This is a log of all transactions in a course, which can be used
2719: # for data mining purposes
2720: #
2721: # It also collects the courseid database, which lists last transaction
2722: # times and course titles for all courseids
2723: #
2724: my %courseidbuffer=();
1.921 raeburn 2725: foreach my $crsid (keys(%courselogs)) {
1.352 www 2726: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2727: &escape($courselogs{$crsid}),
2728: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2729: delete $courselogs{$crsid};
2730: } else {
2731: &logthis('Failed to flush log buffer for '.$crsid);
2732: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2733: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2734: " exceeded maximum size, deleting.</font>");
2735: delete $courselogs{$crsid};
2736: }
1.352 www 2737: }
1.920 raeburn 2738: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2739: 'description' => $coursedescrbuf{$crsid},
2740: 'inst_code' => $courseinstcodebuf{$crsid},
2741: 'type' => $coursetypebuf{$crsid},
2742: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2743: };
1.191 harris41 2744: }
1.352 www 2745: #
2746: # Write course id database (reverse lookup) to homeserver of courses
2747: # Is used in pickcourse
2748: #
1.840 albertel 2749: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2750: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2751: $courseidbuffer{$crs_home},
2752: $crs_home,'timeonly');
1.352 www 2753: }
2754: #
2755: # File accesses
2756: # Writes to the dynamic metadata of resources to get hit counts, etc.
2757: #
1.449 matthew 2758: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2759: if ($entry =~ /___count$/) {
2760: my ($dom,$name);
1.807 albertel 2761: ($dom,$name,undef)=
1.811 albertel 2762: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2763: if (! defined($dom) || $dom eq '' ||
2764: ! defined($name) || $name eq '') {
1.620 albertel 2765: my $cid = $env{'request.course.id'};
2766: $dom = $env{'request.'.$cid.'.domain'};
2767: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2768: }
1.450 matthew 2769: my $value = $accesshash{$entry};
2770: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2771: my %temphash=($url => $value);
1.449 matthew 2772: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2773: if ($result eq 'ok') {
2774: delete $accesshash{$entry};
2775: } elsif ($result eq 'unknown_cmd') {
2776: # Target server has old code running on it.
1.450 matthew 2777: my %temphash=($entry => $value);
1.449 matthew 2778: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2779: delete $accesshash{$entry};
2780: }
2781: }
2782: } else {
1.811 albertel 2783: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2784: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2785: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2786: delete $accesshash{$entry};
2787: }
1.185 www 2788: }
1.191 harris41 2789: }
1.352 www 2790: #
2791: # Roles
2792: # Reverse lookup of user roles for course faculty/staff and co-authorship
2793: #
1.800 albertel 2794: foreach my $entry (keys(%userrolehash)) {
1.351 www 2795: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2796: split(/\:/,$entry);
2797: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2798: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2799: $rudom,$runame) eq 'ok') {
2800: delete $userrolehash{$entry};
2801: }
2802: }
1.662 raeburn 2803: #
2804: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2805: #
2806: my %domrolebuffer = ();
1.1000 raeburn 2807: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2808: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2809: if ($domrolebuffer{$rudom}) {
2810: $domrolebuffer{$rudom}.='&'.&escape($entry).
2811: '='.&escape($domainrolehash{$entry});
2812: } else {
2813: $domrolebuffer{$rudom}.=&escape($entry).
2814: '='.&escape($domainrolehash{$entry});
2815: }
2816: delete $domainrolehash{$entry};
2817: }
2818: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2819: my %servers = &get_servers($dom,'library');
2820: foreach my $tryserver (keys(%servers)) {
2821: unless (&reply('domroleput:'.$dom.':'.
2822: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2823: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2824: }
1.662 raeburn 2825: }
2826: }
1.186 www 2827: $dumpcount++;
1.157 www 2828: }
2829:
2830: sub courselog {
2831: my $what=shift;
1.158 www 2832: $what=time.':'.$what;
1.620 albertel 2833: unless ($env{'request.course.id'}) { return ''; }
2834: $coursedombuf{$env{'request.course.id'}}=
2835: $env{'course.'.$env{'request.course.id'}.'.domain'};
2836: $coursenumbuf{$env{'request.course.id'}}=
2837: $env{'course.'.$env{'request.course.id'}.'.num'};
2838: $coursehombuf{$env{'request.course.id'}}=
2839: $env{'course.'.$env{'request.course.id'}.'.home'};
2840: $coursedescrbuf{$env{'request.course.id'}}=
2841: $env{'course.'.$env{'request.course.id'}.'.description'};
2842: $courseinstcodebuf{$env{'request.course.id'}}=
2843: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2844: $courseownerbuf{$env{'request.course.id'}}=
2845: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2846: $coursetypebuf{$env{'request.course.id'}}=
2847: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2848: if (defined $courselogs{$env{'request.course.id'}}) {
2849: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2850: } else {
1.620 albertel 2851: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2852: }
1.620 albertel 2853: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2854: &flushcourselogs();
2855: }
1.158 www 2856: }
2857:
2858: sub courseacclog {
2859: my $fnsymb=shift;
1.620 albertel 2860: unless ($env{'request.course.id'}) { return ''; }
2861: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2862: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2863: $what.=':POST';
1.583 matthew 2864: # FIXME: Probably ought to escape things....
1.800 albertel 2865: foreach my $key (keys(%env)) {
2866: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2867: my $formitem = $1;
2868: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2869: $what.=':'.$formitem.'='.$env{$key};
2870: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2871: $what.=':'.$formitem.'='.$env{$key};
2872: }
1.158 www 2873: }
1.191 harris41 2874: }
1.583 matthew 2875: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2876: # FIXME: We should not be depending on a form parameter that someone
2877: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2878: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2879: $what.= ':POST';
2880: # FIXME: Probably ought to escape things....
2881: foreach my $element ('courseexp','crsfulltext','crsrelated',
2882: 'crsdiscuss') {
1.620 albertel 2883: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2884: }
2885: }
1.158 www 2886: }
2887: &courselog($what);
1.149 www 2888: }
2889:
1.185 www 2890: sub countacc {
2891: my $url=&declutter(shift);
1.458 matthew 2892: return if (! defined($url) || $url eq '');
1.620 albertel 2893: unless ($env{'request.course.id'}) { return ''; }
2894: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2895: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2896: $accesshash{$key}++;
1.185 www 2897: }
1.349 www 2898:
1.361 www 2899: sub linklog {
2900: my ($from,$to)=@_;
2901: $from=&declutter($from);
2902: $to=&declutter($to);
2903: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2904: $accesshash{$to.'___'.$from.'___goto'}=1;
2905: }
2906:
1.349 www 2907: sub userrolelog {
2908: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2909: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2910: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2911: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 2912: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 2913: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2914: $userrolehash
2915: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2916: =$tend.':'.$tstart;
1.662 raeburn 2917: }
1.898 albertel 2918: if (($env{'request.role'} =~ /dc\./) &&
2919: (($trole=~/^au/) || ($trole=~/^in/) ||
2920: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 2921: ($trole=~/^cr/) || ($trole=~/^ta/) ||
2922: ($trole=~/^co/))) {
1.898 albertel 2923: $userrolehash
2924: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2925: =$tend.':'.$tstart;
2926: }
1.662 raeburn 2927: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2928: ($trole=~/^li/) || ($trole=~/^li/) ||
2929: ($trole=~/^au/) || ($trole=~/^dg/) ||
2930: ($trole=~/^sc/)) {
2931: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2932: $domainrolehash
2933: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2934: = $tend.':'.$tstart;
2935: }
1.351 www 2936: }
2937:
1.957 raeburn 2938: sub courserolelog {
2939: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2940: if (($trole eq 'cc') || ($trole eq 'in') ||
2941: ($trole eq 'ep') || ($trole eq 'ad') ||
2942: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 2943: ($trole=~/^cr/) || ($trole eq 'gr') ||
2944: ($trole eq 'co')) {
1.957 raeburn 2945: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2946: my $cdom = $1;
2947: my $cnum = $2;
2948: my $sec = $3;
2949: my $namespace = 'rolelog';
2950: my %storehash = (
2951: role => $trole,
2952: start => $tstart,
2953: end => $tend,
2954: selfenroll => $selfenroll,
2955: context => $context,
2956: );
2957: if ($trole eq 'gr') {
2958: $namespace = 'groupslog';
2959: $storehash{'group'} = $sec;
2960: } else {
2961: $storehash{'section'} = $sec;
2962: }
2963: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 2964: if (($trole ne 'st') || ($sec ne '')) {
2965: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2966: }
1.957 raeburn 2967: }
2968: }
2969: return;
2970: }
2971:
1.351 www 2972: sub get_course_adv_roles {
1.948 raeburn 2973: my ($cid,$codes) = @_;
1.620 albertel 2974: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2975: my %coursehash=&coursedescription($cid);
1.988 raeburn 2976: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 2977: my %nothide=();
1.800 albertel 2978: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2979: if ($user !~ /:/) {
2980: $nothide{join(':',split(/[\@]/,$user))}=1;
2981: } else {
2982: $nothide{$user}=1;
2983: }
1.470 www 2984: }
1.351 www 2985: my %returnhash=();
2986: my %dumphash=
2987: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2988: my $now=time;
1.997 raeburn 2989: my %privileged;
1.1000 raeburn 2990: foreach my $entry (keys(%dumphash)) {
1.800 albertel 2991: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2992: if (($tstart) && ($tstart<0)) { next; }
2993: if (($tend) && ($tend<$now)) { next; }
2994: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2995: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2996: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 2997: unless (ref($privileged{$domain}) eq 'HASH') {
2998: my %dompersonnel =
1.998 raeburn 2999: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3000: $privileged{$domain} = {};
3001: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3002: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3003: foreach my $user (keys(%{$dompersonnel{$server}})) {
3004: my ($trole,$uname,$udom) = split(/:/,$user);
3005: $privileged{$udom}{$uname} = 1;
3006: }
3007: }
3008: }
3009: }
3010: if ((exists($privileged{$domain}{$username})) &&
3011: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3012: if ($role eq 'cr') { next; }
1.948 raeburn 3013: if ($codes) {
3014: if ($section) { $role .= ':'.$section; }
3015: if ($returnhash{$role}) {
3016: $returnhash{$role}.=','.$username.':'.$domain;
3017: } else {
3018: $returnhash{$role}=$username.':'.$domain;
3019: }
1.351 www 3020: } else {
1.988 raeburn 3021: my $key=&plaintext($role,$crstype);
1.973 bisitz 3022: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3023: if ($returnhash{$key}) {
3024: $returnhash{$key}.=','.$username.':'.$domain;
3025: } else {
3026: $returnhash{$key}=$username.':'.$domain;
3027: }
1.351 www 3028: }
1.948 raeburn 3029: }
1.400 www 3030: return %returnhash;
3031: }
3032:
3033: sub get_my_roles {
1.937 raeburn 3034: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3035: unless (defined($uname)) { $uname=$env{'user.name'}; }
3036: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3037: my (%dumphash,%nothide);
1.858 raeburn 3038: if ($context eq 'userroles') {
3039: %dumphash = &dump('roles',$udom,$uname);
3040: } else {
3041: %dumphash=
1.400 www 3042: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3043: if ($hidepriv) {
3044: my %coursehash=&coursedescription($udom.'_'.$uname);
3045: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3046: if ($user !~ /:/) {
3047: $nothide{join(':',split(/[\@]/,$user))} = 1;
3048: } else {
3049: $nothide{$user} = 1;
3050: }
3051: }
3052: }
1.858 raeburn 3053: }
1.400 www 3054: my %returnhash=();
3055: my $now=time;
1.999 raeburn 3056: my %privileged;
1.800 albertel 3057: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3058: my ($role,$tend,$tstart);
3059: if ($context eq 'userroles') {
3060: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3061: } else {
3062: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3063: }
1.400 www 3064: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3065: my $status = 'active';
1.939 raeburn 3066: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3067: $status = 'previous';
3068: }
3069: if (($tstart) && ($now<$tstart)) {
3070: $status = 'future';
3071: }
3072: if (ref($types) eq 'ARRAY') {
3073: if (!grep(/^\Q$status\E$/,@{$types})) {
3074: next;
3075: }
3076: } else {
3077: if ($status ne 'active') {
3078: next;
3079: }
3080: }
1.867 raeburn 3081: my ($rolecode,$username,$domain,$section,$area);
3082: if ($context eq 'userroles') {
3083: ($area,$rolecode) = split(/_/,$entry);
3084: (undef,$domain,$username,$section) = split(/\//,$area);
3085: } else {
3086: ($role,$username,$domain,$section) = split(/\:/,$entry);
3087: }
1.832 raeburn 3088: if (ref($roledoms) eq 'ARRAY') {
3089: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3090: next;
3091: }
3092: }
3093: if (ref($roles) eq 'ARRAY') {
3094: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3095: if ($role =~ /^cr\//) {
3096: if (!grep(/^cr$/,@{$roles})) {
3097: next;
3098: }
3099: } else {
3100: next;
3101: }
1.832 raeburn 3102: }
1.867 raeburn 3103: }
1.937 raeburn 3104: if ($hidepriv) {
1.999 raeburn 3105: if ($context eq 'userroles') {
3106: if ((&privileged($username,$domain)) &&
3107: (!$nothide{$username.':'.$domain})) {
3108: next;
3109: }
3110: } else {
3111: unless (ref($privileged{$domain}) eq 'HASH') {
3112: my %dompersonnel =
3113: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3114: $privileged{$domain} = {};
3115: if (keys(%dompersonnel)) {
3116: foreach my $server (keys(%dompersonnel)) {
3117: if (ref($dompersonnel{$server}) eq 'HASH') {
3118: foreach my $user (keys(%{$dompersonnel{$server}})) {
3119: my ($trole,$uname,$udom) = split(/:/,$user);
3120: $privileged{$udom}{$uname} = $trole;
3121: }
3122: }
3123: }
3124: }
3125: }
3126: if (exists($privileged{$domain}{$username})) {
3127: if (!$nothide{$username.':'.$domain}) {
3128: next;
3129: }
3130: }
1.937 raeburn 3131: }
3132: }
1.933 raeburn 3133: if ($withsec) {
3134: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3135: $tstart.':'.$tend;
3136: } else {
3137: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3138: }
1.832 raeburn 3139: }
1.373 www 3140: return %returnhash;
1.399 www 3141: }
3142:
3143: # ----------------------------------------------------- Frontpage Announcements
3144: #
3145: #
3146:
3147: sub postannounce {
3148: my ($server,$text)=@_;
1.844 albertel 3149: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3150: unless ($text=~/\w/) { $text=''; }
3151: return &reply('setannounce:'.&escape($text),$server);
3152: }
3153:
3154: sub getannounce {
1.448 albertel 3155:
3156: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3157: my $announcement='';
1.800 albertel 3158: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3159: close($fh);
1.399 www 3160: if ($announcement=~/\w/) {
3161: return
3162: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3163: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3164: } else {
3165: return '';
3166: }
3167: } else {
3168: return '';
3169: }
1.351 www 3170: }
1.353 www 3171:
3172: # ---------------------------------------------------------- Course ID routines
3173: # Deal with domain's nohist_courseid.db files
3174: #
3175:
3176: sub courseidput {
1.921 raeburn 3177: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3178: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3179: my $outcome;
3180: if ($caller eq 'timeonly') {
3181: my $cids = '';
3182: foreach my $item (keys(%$storehash)) {
3183: $cids.=&escape($item).'&';
3184: }
3185: $cids=~s/\&$//;
3186: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3187: $coursehome);
3188: } else {
3189: my $items = '';
3190: foreach my $item (keys(%$storehash)) {
3191: $items.= &escape($item).'='.
3192: &freeze_escape($$storehash{$item}).'&';
3193: }
3194: $items=~s/\&$//;
3195: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3196: $coursehome);
1.918 raeburn 3197: }
3198: if ($outcome eq 'unknown_cmd') {
3199: my $what;
3200: foreach my $cid (keys(%$storehash)) {
3201: $what .= &escape($cid).'=';
1.921 raeburn 3202: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3203: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3204: }
3205: $what =~ s/\:$/&/;
3206: }
3207: $what =~ s/\&$//;
3208: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3209: } else {
3210: return $outcome;
3211: }
1.353 www 3212: }
3213:
3214: sub courseiddump {
1.921 raeburn 3215: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3216: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3217: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3218: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3219: my $as_hash = 1;
3220: my %returnhash;
3221: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3222: my %libserv = &all_library();
3223: foreach my $tryserver (keys(%libserv)) {
3224: if ( ( $hostidflag == 1
3225: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3226: || (!defined($hostidflag)) ) {
3227:
1.918 raeburn 3228: if (($domfilter eq '') ||
3229: (&host_domain($tryserver) eq $domfilter)) {
3230: my $rep =
3231: &reply('courseiddump:'.&host_domain($tryserver).':'.
3232: $sincefilter.':'.&escape($descfilter).':'.
3233: &escape($instcodefilter).':'.&escape($ownerfilter).
3234: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3235: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3236: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3237: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3238: &escape($cc_clone).':'.$cloneonly.':'.
3239: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3240: &escape($creationcontext).':'.$domcloner,
3241: $tryserver);
1.918 raeburn 3242: my @pairs=split(/\&/,$rep);
3243: foreach my $item (@pairs) {
3244: my ($key,$value)=split(/\=/,$item,2);
3245: $key = &unescape($key);
3246: next if ($key =~ /^error: 2 /);
3247: my $result = &thaw_unescape($value);
3248: if (ref($result) eq 'HASH') {
3249: $returnhash{$key}=$result;
3250: } else {
1.921 raeburn 3251: my @responses = split(/:/,$value);
3252: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3253: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3254: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3255: }
1.1008 raeburn 3256: }
1.353 www 3257: }
3258: }
3259: }
3260: }
3261: return %returnhash;
3262: }
3263:
1.1055 raeburn 3264: sub courselastaccess {
3265: my ($cdom,$cnum,$hostidref) = @_;
3266: my %returnhash;
3267: if ($cdom && $cnum) {
3268: my $chome = &homeserver($cnum,$cdom);
3269: if ($chome ne 'no_host') {
3270: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3271: &extract_lastaccess(\%returnhash,$rep);
3272: }
3273: } else {
3274: if (!$cdom) { $cdom=''; }
3275: my %libserv = &all_library();
3276: foreach my $tryserver (keys(%libserv)) {
3277: if (ref($hostidref) eq 'ARRAY') {
3278: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3279: }
3280: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3281: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3282: &extract_lastaccess(\%returnhash,$rep);
3283: }
3284: }
3285: }
3286: return %returnhash;
3287: }
3288:
3289: sub extract_lastaccess {
3290: my ($returnhash,$rep) = @_;
3291: if (ref($returnhash) eq 'HASH') {
3292: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3293: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3294: $rep eq '') {
3295: my @pairs=split(/\&/,$rep);
3296: foreach my $item (@pairs) {
3297: my ($key,$value)=split(/\=/,$item,2);
3298: $key = &unescape($key);
3299: next if ($key =~ /^error: 2 /);
3300: $returnhash->{$key} = &thaw_unescape($value);
3301: }
3302: }
3303: }
3304: return;
3305: }
3306:
1.658 raeburn 3307: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3308:
3309: sub dcmailput {
1.685 raeburn 3310: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3311: my $status = &Apache::lonnet::critical(
1.740 www 3312: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3313: &escape($message),$server);
1.662 raeburn 3314: return $status;
3315: }
3316:
1.658 raeburn 3317: sub dcmaildump {
3318: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3319: my %returnhash=();
1.846 albertel 3320:
3321: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3322: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3323: &escape($enddate).':';
3324: my @esc_senders=map { &escape($_)} @$senders;
3325: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3326: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3327: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3328: if (($key) && ($value)) {
3329: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3330: }
3331: }
3332: }
3333: return %returnhash;
3334: }
1.662 raeburn 3335: # ---------------------------------------------------------- Domain roles
3336:
3337: sub get_domain_roles {
3338: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3339: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3340: $startdate = '.';
3341: }
1.1018 raeburn 3342: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3343: $enddate = '.';
3344: }
1.922 raeburn 3345: my $rolelist;
3346: if (ref($roles) eq 'ARRAY') {
3347: $rolelist = join(':',@{$roles});
3348: }
1.662 raeburn 3349: my %personnel = ();
1.841 albertel 3350:
3351: my %servers = &get_servers($dom,'library');
3352: foreach my $tryserver (keys(%servers)) {
3353: %{$personnel{$tryserver}}=();
3354: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3355: &escape($startdate).':'.
3356: &escape($enddate).':'.
3357: &escape($rolelist), $tryserver))) {
3358: my ($key,$value) = split(/\=/,$line,2);
3359: if (($key) && ($value)) {
3360: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3361: }
3362: }
1.662 raeburn 3363: }
3364: return %personnel;
3365: }
1.658 raeburn 3366:
1.1057 www 3367: # ----------------------------------------------------------- Interval timing
1.149 www 3368:
1.504 albertel 3369: sub get_first_access {
3370: my ($type,$argsymb)=@_;
1.790 albertel 3371: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3372: if ($argsymb) { $symb=$argsymb; }
3373: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3374: if ($type eq 'course') {
3375: $res='course';
3376: } elsif ($type eq 'map') {
1.588 albertel 3377: $res=&symbread($map);
3378: } else {
3379: $res=$symb;
3380: }
3381: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3382: return $times{"$courseid\0$res"};
1.504 albertel 3383: }
3384:
3385: sub set_first_access {
3386: my ($type)=@_;
1.790 albertel 3387: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3388: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3389: if ($type eq 'course') {
3390: $res='course';
3391: } elsif ($type eq 'map') {
1.588 albertel 3392: $res=&symbread($map);
3393: } else {
3394: $res=$symb;
3395: }
3396: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3397: if (!$firstaccess) {
1.588 albertel 3398: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3399: }
3400: return 'already_set';
1.504 albertel 3401: }
3402:
1.110 www 3403: # --------------------------------------------- Set Expire Date for Spreadsheet
3404:
3405: sub expirespread {
3406: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3407: my $cid=$env{'request.course.id'};
1.110 www 3408: if ($cid) {
3409: my $now=time;
3410: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3411: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3412: $env{'course.'.$cid.'.num'}.
1.110 www 3413: ':nohist_expirationdates:'.
3414: &escape($key).'='.$now,
1.620 albertel 3415: $env{'course.'.$cid.'.home'})
1.110 www 3416: }
3417: return 'ok';
1.14 www 3418: }
3419:
1.109 www 3420: # ----------------------------------------------------- Devalidate Spreadsheets
3421:
3422: sub devalidate {
1.325 www 3423: my ($symb,$uname,$udom)=@_;
1.620 albertel 3424: my $cid=$env{'request.course.id'};
1.109 www 3425: if ($cid) {
1.391 matthew 3426: # delete the stored spreadsheets for
3427: # - the student level sheet of this user in course's homespace
3428: # - the assessment level sheet for this resource
3429: # for this user in user's homespace
1.553 albertel 3430: # - current conditional state info
1.325 www 3431: my $key=$uname.':'.$udom.':';
1.109 www 3432: my $status=
1.299 matthew 3433: &del('nohist_calculatedsheets',
1.391 matthew 3434: [$key.'studentcalc:'],
1.620 albertel 3435: $env{'course.'.$cid.'.domain'},
3436: $env{'course.'.$cid.'.num'})
1.133 albertel 3437: .' '.
3438: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3439: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3440: unless ($status eq 'ok ok') {
3441: &logthis('Could not devalidate spreadsheet '.
1.325 www 3442: $uname.' at '.$udom.' for '.
1.109 www 3443: $symb.': '.$status);
1.133 albertel 3444: }
1.553 albertel 3445: &delenv('user.state.'.$cid);
1.109 www 3446: }
3447: }
3448:
1.265 albertel 3449: sub get_scalar {
3450: my ($string,$end) = @_;
3451: my $value;
3452: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3453: $value = $1;
3454: } elsif ($$string =~ s/^([^&]*?)&//) {
3455: $value = $1;
3456: }
3457: return &unescape($value);
3458: }
3459:
3460: sub array2str {
3461: my (@array) = @_;
3462: my $result=&arrayref2str(\@array);
3463: $result=~s/^__ARRAY_REF__//;
3464: $result=~s/__END_ARRAY_REF__$//;
3465: return $result;
3466: }
3467:
1.204 albertel 3468: sub arrayref2str {
3469: my ($arrayref) = @_;
1.265 albertel 3470: my $result='__ARRAY_REF__';
1.204 albertel 3471: foreach my $elem (@$arrayref) {
1.265 albertel 3472: if(ref($elem) eq 'ARRAY') {
3473: $result.=&arrayref2str($elem).'&';
3474: } elsif(ref($elem) eq 'HASH') {
3475: $result.=&hashref2str($elem).'&';
3476: } elsif(ref($elem)) {
3477: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3478: } else {
3479: $result.=&escape($elem).'&';
3480: }
3481: }
3482: $result=~s/\&$//;
1.265 albertel 3483: $result .= '__END_ARRAY_REF__';
1.204 albertel 3484: return $result;
3485: }
3486:
1.168 albertel 3487: sub hash2str {
1.204 albertel 3488: my (%hash) = @_;
3489: my $result=&hashref2str(\%hash);
1.265 albertel 3490: $result=~s/^__HASH_REF__//;
3491: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3492: return $result;
3493: }
3494:
3495: sub hashref2str {
3496: my ($hashref)=@_;
1.265 albertel 3497: my $result='__HASH_REF__';
1.800 albertel 3498: foreach my $key (sort(keys(%$hashref))) {
3499: if (ref($key) eq 'ARRAY') {
3500: $result.=&arrayref2str($key).'=';
3501: } elsif (ref($key) eq 'HASH') {
3502: $result.=&hashref2str($key).'=';
3503: } elsif (ref($key)) {
1.265 albertel 3504: $result.='=';
1.800 albertel 3505: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3506: } else {
1.800 albertel 3507: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3508: }
3509:
1.800 albertel 3510: if(ref($hashref->{$key}) eq 'ARRAY') {
3511: $result.=&arrayref2str($hashref->{$key}).'&';
3512: } elsif(ref($hashref->{$key}) eq 'HASH') {
3513: $result.=&hashref2str($hashref->{$key}).'&';
3514: } elsif(ref($hashref->{$key})) {
1.265 albertel 3515: $result.='&';
1.800 albertel 3516: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3517: } else {
1.800 albertel 3518: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3519: }
3520: }
1.168 albertel 3521: $result=~s/\&$//;
1.265 albertel 3522: $result .= '__END_HASH_REF__';
1.168 albertel 3523: return $result;
3524: }
3525:
3526: sub str2hash {
1.265 albertel 3527: my ($string)=@_;
3528: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3529: return %$hash;
3530: }
3531:
3532: sub str2hashref {
1.168 albertel 3533: my ($string) = @_;
1.265 albertel 3534:
3535: my %hash;
3536:
3537: if($string !~ /^__HASH_REF__/) {
3538: if (! ($string eq '' || !defined($string))) {
3539: $hash{'error'}='Not hash reference';
3540: }
3541: return (\%hash, $string);
3542: }
3543:
3544: $string =~ s/^__HASH_REF__//;
3545:
3546: while($string !~ /^__END_HASH_REF__/) {
3547: #key
3548: my $key='';
3549: if($string =~ /^__HASH_REF__/) {
3550: ($key, $string)=&str2hashref($string);
3551: if(defined($key->{'error'})) {
3552: $hash{'error'}='Bad data';
3553: return (\%hash, $string);
3554: }
3555: } elsif($string =~ /^__ARRAY_REF__/) {
3556: ($key, $string)=&str2arrayref($string);
3557: if($key->[0] eq 'Array reference error') {
3558: $hash{'error'}='Bad data';
3559: return (\%hash, $string);
3560: }
3561: } else {
3562: $string =~ s/^(.*?)=//;
1.267 albertel 3563: $key=&unescape($1);
1.265 albertel 3564: }
3565: $string =~ s/^=//;
3566:
3567: #value
3568: my $value='';
3569: if($string =~ /^__HASH_REF__/) {
3570: ($value, $string)=&str2hashref($string);
3571: if(defined($value->{'error'})) {
3572: $hash{'error'}='Bad data';
3573: return (\%hash, $string);
3574: }
3575: } elsif($string =~ /^__ARRAY_REF__/) {
3576: ($value, $string)=&str2arrayref($string);
3577: if($value->[0] eq 'Array reference error') {
3578: $hash{'error'}='Bad data';
3579: return (\%hash, $string);
3580: }
3581: } else {
3582: $value=&get_scalar(\$string,'__END_HASH_REF__');
3583: }
3584: $string =~ s/^&//;
3585:
3586: $hash{$key}=$value;
1.204 albertel 3587: }
1.265 albertel 3588:
3589: $string =~ s/^__END_HASH_REF__//;
3590:
3591: return (\%hash, $string);
1.204 albertel 3592: }
3593:
3594: sub str2array {
1.265 albertel 3595: my ($string)=@_;
3596: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3597: return @$array;
3598: }
3599:
3600: sub str2arrayref {
1.204 albertel 3601: my ($string) = @_;
1.265 albertel 3602: my @array;
3603:
3604: if($string !~ /^__ARRAY_REF__/) {
3605: if (! ($string eq '' || !defined($string))) {
3606: $array[0]='Array reference error';
3607: }
3608: return (\@array, $string);
3609: }
3610:
3611: $string =~ s/^__ARRAY_REF__//;
3612:
3613: while($string !~ /^__END_ARRAY_REF__/) {
3614: my $value='';
3615: if($string =~ /^__HASH_REF__/) {
3616: ($value, $string)=&str2hashref($string);
3617: if(defined($value->{'error'})) {
3618: $array[0] ='Array reference error';
3619: return (\@array, $string);
3620: }
3621: } elsif($string =~ /^__ARRAY_REF__/) {
3622: ($value, $string)=&str2arrayref($string);
3623: if($value->[0] eq 'Array reference error') {
3624: $array[0] ='Array reference error';
3625: return (\@array, $string);
3626: }
3627: } else {
3628: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3629: }
3630: $string =~ s/^&//;
3631:
3632: push(@array, $value);
1.191 harris41 3633: }
1.265 albertel 3634:
3635: $string =~ s/^__END_ARRAY_REF__//;
3636:
3637: return (\@array, $string);
1.168 albertel 3638: }
3639:
1.167 albertel 3640: # -------------------------------------------------------------------Temp Store
3641:
1.168 albertel 3642: sub tmpreset {
3643: my ($symb,$namespace,$domain,$stuname) = @_;
3644: if (!$symb) {
3645: $symb=&symbread();
1.620 albertel 3646: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3647: }
3648: $symb=escape($symb);
3649:
1.620 albertel 3650: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3651: $namespace=~s/\//\_/g;
3652: $namespace=~s/\W//g;
3653:
1.620 albertel 3654: if (!$domain) { $domain=$env{'user.domain'}; }
3655: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3656: if ($domain eq 'public' && $stuname eq 'public') {
3657: $stuname=$ENV{'REMOTE_ADDR'};
3658: }
1.168 albertel 3659: my $path=$perlvar{'lonDaemons'}.'/tmp';
3660: my %hash;
3661: if (tie(%hash,'GDBM_File',
3662: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3663: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3664: foreach my $key (keys(%hash)) {
1.180 albertel 3665: if ($key=~ /:$symb/) {
1.168 albertel 3666: delete($hash{$key});
3667: }
3668: }
3669: }
3670: }
3671:
1.167 albertel 3672: sub tmpstore {
1.168 albertel 3673: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3674:
3675: if (!$symb) {
3676: $symb=&symbread();
1.620 albertel 3677: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3678: }
3679: $symb=escape($symb);
3680:
3681: if (!$namespace) {
3682: # I don't think we would ever want to store this for a course.
3683: # it seems this will only be used if we don't have a course.
1.620 albertel 3684: #$namespace=$env{'request.course.id'};
1.168 albertel 3685: #if (!$namespace) {
1.620 albertel 3686: $namespace=$env{'request.state'};
1.168 albertel 3687: #}
3688: }
3689: $namespace=~s/\//\_/g;
3690: $namespace=~s/\W//g;
1.620 albertel 3691: if (!$domain) { $domain=$env{'user.domain'}; }
3692: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3693: if ($domain eq 'public' && $stuname eq 'public') {
3694: $stuname=$ENV{'REMOTE_ADDR'};
3695: }
1.168 albertel 3696: my $now=time;
3697: my %hash;
3698: my $path=$perlvar{'lonDaemons'}.'/tmp';
3699: if (tie(%hash,'GDBM_File',
3700: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3701: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3702: $hash{"version:$symb"}++;
3703: my $version=$hash{"version:$symb"};
3704: my $allkeys='';
3705: foreach my $key (keys(%$storehash)) {
3706: $allkeys.=$key.':';
1.591 albertel 3707: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3708: }
3709: $hash{"$version:$symb:timestamp"}=$now;
3710: $allkeys.='timestamp';
3711: $hash{"$version:keys:$symb"}=$allkeys;
3712: if (untie(%hash)) {
3713: return 'ok';
3714: } else {
3715: return "error:$!";
3716: }
3717: } else {
3718: return "error:$!";
3719: }
3720: }
1.167 albertel 3721:
1.168 albertel 3722: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3723:
1.168 albertel 3724: sub tmprestore {
3725: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3726:
1.168 albertel 3727: if (!$symb) {
3728: $symb=&symbread();
1.620 albertel 3729: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3730: }
3731: $symb=escape($symb);
3732:
1.620 albertel 3733: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3734:
1.620 albertel 3735: if (!$domain) { $domain=$env{'user.domain'}; }
3736: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3737: if ($domain eq 'public' && $stuname eq 'public') {
3738: $stuname=$ENV{'REMOTE_ADDR'};
3739: }
1.168 albertel 3740: my %returnhash;
3741: $namespace=~s/\//\_/g;
3742: $namespace=~s/\W//g;
3743: my %hash;
3744: my $path=$perlvar{'lonDaemons'}.'/tmp';
3745: if (tie(%hash,'GDBM_File',
3746: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3747: &GDBM_READER(),0640)) {
1.168 albertel 3748: my $version=$hash{"version:$symb"};
3749: $returnhash{'version'}=$version;
3750: my $scope;
3751: for ($scope=1;$scope<=$version;$scope++) {
3752: my $vkeys=$hash{"$scope:keys:$symb"};
3753: my @keys=split(/:/,$vkeys);
3754: my $key;
3755: $returnhash{"$scope:keys"}=$vkeys;
3756: foreach $key (@keys) {
1.591 albertel 3757: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3758: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3759: }
3760: }
1.168 albertel 3761: if (!(untie(%hash))) {
3762: return "error:$!";
3763: }
3764: } else {
3765: return "error:$!";
3766: }
3767: return %returnhash;
1.167 albertel 3768: }
3769:
1.9 www 3770: # ----------------------------------------------------------------------- Store
3771:
3772: sub store {
1.124 www 3773: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3774: my $home='';
3775:
1.168 albertel 3776: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3777:
1.213 www 3778: $symb=&symbclean($symb);
1.122 albertel 3779: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3780:
1.620 albertel 3781: if (!$domain) { $domain=$env{'user.domain'}; }
3782: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3783:
3784: &devalidate($symb,$stuname,$domain);
1.109 www 3785:
3786: $symb=escape($symb);
1.187 www 3787: if (!$namespace) {
1.620 albertel 3788: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3789: return '';
3790: }
3791: }
1.620 albertel 3792: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3793:
3794: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3795: $$storehash{'host'}=$perlvar{'lonHostID'};
3796:
1.12 www 3797: my $namevalue='';
1.800 albertel 3798: foreach my $key (keys(%$storehash)) {
3799: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3800: }
1.12 www 3801: $namevalue=~s/\&$//;
1.187 www 3802: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3803: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3804: }
3805:
1.47 www 3806: # -------------------------------------------------------------- Critical Store
3807:
3808: sub cstore {
1.124 www 3809: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3810: my $home='';
3811:
1.168 albertel 3812: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3813:
1.213 www 3814: $symb=&symbclean($symb);
1.122 albertel 3815: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3816:
1.620 albertel 3817: if (!$domain) { $domain=$env{'user.domain'}; }
3818: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3819:
3820: &devalidate($symb,$stuname,$domain);
1.109 www 3821:
3822: $symb=escape($symb);
1.187 www 3823: if (!$namespace) {
1.620 albertel 3824: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3825: return '';
3826: }
3827: }
1.620 albertel 3828: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3829:
3830: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3831: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3832:
1.47 www 3833: my $namevalue='';
1.800 albertel 3834: foreach my $key (keys(%$storehash)) {
3835: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3836: }
1.47 www 3837: $namevalue=~s/\&$//;
1.187 www 3838: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3839: return critical
3840: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3841: }
3842:
1.9 www 3843: # --------------------------------------------------------------------- Restore
3844:
3845: sub restore {
1.124 www 3846: my ($symb,$namespace,$domain,$stuname) = @_;
3847: my $home='';
3848:
1.168 albertel 3849: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3850:
1.122 albertel 3851: if (!$symb) {
3852: unless ($symb=escape(&symbread())) { return ''; }
3853: } else {
1.213 www 3854: $symb=&escape(&symbclean($symb));
1.122 albertel 3855: }
1.188 www 3856: if (!$namespace) {
1.620 albertel 3857: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3858: return '';
3859: }
3860: }
1.620 albertel 3861: if (!$domain) { $domain=$env{'user.domain'}; }
3862: if (!$stuname) { $stuname=$env{'user.name'}; }
3863: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3864: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3865:
1.12 www 3866: my %returnhash=();
1.800 albertel 3867: foreach my $line (split(/\&/,$answer)) {
3868: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3869: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3870: }
1.75 www 3871: my $version;
3872: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3873: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3874: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3875: }
1.75 www 3876: }
1.13 www 3877: return %returnhash;
1.34 www 3878: }
3879:
3880: # ---------------------------------------------------------- Course Description
3881:
3882: sub coursedescription {
1.731 albertel 3883: my ($courseid,$args)=@_;
1.34 www 3884: $courseid=~s/^\///;
1.49 www 3885: $courseid=~s/\_/\//g;
1.34 www 3886: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3887: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3888: my $normalid=$cdomain.'_'.$cnum;
3889: # need to always cache even if we get errors otherwise we keep
3890: # trying and trying and trying to get the course description.
3891: my %envhash=();
3892: my %returnhash=();
1.731 albertel 3893:
3894: my $expiretime=600;
3895: if ($env{'request.course.id'} eq $normalid) {
3896: $expiretime=120;
3897: }
3898:
3899: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3900: if (!$args->{'freshen_cache'}
3901: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3902: foreach my $key (keys(%env)) {
3903: next if ($key !~ /^\Q$prefix\E(.*)/);
3904: my ($setting) = $1;
3905: $returnhash{$setting} = $env{$key};
3906: }
3907: return %returnhash;
3908: }
3909:
3910: # get the data agin
3911: if (!$args->{'one_time'}) {
3912: $envhash{'course.'.$normalid.'.last_cache'}=time;
3913: }
1.811 albertel 3914:
1.34 www 3915: if ($chome ne 'no_host') {
1.302 albertel 3916: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3917: if (!exists($returnhash{'con_lost'})) {
3918: $returnhash{'home'}= $chome;
3919: $returnhash{'domain'} = $cdomain;
3920: $returnhash{'num'} = $cnum;
1.741 raeburn 3921: if (!defined($returnhash{'type'})) {
3922: $returnhash{'type'} = 'Course';
3923: }
1.130 albertel 3924: while (my ($name,$value) = each %returnhash) {
1.53 www 3925: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3926: }
1.270 www 3927: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3928: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3929: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3930: $envhash{'course.'.$normalid.'.home'}=$chome;
3931: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3932: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3933: }
3934: }
1.731 albertel 3935: if (!$args->{'one_time'}) {
1.949 raeburn 3936: &appenv(\%envhash);
1.731 albertel 3937: }
1.302 albertel 3938: return %returnhash;
1.461 www 3939: }
3940:
1.1080 raeburn 3941: sub update_released_required {
3942: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
3943: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
3944: $cid = $env{'request.course.id'};
3945: $cdom = $env{'course.'.$cid.'.domain'};
3946: $cnum = $env{'course.'.$cid.'.num'};
3947: $chome = $env{'course.'.$cid.'.home'};
3948: }
3949: if ($needsrelease) {
3950: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
3951: my $needsupdate;
3952: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
3953: $needsupdate = 1;
3954: } else {
3955: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
3956: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
3957: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
3958: $needsupdate = 1;
3959: }
3960: }
3961: if ($needsupdate) {
3962: my %needshash = (
3963: 'internal.releaserequired' => $needsrelease,
3964: );
3965: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
3966: if ($putresult eq 'ok') {
3967: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
3968: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
3969: if (ref($crsinfo{$cid}) eq 'HASH') {
3970: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
3971: &courseidput($cdom,\%crsinfo,$chome,'notime');
3972: }
3973: }
3974: }
3975: }
3976: return;
3977: }
3978:
1.461 www 3979: # -------------------------------------------------See if a user is privileged
3980:
3981: sub privileged {
3982: my ($username,$domain)=@_;
3983: my $rolesdump=&reply("dump:$domain:$username:roles",
3984: &homeserver($username,$domain));
1.1033 raeburn 3985: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3986: ($rolesdump =~ /^error:/)) {
3987: return 0;
3988: }
1.461 www 3989: my $now=time;
3990: if ($rolesdump ne '') {
1.800 albertel 3991: foreach my $entry (split(/&/,$rolesdump)) {
3992: if ($entry!~/^rolesdef_/) {
3993: my ($area,$role)=split(/=/,$entry);
1.461 www 3994: $area=~s/\_\w\w$//;
3995: my ($trole,$tend,$tstart)=split(/_/,$role);
3996: if (($trole eq 'dc') || ($trole eq 'su')) {
3997: my $active=1;
3998: if ($tend) {
3999: if ($tend<$now) { $active=0; }
4000: }
4001: if ($tstart) {
4002: if ($tstart>$now) { $active=0; }
4003: }
4004: if ($active) { return 1; }
4005: }
4006: }
4007: }
4008: }
4009: return 0;
1.9 www 4010: }
1.1 albertel 4011:
1.103 harris41 4012: # -------------------------------------------------------- Get user privileges
1.11 www 4013:
4014: sub rolesinit {
4015: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4016: my $now=time;
4017: my %userroles = ('user.login.time' => $now);
1.1078 raeburn 4018: my $extra = &freeze_escape({'clientcheckrole' => 1});
4019: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4020: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1078 raeburn 4021: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4022: return \%userroles;
4023: }
1.11 www 4024: my %allroles=();
1.678 raeburn 4025: my %allgroups=();
4026: my $group_privs;
1.11 www 4027:
4028: if ($rolesdump ne '') {
1.800 albertel 4029: foreach my $entry (split(/&/,$rolesdump)) {
4030: if ($entry!~/^rolesdef_/) {
4031: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4032: $area=~s/\_\w\w$//;
1.678 raeburn 4033: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4034: if ($role=~/^cr/) {
1.807 albertel 4035: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4036: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4037: ($tend,$tstart)=split('_',$trest);
4038: } else {
4039: $trole=$role;
4040: }
1.678 raeburn 4041: } elsif ($role =~ m|^gr/|) {
4042: ($trole,$tend,$tstart) = split(/_/,$role);
4043: ($trole,$group_privs) = split(/\//,$trole);
4044: $group_privs = &unescape($group_privs);
1.587 albertel 4045: } else {
4046: ($trole,$tend,$tstart)=split(/_/,$role);
4047: }
1.743 albertel 4048: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4049: $username);
4050: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4051: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4052: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4053: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4054: my $spec=$trole.'.'.$area;
4055: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4056: if ($trole =~ /^cr\//) {
1.567 raeburn 4057: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4058: } elsif ($trole eq 'gr') {
4059: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4060: } else {
1.567 raeburn 4061: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4062: }
1.12 www 4063: }
1.662 raeburn 4064: }
1.191 harris41 4065: }
1.743 albertel 4066: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4067: $userroles{'user.adv'} = $adv;
4068: $userroles{'user.author'} = $author;
1.620 albertel 4069: $env{'user.adv'}=$adv;
1.11 www 4070: }
1.743 albertel 4071: return \%userroles;
1.11 www 4072: }
4073:
1.567 raeburn 4074: sub set_arearole {
4075: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4076: # log the associated role with the area
4077: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4078: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4079: }
4080:
4081: sub custom_roleprivs {
4082: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4083: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4084: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4085: if (&hostname($homsvr) ne '') {
1.567 raeburn 4086: my ($rdummy,$roledef)=
4087: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4088: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4089: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4090: if (defined($syspriv)) {
1.1043 raeburn 4091: if ($trest =~ /^$match_community$/) {
4092: $syspriv =~ s/bre\&S//;
4093: }
1.567 raeburn 4094: $$allroles{'cm./'}.=':'.$syspriv;
4095: $$allroles{$spec.'./'}.=':'.$syspriv;
4096: }
4097: if ($tdomain ne '') {
4098: if (defined($dompriv)) {
4099: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4100: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4101: }
4102: if (($trest ne '') && (defined($coursepriv))) {
4103: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4104: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4105: }
4106: }
4107: }
4108: }
4109: }
4110:
1.678 raeburn 4111: sub group_roleprivs {
4112: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4113: my $access = 1;
4114: my $now = time;
4115: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4116: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4117: if ($access) {
1.811 albertel 4118: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4119: $$allgroups{$course}{$group} .=':'.$group_privs;
4120: }
4121: }
1.567 raeburn 4122:
4123: sub standard_roleprivs {
4124: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4125: if (defined($pr{$trole.':s'})) {
4126: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4127: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4128: }
4129: if ($tdomain ne '') {
4130: if (defined($pr{$trole.':d'})) {
4131: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4132: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4133: }
4134: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4135: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4136: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4137: }
4138: }
4139: }
4140:
4141: sub set_userprivs {
1.1064 raeburn 4142: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4143: my $author=0;
4144: my $adv=0;
1.678 raeburn 4145: my %grouproles = ();
4146: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4147: my @groupkeys;
1.1000 raeburn 4148: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4149: push(@groupkeys,$role);
4150: }
4151: if (ref($groups_roles) eq 'HASH') {
4152: foreach my $key (keys(%{$groups_roles})) {
4153: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4154: push(@groupkeys,$key);
4155: }
4156: }
4157: }
4158: if (@groupkeys > 0) {
4159: foreach my $role (@groupkeys) {
4160: my ($trole,$area,$sec,$extendedarea);
4161: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4162: $trole = $1;
4163: $area = $2;
4164: $sec = $3;
4165: $extendedarea = $area.$sec;
4166: if (exists($$allgroups{$area})) {
4167: foreach my $group (keys(%{$$allgroups{$area}})) {
4168: my $spec = $trole.'.'.$extendedarea;
4169: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4170: $$allgroups{$area}{$group};
1.1064 raeburn 4171: }
1.678 raeburn 4172: }
4173: }
4174: }
4175: }
4176: }
1.800 albertel 4177: foreach my $group (keys(%grouproles)) {
4178: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4179: }
1.800 albertel 4180: foreach my $role (keys(%{$allroles})) {
4181: my %thesepriv;
1.941 raeburn 4182: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4183: foreach my $item (split(/:/,$$allroles{$role})) {
4184: if ($item ne '') {
4185: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4186: if ($restrictions eq '') {
4187: $thesepriv{$privilege}='F';
4188: } elsif ($thesepriv{$privilege} ne 'F') {
4189: $thesepriv{$privilege}.=$restrictions;
4190: }
4191: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4192: }
4193: }
4194: my $thesestr='';
1.800 albertel 4195: foreach my $priv (keys(%thesepriv)) {
4196: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4197: }
4198: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4199: }
4200: return ($author,$adv);
4201: }
4202:
1.994 raeburn 4203: sub role_status {
1.1002 raeburn 4204: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4205: my @pwhere = ();
4206: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4207: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4208: unless (!defined($$role) || $$role eq '') {
4209: $$where=join('.',@pwhere);
4210: $$trolecode=$$role.'.'.$$where;
4211: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4212: $$tstatus='is';
4213: if ($$tstart && $$tstart>$then) {
4214: $$tstatus='future';
1.1034 raeburn 4215: if ($$tstart<$now) {
4216: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4217: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4218: my (%allroles,%allgroups,$group_privs,
4219: %groups_roles,@rolecodes);
1.1002 raeburn 4220: my %userroles = (
4221: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4222: );
1.1064 raeburn 4223: @rolecodes = ('cm');
1.1002 raeburn 4224: my $spec=$$role.'.'.$$where;
4225: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4226: if ($$role =~ /^cr\//) {
4227: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4228: push(@rolecodes,'cr');
1.1002 raeburn 4229: } elsif ($$role eq 'gr') {
1.1064 raeburn 4230: push(@rolecodes,$$role);
1.1002 raeburn 4231: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4232: $env{'user.name'});
1.1064 raeburn 4233: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4234: (undef,my $group_privs) = split(/\//,$trole);
4235: $group_privs = &unescape($group_privs);
4236: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4237: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4238: if (keys(%course_roles) > 0) {
4239: my ($tnum) = ($trest =~ /^($match_courseid)/);
4240: if ($tdomain ne '' && $tnum ne '') {
4241: foreach my $key (keys(%course_roles)) {
4242: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4243: my $crsrole = $1;
4244: my $crssec = $2;
4245: if ($crsrole =~ /^cr/) {
4246: unless (grep(/^cr$/,@rolecodes)) {
4247: push(@rolecodes,'cr');
4248: }
4249: } else {
4250: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4251: push(@rolecodes,$crsrole);
4252: }
4253: }
4254: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4255: if ($crssec ne '') {
4256: $rolekey .= '/'.$crssec;
4257: }
4258: $rolekey .= './';
4259: $groups_roles{$rolekey} = \@rolecodes;
4260: }
4261: }
4262: }
4263: }
1.1002 raeburn 4264: } else {
1.1064 raeburn 4265: push(@rolecodes,$$role);
1.1002 raeburn 4266: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4267: }
1.1064 raeburn 4268: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4269: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4270: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4271: }
4272: }
1.1034 raeburn 4273: $$tstatus = 'is';
1.1002 raeburn 4274: }
1.994 raeburn 4275: }
4276: if ($$tend) {
4277: if ($$tend<$then) {
4278: $$tstatus='expired';
4279: } elsif ($$tend<$now) {
4280: $$tstatus='will_not';
4281: }
4282: }
4283: }
4284: }
4285: }
4286:
4287: sub check_adhoc_privs {
1.1002 raeburn 4288: my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994 raeburn 4289: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4290: if ($env{$cckey}) {
4291: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4292: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4293: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4294: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4295: }
4296: } else {
4297: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4298: }
4299: }
4300:
4301: sub set_adhoc_privileges {
4302: # role can be cc or ca
4303: my ($dcdom,$pickedcourse,$role) = @_;
4304: my $area = '/'.$dcdom.'/'.$pickedcourse;
4305: my $spec = $role.'.'.$area;
4306: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4307: $env{'user.name'});
4308: my %ccrole = ();
4309: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4310: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4311: &appenv(\%userroles,[$role,'cm']);
4312: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4313: &appenv( {'request.role' => $spec,
4314: 'request.role.domain' => $dcdom,
4315: 'request.course.sec' => ''
4316: }
4317: );
4318: my $tadv=0;
4319: if (&allowed('adv') eq 'F') { $tadv=1; }
4320: &appenv({'request.role.adv' => $tadv});
4321: }
4322:
1.12 www 4323: # --------------------------------------------------------------- get interface
4324:
4325: sub get {
1.131 albertel 4326: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4327: my $items='';
1.800 albertel 4328: foreach my $item (@$storearr) {
4329: $items.=&escape($item).'&';
1.191 harris41 4330: }
1.12 www 4331: $items=~s/\&$//;
1.620 albertel 4332: if (!$udomain) { $udomain=$env{'user.domain'}; }
4333: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4334: my $uhome=&homeserver($uname,$udomain);
4335:
1.133 albertel 4336: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4337: my @pairs=split(/\&/,$rep);
1.273 albertel 4338: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4339: return @pairs;
4340: }
1.15 www 4341: my %returnhash=();
1.42 www 4342: my $i=0;
1.800 albertel 4343: foreach my $item (@$storearr) {
4344: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4345: $i++;
1.191 harris41 4346: }
1.15 www 4347: return %returnhash;
1.27 www 4348: }
4349:
4350: # --------------------------------------------------------------- del interface
4351:
4352: sub del {
1.133 albertel 4353: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4354: my $items='';
1.800 albertel 4355: foreach my $item (@$storearr) {
4356: $items.=&escape($item).'&';
1.191 harris41 4357: }
1.984 neumanie 4358:
1.27 www 4359: $items=~s/\&$//;
1.620 albertel 4360: if (!$udomain) { $udomain=$env{'user.domain'}; }
4361: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4362: my $uhome=&homeserver($uname,$udomain);
4363: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4364: }
4365:
4366: # -------------------------------------------------------------- dump interface
4367:
4368: sub dump {
1.755 albertel 4369: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4370: if (!$udomain) { $udomain=$env{'user.domain'}; }
4371: if (!$uname) { $uname=$env{'user.name'}; }
4372: my $uhome=&homeserver($uname,$udomain);
4373: if ($regexp) {
4374: $regexp=&escape($regexp);
4375: } else {
4376: $regexp='.';
4377: }
4378: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4379: my @pairs=split(/\&/,$rep);
4380: my %returnhash=();
4381: foreach my $item (@pairs) {
4382: my ($key,$value)=split(/=/,$item,2);
4383: $key = &unescape($key);
4384: next if ($key =~ /^error: 2 /);
4385: $returnhash{$key}=&thaw_unescape($value);
4386: }
4387: return %returnhash;
1.407 www 4388: }
4389:
1.717 albertel 4390: # --------------------------------------------------------- dumpstore interface
4391:
4392: sub dumpstore {
4393: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4394: if (!$udomain) { $udomain=$env{'user.domain'}; }
4395: if (!$uname) { $uname=$env{'user.name'}; }
4396: my $uhome=&homeserver($uname,$udomain);
4397: if ($regexp) {
4398: $regexp=&escape($regexp);
4399: } else {
4400: $regexp='.';
4401: }
4402: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4403: my @pairs=split(/\&/,$rep);
4404: my %returnhash=();
4405: foreach my $item (@pairs) {
4406: my ($key,$value)=split(/=/,$item,2);
4407: next if ($key =~ /^error: 2 /);
4408: $returnhash{$key}=&thaw_unescape($value);
4409: }
4410: return %returnhash;
1.717 albertel 4411: }
4412:
1.407 www 4413: # -------------------------------------------------------------- keys interface
4414:
4415: sub getkeys {
4416: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4417: if (!$udomain) { $udomain=$env{'user.domain'}; }
4418: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4419: my $uhome=&homeserver($uname,$udomain);
4420: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4421: my @keyarray=();
1.800 albertel 4422: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4423: next if ($key =~ /^error: 2 /);
1.800 albertel 4424: push(@keyarray,&unescape($key));
1.407 www 4425: }
4426: return @keyarray;
1.318 matthew 4427: }
4428:
1.319 matthew 4429: # --------------------------------------------------------------- currentdump
4430: sub currentdump {
1.328 matthew 4431: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4432: $courseid = $env{'request.course.id'} if (! defined($courseid));
4433: $sdom = $env{'user.domain'} if (! defined($sdom));
4434: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4435: my $uhome = &homeserver($sname,$sdom);
4436: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4437: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4438: #
1.318 matthew 4439: my %returnhash=();
1.319 matthew 4440: #
4441: if ($rep eq "unknown_cmd") {
4442: # an old lond will not know currentdump
4443: # Do a dump and make it look like a currentdump
1.822 albertel 4444: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4445: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4446: my %hash = @tmp;
4447: @tmp=();
1.424 matthew 4448: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4449: } else {
4450: my @pairs=split(/\&/,$rep);
1.800 albertel 4451: foreach my $pair (@pairs) {
4452: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4453: my ($symb,$param) = split(/:/,$key);
4454: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4455: &thaw_unescape($value);
1.319 matthew 4456: }
1.191 harris41 4457: }
1.12 www 4458: return %returnhash;
1.424 matthew 4459: }
4460:
4461: sub convert_dump_to_currentdump{
4462: my %hash = %{shift()};
4463: my %returnhash;
4464: # Code ripped from lond, essentially. The only difference
4465: # here is the unescaping done by lonnet::dump(). Conceivably
4466: # we might run in to problems with parameter names =~ /^v\./
4467: while (my ($key,$value) = each(%hash)) {
4468: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4469: $symb = &unescape($symb);
4470: $param = &unescape($param);
1.424 matthew 4471: next if ($v eq 'version' || $symb eq 'keys');
4472: next if (exists($returnhash{$symb}) &&
4473: exists($returnhash{$symb}->{$param}) &&
4474: $returnhash{$symb}->{'v.'.$param} > $v);
4475: $returnhash{$symb}->{$param}=$value;
4476: $returnhash{$symb}->{'v.'.$param}=$v;
4477: }
4478: #
4479: # Remove all of the keys in the hashes which keep track of
4480: # the version of the parameter.
4481: while (my ($symb,$param_hash) = each(%returnhash)) {
4482: # use a foreach because we are going to delete from the hash.
4483: foreach my $key (keys(%$param_hash)) {
4484: delete($param_hash->{$key}) if ($key =~ /^v\./);
4485: }
4486: }
4487: return \%returnhash;
1.12 www 4488: }
4489:
1.627 albertel 4490: # ------------------------------------------------------ critical inc interface
4491:
4492: sub cinc {
4493: return &inc(@_,'critical');
4494: }
4495:
1.449 matthew 4496: # --------------------------------------------------------------- inc interface
4497:
4498: sub inc {
1.627 albertel 4499: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4500: if (!$udomain) { $udomain=$env{'user.domain'}; }
4501: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4502: my $uhome=&homeserver($uname,$udomain);
4503: my $items='';
4504: if (! ref($store)) {
4505: # got a single value, so use that instead
4506: $items = &escape($store).'=&';
4507: } elsif (ref($store) eq 'SCALAR') {
4508: $items = &escape($$store).'=&';
4509: } elsif (ref($store) eq 'ARRAY') {
4510: $items = join('=&',map {&escape($_);} @{$store});
4511: } elsif (ref($store) eq 'HASH') {
4512: while (my($key,$value) = each(%{$store})) {
4513: $items.= &escape($key).'='.&escape($value).'&';
4514: }
4515: }
4516: $items=~s/\&$//;
1.627 albertel 4517: if ($critical) {
4518: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4519: } else {
4520: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4521: }
1.449 matthew 4522: }
4523:
1.12 www 4524: # --------------------------------------------------------------- put interface
4525:
4526: sub put {
1.134 albertel 4527: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4528: if (!$udomain) { $udomain=$env{'user.domain'}; }
4529: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4530: my $uhome=&homeserver($uname,$udomain);
1.12 www 4531: my $items='';
1.800 albertel 4532: foreach my $item (keys(%$storehash)) {
4533: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4534: }
1.12 www 4535: $items=~s/\&$//;
1.134 albertel 4536: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4537: }
4538:
1.631 albertel 4539: # ------------------------------------------------------------ newput interface
4540:
4541: sub newput {
4542: my ($namespace,$storehash,$udomain,$uname)=@_;
4543: if (!$udomain) { $udomain=$env{'user.domain'}; }
4544: if (!$uname) { $uname=$env{'user.name'}; }
4545: my $uhome=&homeserver($uname,$udomain);
4546: my $items='';
4547: foreach my $key (keys(%$storehash)) {
4548: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4549: }
4550: $items=~s/\&$//;
4551: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4552: }
4553:
4554: # --------------------------------------------------------- putstore interface
4555:
1.524 raeburn 4556: sub putstore {
1.715 albertel 4557: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4558: if (!$udomain) { $udomain=$env{'user.domain'}; }
4559: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4560: my $uhome=&homeserver($uname,$udomain);
4561: my $items='';
1.715 albertel 4562: foreach my $key (keys(%$storehash)) {
4563: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4564: }
1.715 albertel 4565: $items=~s/\&$//;
1.716 albertel 4566: my $esc_symb=&escape($symb);
4567: my $esc_v=&escape($version);
1.715 albertel 4568: my $reply =
1.716 albertel 4569: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4570: $uhome);
4571: if ($reply eq 'unknown_cmd') {
1.716 albertel 4572: # gfall back to way things use to be done
1.715 albertel 4573: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4574: $uname);
1.524 raeburn 4575: }
1.715 albertel 4576: return $reply;
4577: }
4578:
4579: sub old_putstore {
1.716 albertel 4580: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4581: if (!$udomain) { $udomain=$env{'user.domain'}; }
4582: if (!$uname) { $uname=$env{'user.name'}; }
4583: my $uhome=&homeserver($uname,$udomain);
4584: my %newstorehash;
1.800 albertel 4585: foreach my $item (keys(%$storehash)) {
4586: my $key = $version.':'.&escape($symb).':'.$item;
4587: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4588: }
4589: my $items='';
4590: my %allitems = ();
1.800 albertel 4591: foreach my $item (keys(%newstorehash)) {
4592: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4593: my $key = $1.':keys:'.$2;
4594: $allitems{$key} .= $3.':';
4595: }
1.800 albertel 4596: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4597: }
1.800 albertel 4598: foreach my $item (keys(%allitems)) {
4599: $allitems{$item} =~ s/\:$//;
4600: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4601: }
4602: $items=~s/\&$//;
4603: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4604: }
4605:
1.47 www 4606: # ------------------------------------------------------ critical put interface
4607:
4608: sub cput {
1.134 albertel 4609: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4610: if (!$udomain) { $udomain=$env{'user.domain'}; }
4611: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4612: my $uhome=&homeserver($uname,$udomain);
1.47 www 4613: my $items='';
1.800 albertel 4614: foreach my $item (keys(%$storehash)) {
4615: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4616: }
1.47 www 4617: $items=~s/\&$//;
1.134 albertel 4618: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4619: }
4620:
4621: # -------------------------------------------------------------- eget interface
4622:
4623: sub eget {
1.133 albertel 4624: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4625: my $items='';
1.800 albertel 4626: foreach my $item (@$storearr) {
4627: $items.=&escape($item).'&';
1.191 harris41 4628: }
1.12 www 4629: $items=~s/\&$//;
1.620 albertel 4630: if (!$udomain) { $udomain=$env{'user.domain'}; }
4631: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4632: my $uhome=&homeserver($uname,$udomain);
4633: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4634: my @pairs=split(/\&/,$rep);
4635: my %returnhash=();
1.42 www 4636: my $i=0;
1.800 albertel 4637: foreach my $item (@$storearr) {
4638: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4639: $i++;
1.191 harris41 4640: }
1.12 www 4641: return %returnhash;
4642: }
4643:
1.667 albertel 4644: # ------------------------------------------------------------ tmpput interface
4645: sub tmpput {
1.802 raeburn 4646: my ($storehash,$server,$context)=@_;
1.667 albertel 4647: my $items='';
1.800 albertel 4648: foreach my $item (keys(%$storehash)) {
4649: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4650: }
4651: $items=~s/\&$//;
1.802 raeburn 4652: if (defined($context)) {
4653: $items .= ':'.&escape($context);
4654: }
1.667 albertel 4655: return &reply("tmpput:$items",$server);
4656: }
4657:
4658: # ------------------------------------------------------------ tmpget interface
4659: sub tmpget {
1.688 albertel 4660: my ($token,$server)=@_;
4661: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4662: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4663: my %returnhash;
4664: foreach my $item (split(/\&/,$rep)) {
4665: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4666: next if ($key =~ /^error: 2 /);
1.667 albertel 4667: $returnhash{&unescape($key)}=&thaw_unescape($value);
4668: }
4669: return %returnhash;
4670: }
4671:
1.688 albertel 4672: # ------------------------------------------------------------ tmpget interface
4673: sub tmpdel {
4674: my ($token,$server)=@_;
4675: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4676: return &reply("tmpdel:$token",$server);
4677: }
4678:
1.765 albertel 4679: # -------------------------------------------------- portfolio access checking
4680:
4681: sub portfolio_access {
1.766 albertel 4682: my ($requrl) = @_;
1.765 albertel 4683: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4684: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4685: if ($result) {
4686: my %setters;
4687: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4688: my ($startblock,$endblock) =
4689: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4690: if ($startblock && $endblock) {
4691: return 'B';
4692: }
4693: } else {
4694: my ($startblock,$endblock) =
4695: &Apache::loncommon::blockcheck(\%setters,'port');
4696: if ($startblock && $endblock) {
4697: return 'B';
4698: }
4699: }
4700: }
1.765 albertel 4701: if ($result eq 'ok') {
1.766 albertel 4702: return 'F';
1.765 albertel 4703: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4704: return 'A';
1.765 albertel 4705: }
1.766 albertel 4706: return '';
1.765 albertel 4707: }
4708:
4709: sub get_portfolio_access {
1.767 albertel 4710: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4711:
4712: if (!ref($access_hash)) {
4713: my $current_perms = &get_portfile_permissions($udom,$unum);
4714: my %access_controls = &get_access_controls($current_perms,$group,
4715: $file_name);
4716: $access_hash = $access_controls{$file_name};
4717: }
4718:
1.765 albertel 4719: my ($public,$guest,@domains,@users,@courses,@groups);
4720: my $now = time;
4721: if (ref($access_hash) eq 'HASH') {
4722: foreach my $key (keys(%{$access_hash})) {
4723: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4724: if ($start > $now) {
4725: next;
4726: }
4727: if ($end && $end<$now) {
4728: next;
4729: }
4730: if ($scope eq 'public') {
4731: $public = $key;
4732: last;
4733: } elsif ($scope eq 'guest') {
4734: $guest = $key;
4735: } elsif ($scope eq 'domains') {
4736: push(@domains,$key);
4737: } elsif ($scope eq 'users') {
4738: push(@users,$key);
4739: } elsif ($scope eq 'course') {
4740: push(@courses,$key);
4741: } elsif ($scope eq 'group') {
4742: push(@groups,$key);
4743: }
4744: }
4745: if ($public) {
4746: return 'ok';
4747: }
4748: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4749: if ($guest) {
4750: return $guest;
4751: }
4752: } else {
4753: if (@domains > 0) {
4754: foreach my $domkey (@domains) {
4755: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4756: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4757: return 'ok';
4758: }
4759: }
4760: }
4761: }
4762: if (@users > 0) {
4763: foreach my $userkey (@users) {
1.865 raeburn 4764: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4765: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4766: if (ref($item) eq 'HASH') {
4767: if (($item->{'uname'} eq $env{'user.name'}) &&
4768: ($item->{'udom'} eq $env{'user.domain'})) {
4769: return 'ok';
4770: }
4771: }
4772: }
4773: }
1.765 albertel 4774: }
4775: }
4776: my %roleshash;
4777: my @courses_and_groups = @courses;
4778: push(@courses_and_groups,@groups);
4779: if (@courses_and_groups > 0) {
4780: my (%allgroups,%allroles);
4781: my ($start,$end,$role,$sec,$group);
4782: foreach my $envkey (%env) {
1.1060 raeburn 4783: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4784: my $cid = $2.'_'.$3;
4785: if ($1 eq 'gr') {
4786: $group = $4;
4787: $allgroups{$cid}{$group} = $env{$envkey};
4788: } else {
4789: if ($4 eq '') {
4790: $sec = 'none';
4791: } else {
4792: $sec = $4;
4793: }
4794: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4795: }
1.811 albertel 4796: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4797: my $cid = $2.'_'.$3;
4798: if ($4 eq '') {
4799: $sec = 'none';
4800: } else {
4801: $sec = $4;
4802: }
4803: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4804: }
4805: }
4806: if (keys(%allroles) == 0) {
4807: return;
4808: }
4809: foreach my $key (@courses_and_groups) {
4810: my %content = %{$$access_hash{$key}};
4811: my $cnum = $content{'number'};
4812: my $cdom = $content{'domain'};
4813: my $cid = $cdom.'_'.$cnum;
4814: if (!exists($allroles{$cid})) {
4815: next;
4816: }
4817: foreach my $role_id (keys(%{$content{'roles'}})) {
4818: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4819: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4820: my @status = @{$content{'roles'}{$role_id}{'access'}};
4821: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4822: foreach my $role (keys(%{$allroles{$cid}})) {
4823: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4824: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4825: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4826: if (grep/^all$/,@sections) {
4827: return 'ok';
4828: } else {
4829: if (grep/^$sec$/,@sections) {
4830: return 'ok';
4831: }
4832: }
4833: }
4834: }
4835: if (keys(%{$allgroups{$cid}}) == 0) {
4836: if (grep/^none$/,@groups) {
4837: return 'ok';
4838: }
4839: } else {
4840: if (grep/^all$/,@groups) {
4841: return 'ok';
4842: }
4843: foreach my $group (keys(%{$allgroups{$cid}})) {
4844: if (grep/^$group$/,@groups) {
4845: return 'ok';
4846: }
4847: }
4848: }
4849: }
4850: }
4851: }
4852: }
4853: }
4854: if ($guest) {
4855: return $guest;
4856: }
4857: }
4858: }
4859: return;
4860: }
4861:
4862: sub course_group_datechecker {
4863: my ($dates,$now,$status) = @_;
4864: my ($start,$end) = split(/\./,$dates);
4865: if (!$start && !$end) {
4866: return 'ok';
4867: }
4868: if (grep/^active$/,@{$status}) {
4869: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4870: return 'ok';
4871: }
4872: }
4873: if (grep/^previous$/,@{$status}) {
4874: if ($end > $now ) {
4875: return 'ok';
4876: }
4877: }
4878: if (grep/^future$/,@{$status}) {
4879: if ($start > $now) {
4880: return 'ok';
4881: }
4882: }
4883: return;
4884: }
4885:
4886: sub parse_portfolio_url {
4887: my ($url) = @_;
4888:
4889: my ($type,$udom,$unum,$group,$file_name);
4890:
1.823 albertel 4891: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4892: $type = 1;
4893: $udom = $1;
4894: $unum = $2;
4895: $file_name = $3;
1.823 albertel 4896: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4897: $type = 2;
4898: $udom = $1;
4899: $unum = $2;
4900: $group = $3;
4901: $file_name = $3.'/'.$4;
4902: }
4903: if (wantarray) {
4904: return ($type,$udom,$unum,$file_name,$group);
4905: }
4906: return $type;
4907: }
4908:
4909: sub is_portfolio_url {
4910: my ($url) = @_;
4911: return scalar(&parse_portfolio_url($url));
4912: }
4913:
1.798 raeburn 4914: sub is_portfolio_file {
4915: my ($file) = @_;
1.820 raeburn 4916: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4917: return 1;
4918: }
4919: return;
4920: }
4921:
1.976 raeburn 4922: sub usertools_access {
1.1084 ! raeburn 4923: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 4924: my ($access,%tools);
4925: if ($context eq '') {
4926: $context = 'tools';
4927: }
4928: if ($context eq 'requestcourses') {
4929: %tools = (
4930: official => 1,
4931: unofficial => 1,
1.1006 raeburn 4932: community => 1,
1.985 raeburn 4933: );
4934: } else {
4935: %tools = (
4936: aboutme => 1,
4937: blog => 1,
4938: portfolio => 1,
4939: );
4940: }
1.976 raeburn 4941: return if (!defined($tools{$tool}));
4942:
4943: if ((!defined($udom)) || (!defined($uname))) {
4944: $udom = $env{'user.domain'};
4945: $uname = $env{'user.name'};
4946: }
4947:
1.978 raeburn 4948: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4949: if ($action ne 'reload') {
1.985 raeburn 4950: if ($context eq 'requestcourses') {
4951: return $env{'environment.canrequest.'.$tool};
4952: } else {
4953: return $env{'environment.availabletools.'.$tool};
4954: }
4955: }
1.976 raeburn 4956: }
4957:
4958: my ($toolstatus,$inststatus);
4959:
1.985 raeburn 4960: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4961: ($action ne 'reload')) {
4962: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 4963: $inststatus = $env{'environment.inststatus'};
4964: } else {
1.1084 ! raeburn 4965: if (ref($userenvref) eq 'HASH') {
! 4966: $toolstatus = $userenvref->{$context.'.'.$tool};
! 4967: $inststatus = $userenvref->{'inststatus'};
! 4968: } else {
! 4969: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
! 4970: $toolstatus = $userenv{$context.'.'.$tool};
! 4971: $inststatus = $userenv{'inststatus'};
! 4972: }
1.976 raeburn 4973: }
4974:
4975: if ($toolstatus ne '') {
4976: if ($toolstatus) {
4977: $access = 1;
4978: } else {
4979: $access = 0;
4980: }
4981: return $access;
4982: }
4983:
1.1084 ! raeburn 4984: my ($is_adv,%domdef);
! 4985: if (ref($is_advref) eq 'HASH') {
! 4986: $is_adv = $is_advref->{'is_adv'};
! 4987: } else {
! 4988: $is_adv = &is_advanced_user($udom,$uname);
! 4989: }
! 4990: if (ref($domdefref) eq 'HASH') {
! 4991: %domdef = %{$domdefref};
! 4992: } else {
! 4993: %domdef = &get_domain_defaults($udom);
! 4994: }
1.976 raeburn 4995: if (ref($domdef{$tool}) eq 'HASH') {
4996: if ($is_adv) {
4997: if ($domdef{$tool}{'_LC_adv'} ne '') {
4998: if ($domdef{$tool}{'_LC_adv'}) {
4999: $access = 1;
5000: } else {
5001: $access = 0;
5002: }
5003: return $access;
5004: }
5005: }
5006: if ($inststatus ne '') {
5007: my ($hasaccess,$hasnoaccess);
5008: foreach my $affiliation (split(/:/,$inststatus)) {
5009: if ($domdef{$tool}{$affiliation} ne '') {
5010: if ($domdef{$tool}{$affiliation}) {
5011: $hasaccess = 1;
5012: } else {
5013: $hasnoaccess = 1;
5014: }
5015: }
5016: }
5017: if ($hasaccess || $hasnoaccess) {
5018: if ($hasaccess) {
5019: $access = 1;
5020: } elsif ($hasnoaccess) {
5021: $access = 0;
5022: }
5023: return $access;
5024: }
5025: } else {
5026: if ($domdef{$tool}{'default'} ne '') {
5027: if ($domdef{$tool}{'default'}) {
5028: $access = 1;
5029: } elsif ($domdef{$tool}{'default'} == 0) {
5030: $access = 0;
5031: }
5032: return $access;
5033: }
5034: }
5035: } else {
1.985 raeburn 5036: if ($context eq 'tools') {
5037: $access = 1;
5038: } else {
5039: $access = 0;
5040: }
1.976 raeburn 5041: return $access;
5042: }
5043: }
5044:
1.1050 raeburn 5045: sub is_course_owner {
5046: my ($cdom,$cnum,$udom,$uname) = @_;
5047: if (($udom eq '') || ($uname eq '')) {
5048: $udom = $env{'user.domain'};
5049: $uname = $env{'user.name'};
5050: }
5051: unless (($udom eq '') || ($uname eq '')) {
5052: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5053: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5054: return 1;
5055: } else {
5056: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5057: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5058: return 1;
5059: }
5060: }
5061: }
5062: }
5063: return;
5064: }
5065:
1.976 raeburn 5066: sub is_advanced_user {
5067: my ($udom,$uname) = @_;
5068: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5069: my %allroles;
5070: my $is_adv;
5071: foreach my $role (keys(%roleshash)) {
5072: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5073: my $area = '/'.$tdomain.'/'.$trest;
5074: if ($sec ne '') {
5075: $area .= '/'.$sec;
5076: }
5077: if (($area ne '') && ($trole ne '')) {
5078: my $spec=$trole.'.'.$area;
5079: if ($trole =~ /^cr\//) {
5080: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5081: } elsif ($trole ne 'gr') {
5082: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5083: }
5084: }
5085: }
5086: foreach my $role (keys(%allroles)) {
5087: last if ($is_adv);
5088: foreach my $item (split(/:/,$allroles{$role})) {
5089: if ($item ne '') {
5090: my ($privilege,$restrictions)=split(/&/,$item);
5091: if ($privilege eq 'adv') {
5092: $is_adv = 1;
5093: last;
5094: }
5095: }
5096: }
5097: }
5098: return $is_adv;
5099: }
1.798 raeburn 5100:
1.1035 raeburn 5101: sub check_can_request {
1.1036 raeburn 5102: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5103: my $canreq = 0;
5104: my ($types,$typename) = &Apache::loncommon::course_types();
5105: my @options = ('approval','validate','autolimit');
5106: my $optregex = join('|',@options);
5107: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5108: foreach my $type (@{$types}) {
5109: if (&usertools_access($env{'user.name'},
5110: $env{'user.domain'},
5111: $type,undef,'requestcourses')) {
5112: $canreq ++;
1.1036 raeburn 5113: if (ref($request_domains) eq 'HASH') {
5114: push(@{$request_domains->{$type}},$env{'user.domain'});
5115: }
1.1035 raeburn 5116: if ($dom eq $env{'user.domain'}) {
5117: $can_request->{$type} = 1;
5118: }
5119: }
5120: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5121: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5122: if (@curr > 0) {
1.1036 raeburn 5123: foreach my $item (@curr) {
5124: if (ref($request_domains) eq 'HASH') {
5125: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5126: if ($otherdom ne '') {
5127: if (ref($request_domains->{$type}) eq 'ARRAY') {
5128: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5129: push(@{$request_domains->{$type}},$otherdom);
5130: }
5131: } else {
5132: push(@{$request_domains->{$type}},$otherdom);
5133: }
5134: }
5135: }
5136: }
5137: unless($dom eq $env{'user.domain'}) {
5138: $canreq ++;
1.1035 raeburn 5139: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5140: $can_request->{$type} = 1;
5141: }
5142: }
5143: }
5144: }
5145: }
5146: }
5147: return $canreq;
5148: }
5149:
1.341 www 5150: # ---------------------------------------------- Custom access rule evaluation
5151:
5152: sub customaccess {
5153: my ($priv,$uri)=@_;
1.807 albertel 5154: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5155: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5156: $udom = &LONCAPA::clean_domain($udom);
5157: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5158: my $access=0;
1.800 albertel 5159: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5160: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5161: if ($type eq 'user') {
5162: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5163: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5164: if ($tdom) {
5165: if ($tdom ne $env{'user.domain'}) { next; }
5166: }
1.896 albertel 5167: if ($tuname) {
5168: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5169: }
5170: $access=($effect eq 'allow');
5171: last;
5172: }
5173: } else {
5174: if ($role) {
5175: if ($role ne $urole) { next; }
5176: }
5177: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5178: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5179: if ($tdom) {
5180: if ($tdom ne $udom) { next; }
5181: }
5182: if ($tcrs) {
5183: if ($tcrs ne $ucrs) { next; }
5184: }
5185: if ($tsec) {
5186: if ($tsec ne $usec) { next; }
5187: }
5188: $access=($effect eq 'allow');
5189: last;
5190: }
5191: if ($realm eq '' && $role eq '') {
5192: $access=($effect eq 'allow');
5193: }
1.402 bowersj2 5194: }
1.341 www 5195: }
5196: return $access;
5197: }
5198:
1.103 harris41 5199: # ------------------------------------------------- Check for a user privilege
1.12 www 5200:
5201: sub allowed {
1.810 raeburn 5202: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5203: my $ver_orguri=$uri;
1.439 www 5204: $uri=&deversion($uri);
1.152 www 5205: my $orguri=$uri;
1.52 www 5206: $uri=&declutter($uri);
1.809 raeburn 5207:
1.810 raeburn 5208: if ($priv eq 'evb') {
5209: # Evade communication block restrictions for specified role in a course
5210: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5211: return $1;
5212: } else {
5213: return;
5214: }
5215: }
5216:
1.620 albertel 5217: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5218: # Free bre access to adm and meta resources
1.775 albertel 5219: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5220: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5221: && ($priv eq 'bre')) {
1.14 www 5222: return 'F';
1.159 www 5223: }
5224:
1.545 banghart 5225: # Free bre access to user's own portfolio contents
1.714 raeburn 5226: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5227: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5228: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5229: my %setters;
5230: my ($startblock,$endblock) =
5231: &Apache::loncommon::blockcheck(\%setters,'port');
5232: if ($startblock && $endblock) {
5233: return 'B';
5234: } else {
5235: return 'F';
5236: }
1.545 banghart 5237: }
5238:
1.762 raeburn 5239: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5240: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5241: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5242: if (exists($env{'request.course.id'})) {
5243: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5244: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5245: if (($domain eq $cdom) && ($name eq $cnum)) {
5246: my $courseprivid=$env{'request.course.id'};
5247: $courseprivid=~s/\_/\//;
5248: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5249: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5250: return $1;
1.762 raeburn 5251: } else {
5252: if ($env{'request.course.sec'}) {
5253: $courseprivid.='/'.$env{'request.course.sec'};
5254: }
5255: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5256: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5257: return $2;
5258: }
1.714 raeburn 5259: }
5260: }
5261: }
5262: }
5263:
1.159 www 5264: # Free bre to public access
5265:
5266: if ($priv eq 'bre') {
1.238 www 5267: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5268: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5269: return 'F';
5270: }
1.238 www 5271: if ($copyright eq 'priv') {
5272: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5273: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5274: return '';
5275: }
5276: }
5277: if ($copyright eq 'domain') {
5278: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5279: unless (($env{'user.domain'} eq $1) ||
5280: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5281: return '';
5282: }
1.262 matthew 5283: }
1.620 albertel 5284: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5285: # Library role, so allow browsing of resources in this domain.
5286: return 'F';
1.238 www 5287: }
1.341 www 5288: if ($copyright eq 'custom') {
5289: unless (&customaccess($priv,$uri)) { return ''; }
5290: }
1.14 www 5291: }
1.264 matthew 5292: # Domain coordinator is trying to create a course
1.620 albertel 5293: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5294: # uri is the requested domain in this case.
5295: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5296: # a role of dc for the domain in question.
1.620 albertel 5297: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5298: }
1.29 www 5299:
1.52 www 5300: my $thisallowed='';
5301: my $statecond=0;
5302: my $courseprivid='';
5303:
1.1039 raeburn 5304: my $ownaccess;
1.1043 raeburn 5305: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5306: if (($priv eq 'bro') && ($env{'user.author'})) {
5307: if ($uri eq '') {
5308: $ownaccess = 1;
5309: } else {
5310: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5311: my $udom = $env{'user.domain'};
5312: my $uname = $env{'user.name'};
5313: if ($uri =~ m{^\Q$udom\E/?$}) {
5314: $ownaccess = 1;
1.1040 raeburn 5315: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5316: unless ($uri =~ m{\.\./}) {
5317: $ownaccess = 1;
5318: }
5319: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5320: my $now = time;
5321: if ($uri =~ m{^([^/]+)/?$}) {
5322: my $adom = $1;
5323: foreach my $key (keys(%env)) {
1.1042 raeburn 5324: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5325: my ($start,$end) = split('.',$env{$key});
5326: if (($now >= $start) && (!$end || $end < $now)) {
5327: $ownaccess = 1;
5328: last;
5329: }
5330: }
5331: }
5332: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5333: my $adom = $1;
5334: my $aname = $2;
1.1042 raeburn 5335: foreach my $role ('ca','aa') {
5336: if ($env{"user.role.$role./$adom/$aname"}) {
5337: my ($start,$end) =
5338: split('.',$env{"user.role.$role./$adom/$aname"});
5339: if (($now >= $start) && (!$end || $end < $now)) {
5340: $ownaccess = 1;
5341: last;
5342: }
1.1039 raeburn 5343: }
5344: }
5345: }
5346: }
5347: }
5348: }
5349: }
5350:
1.52 www 5351: # Course
5352:
1.620 albertel 5353: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5354: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5355: $thisallowed.=$1;
5356: }
1.52 www 5357: }
1.29 www 5358:
1.52 www 5359: # Domain
5360:
1.620 albertel 5361: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5362: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5363: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5364: $thisallowed.=$1;
5365: }
1.12 www 5366: }
1.52 www 5367:
5368: # Course: uri itself is a course
1.66 www 5369: my $courseuri=$uri;
5370: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5371: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5372:
1.620 albertel 5373: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5374: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5375: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5376: $thisallowed.=$1;
5377: }
1.12 www 5378: }
1.29 www 5379:
1.665 albertel 5380: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5381: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5382: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5383: $thisallowed='';
1.671 raeburn 5384: my ($match)=&is_on_map($uri);
5385: if ($match) {
5386: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5387: =~/\Q$priv\E\&([^\:]*)/) {
5388: $thisallowed.=$1;
5389: }
5390: } else {
1.705 albertel 5391: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5392: if ($refuri) {
5393: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5394: $thisallowed='F';
1.671 raeburn 5395: } else {
5396: $refuri=&declutter($refuri);
5397: my ($match) = &is_on_map($refuri);
5398: if ($match) {
5399: $thisallowed='F';
5400: }
1.669 raeburn 5401: }
1.671 raeburn 5402: }
5403: }
1.314 www 5404: }
1.492 albertel 5405:
1.766 albertel 5406: if ($priv eq 'bre'
5407: && $thisallowed ne 'F'
5408: && $thisallowed ne '2'
5409: && &is_portfolio_url($uri)) {
5410: $thisallowed = &portfolio_access($uri);
5411: }
5412:
1.52 www 5413: # Full access at system, domain or course-wide level? Exit.
1.29 www 5414: if ($thisallowed=~/F/) {
5415: return 'F';
5416: }
5417:
1.52 www 5418: # If this is generating or modifying users, exit with special codes
1.29 www 5419:
1.643 www 5420: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5421: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5422: my ($audom,$auname)=split('/',$uri);
1.643 www 5423: # no author name given, so this just checks on the general right to make a co-author in this domain
5424: unless ($auname) { return $thisallowed; }
5425: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5426: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5427: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5428: ($audom ne $env{'request.role.domain'}))) { return ''; }
5429: }
1.52 www 5430: return $thisallowed;
5431: }
5432: #
1.103 harris41 5433: # Gathered so far: system, domain and course wide privileges
1.52 www 5434: #
5435: # Course: See if uri or referer is an individual resource that is part of
5436: # the course
5437:
1.620 albertel 5438: if ($env{'request.course.id'}) {
1.232 www 5439:
1.620 albertel 5440: $courseprivid=$env{'request.course.id'};
5441: if ($env{'request.course.sec'}) {
5442: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5443: }
5444: $courseprivid=~s/\_/\//;
5445: my $checkreferer=1;
1.232 www 5446: my ($match,$cond)=&is_on_map($uri);
5447: if ($match) {
5448: $statecond=$cond;
1.620 albertel 5449: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5450: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5451: $thisallowed.=$1;
5452: $checkreferer=0;
5453: }
1.29 www 5454: }
1.83 www 5455:
1.148 www 5456: if ($checkreferer) {
1.620 albertel 5457: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5458: unless ($refuri) {
1.800 albertel 5459: foreach my $key (keys(%env)) {
5460: if ($key=~/^httpref\..*\*/) {
5461: my $pattern=$key;
1.156 www 5462: $pattern=~s/^httpref\.\/res\///;
1.148 www 5463: $pattern=~s/\*/\[\^\/\]\+/g;
5464: $pattern=~s/\//\\\//g;
1.152 www 5465: if ($orguri=~/$pattern/) {
1.800 albertel 5466: $refuri=$env{$key};
1.148 www 5467: }
5468: }
1.191 harris41 5469: }
1.148 www 5470: }
1.232 www 5471:
1.148 www 5472: if ($refuri) {
1.152 www 5473: $refuri=&declutter($refuri);
1.232 www 5474: my ($match,$cond)=&is_on_map($refuri);
5475: if ($match) {
5476: my $refstatecond=$cond;
1.620 albertel 5477: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5478: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5479: $thisallowed.=$1;
1.53 www 5480: $uri=$refuri;
5481: $statecond=$refstatecond;
1.52 www 5482: }
5483: }
1.148 www 5484: }
1.29 www 5485: }
1.52 www 5486: }
1.29 www 5487:
1.52 www 5488: #
1.103 harris41 5489: # Gathered now: all privileges that could apply, and condition number
1.52 www 5490: #
5491: #
5492: # Full or no access?
5493: #
1.29 www 5494:
1.52 www 5495: if ($thisallowed=~/F/) {
5496: return 'F';
5497: }
1.29 www 5498:
1.52 www 5499: unless ($thisallowed) {
5500: return '';
5501: }
1.29 www 5502:
1.52 www 5503: # Restrictions exist, deal with them
5504: #
5505: # C:according to course preferences
5506: # R:according to resource settings
5507: # L:unless locked
5508: # X:according to user session state
5509: #
5510:
5511: # Possibly locked functionality, check all courses
1.54 www 5512: # Locks might take effect only after 10 minutes cache expiration for other
5513: # courses, and 2 minutes for current course
1.52 www 5514:
5515: my $envkey;
5516: if ($thisallowed=~/L/) {
1.1000 raeburn 5517: foreach $envkey (keys(%env)) {
1.54 www 5518: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5519: my $courseid=$2;
5520: my $roleid=$1.'.'.$2;
1.92 www 5521: $courseid=~s/^\///;
1.54 www 5522: my $expiretime=600;
1.620 albertel 5523: if ($env{'request.role'} eq $roleid) {
1.54 www 5524: $expiretime=120;
5525: }
5526: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5527: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5528: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5529: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5530: }
1.620 albertel 5531: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5532: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5533: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5534: &log($env{'user.domain'},$env{'user.name'},
5535: $env{'user.home'},
1.57 www 5536: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5537: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5538: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5539: return '';
5540: }
5541: }
1.620 albertel 5542: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5543: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5544: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5545: &log($env{'user.domain'},$env{'user.name'},
5546: $env{'user.home'},
1.57 www 5547: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5548: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5549: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5550: return '';
5551: }
5552: }
5553: }
1.29 www 5554: }
1.52 www 5555: }
5556:
5557: #
5558: # Rest of the restrictions depend on selected course
5559: #
5560:
1.620 albertel 5561: unless ($env{'request.course.id'}) {
1.766 albertel 5562: if ($thisallowed eq 'A') {
5563: return 'A';
1.814 raeburn 5564: } elsif ($thisallowed eq 'B') {
5565: return 'B';
1.766 albertel 5566: } else {
5567: return '1';
5568: }
1.52 www 5569: }
1.29 www 5570:
1.52 www 5571: #
5572: # Now user is definitely in a course
5573: #
1.53 www 5574:
5575:
5576: # Course preferences
5577:
5578: if ($thisallowed=~/C/) {
1.620 albertel 5579: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5580: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5581: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5582: =~/\Q$rolecode\E/) {
1.689 albertel 5583: if ($priv ne 'pch') {
5584: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5585: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5586: $env{'request.course.id'});
5587: }
1.237 www 5588: return '';
5589: }
5590:
1.620 albertel 5591: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5592: =~/\Q$unamedom\E/) {
1.689 albertel 5593: if ($priv ne 'pch') {
5594: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5595: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5596: $env{'request.course.id'});
5597: }
1.54 www 5598: return '';
5599: }
1.53 www 5600: }
5601:
5602: # Resource preferences
5603:
5604: if ($thisallowed=~/R/) {
1.620 albertel 5605: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5606: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5607: if ($priv ne 'pch') {
5608: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5609: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5610: }
5611: return '';
1.54 www 5612: }
1.53 www 5613: }
1.30 www 5614:
1.246 www 5615: # Restricted by state or randomout?
1.30 www 5616:
1.52 www 5617: if ($thisallowed=~/X/) {
1.620 albertel 5618: if ($env{'acc.randomout'}) {
1.579 albertel 5619: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5620: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5621: return '';
5622: }
1.247 www 5623: }
5624: if (&condval($statecond)) {
1.52 www 5625: return '2';
5626: } else {
5627: return '';
5628: }
5629: }
1.30 www 5630:
1.766 albertel 5631: if ($thisallowed eq 'A') {
5632: return 'A';
1.814 raeburn 5633: } elsif ($thisallowed eq 'B') {
5634: return 'B';
1.766 albertel 5635: }
1.52 www 5636: return 'F';
1.232 www 5637: }
5638:
1.710 albertel 5639: sub split_uri_for_cond {
5640: my $uri=&deversion(&declutter(shift));
5641: my @uriparts=split(/\//,$uri);
5642: my $filename=pop(@uriparts);
5643: my $pathname=join('/',@uriparts);
5644: return ($pathname,$filename);
5645: }
1.232 www 5646: # --------------------------------------------------- Is a resource on the map?
5647:
5648: sub is_on_map {
1.710 albertel 5649: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5650: #Trying to find the conditional for the file
1.620 albertel 5651: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5652: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5653: if ($match) {
1.289 bowersj2 5654: return (1,$1);
5655: } else {
1.434 www 5656: return (0,0);
1.289 bowersj2 5657: }
1.12 www 5658: }
5659:
1.427 www 5660: # --------------------------------------------------------- Get symb from alias
5661:
5662: sub get_symb_from_alias {
5663: my $symb=shift;
5664: my ($map,$resid,$url)=&decode_symb($symb);
5665: # Already is a symb
5666: if ($url) { return $symb; }
5667: # Must be an alias
5668: my $aliassymb='';
5669: my %bighash;
1.620 albertel 5670: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5671: &GDBM_READER(),0640)) {
5672: my $rid=$bighash{'mapalias_'.$symb};
5673: if ($rid) {
5674: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5675: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5676: $resid,$bighash{'src_'.$rid});
1.427 www 5677: }
5678: untie %bighash;
5679: }
5680: return $aliassymb;
5681: }
5682:
1.12 www 5683: # ----------------------------------------------------------------- Define Role
5684:
5685: sub definerole {
5686: if (allowed('mcr','/')) {
5687: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5688: foreach my $role (split(':',$sysrole)) {
5689: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5690: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5691: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5692: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5693: return "refused:s:$crole&$cqual";
5694: }
5695: }
1.191 harris41 5696: }
1.800 albertel 5697: foreach my $role (split(':',$domrole)) {
5698: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5699: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5700: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5701: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5702: return "refused:d:$crole&$cqual";
5703: }
5704: }
1.191 harris41 5705: }
1.800 albertel 5706: foreach my $role (split(':',$courole)) {
5707: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5708: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5709: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5710: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5711: return "refused:c:$crole&$cqual";
5712: }
5713: }
1.191 harris41 5714: }
1.620 albertel 5715: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5716: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5717: "rolesdef_$rolename=".
5718: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5719: return reply($command,$env{'user.home'});
1.12 www 5720: } else {
5721: return 'refused';
5722: }
1.105 harris41 5723: }
5724:
5725: # ---------------- Make a metadata query against the network of library servers
5726:
5727: sub metadata_query {
1.244 matthew 5728: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5729: my %rhash;
1.845 albertel 5730: my %libserv = &all_library();
1.244 matthew 5731: my @server_list = (defined($server_array) ? @$server_array
5732: : keys(%libserv) );
5733: for my $server (@server_list) {
1.118 harris41 5734: unless ($custom or $customshow) {
5735: my $reply=&reply("querysend:".&escape($query),$server);
5736: $rhash{$server}=$reply;
5737: }
5738: else {
5739: my $reply=&reply("querysend:".&escape($query).':'.
5740: &escape($custom).':'.&escape($customshow),
5741: $server);
5742: $rhash{$server}=$reply;
5743: }
1.112 harris41 5744: }
1.118 harris41 5745: return \%rhash;
1.240 www 5746: }
5747:
5748: # ----------------------------------------- Send log queries and wait for reply
5749:
5750: sub log_query {
5751: my ($uname,$udom,$query,%filters)=@_;
5752: my $uhome=&homeserver($uname,$udom);
5753: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5754: my $uhost=&hostname($uhome);
1.800 albertel 5755: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5756: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5757: $uhome);
1.479 albertel 5758: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5759: return get_query_reply($queryid);
5760: }
5761:
1.818 raeburn 5762: # -------------------------- Update MySQL table for portfolio file
5763:
5764: sub update_portfolio_table {
1.821 raeburn 5765: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5766: if ($group ne '') {
5767: $file_name =~s /^\Q$group\E//;
5768: }
1.818 raeburn 5769: my $homeserver = &homeserver($uname,$udom);
5770: my $queryid=
1.821 raeburn 5771: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5772: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5773: my $reply = &get_query_reply($queryid);
5774: return $reply;
5775: }
5776:
1.899 raeburn 5777: # -------------------------- Update MySQL allusers table
5778:
5779: sub update_allusers_table {
5780: my ($uname,$udom,$names) = @_;
5781: my $homeserver = &homeserver($uname,$udom);
5782: my $queryid=
5783: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5784: 'lastname='.&escape($names->{'lastname'}).'%%'.
5785: 'firstname='.&escape($names->{'firstname'}).'%%'.
5786: 'middlename='.&escape($names->{'middlename'}).'%%'.
5787: 'generation='.&escape($names->{'generation'}).'%%'.
5788: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5789: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 5790: return;
1.899 raeburn 5791: }
5792:
1.508 raeburn 5793: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5794:
5795: sub fetch_enrollment_query {
1.511 raeburn 5796: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5797: my $homeserver;
1.547 raeburn 5798: my $maxtries = 1;
1.508 raeburn 5799: if ($context eq 'automated') {
5800: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5801: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5802: } else {
5803: $homeserver = &homeserver($cnum,$dom);
5804: }
1.838 albertel 5805: my $host=&hostname($homeserver);
1.506 raeburn 5806: my $cmd = '';
1.1000 raeburn 5807: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5808: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5809: }
5810: $cmd =~ s/%%$//;
5811: $cmd = &escape($cmd);
5812: my $query = 'fetchenrollment';
1.620 albertel 5813: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5814: unless ($queryid=~/^\Q$host\E\_/) {
5815: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5816: return 'error: '.$queryid;
5817: }
1.506 raeburn 5818: my $reply = &get_query_reply($queryid);
1.547 raeburn 5819: my $tries = 1;
5820: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5821: $reply = &get_query_reply($queryid);
5822: $tries ++;
5823: }
1.526 raeburn 5824: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5825: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5826: } else {
1.901 albertel 5827: my @responses = split(/:/,$reply);
1.515 raeburn 5828: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5829: foreach my $line (@responses) {
5830: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5831: $$replyref{$key} = $value;
5832: }
5833: } else {
1.506 raeburn 5834: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5835: foreach my $line (@responses) {
5836: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5837: $$replyref{$key} = $value;
5838: if ($value > 0) {
1.800 albertel 5839: foreach my $item (@{$$affiliatesref{$key}}) {
5840: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5841: my $destname = $pathname.'/'.$filename;
5842: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5843: if ($xml_classlist =~ /^error/) {
5844: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5845: } else {
1.506 raeburn 5846: if ( open(FILE,">$destname") ) {
5847: print FILE &unescape($xml_classlist);
5848: close(FILE);
1.526 raeburn 5849: } else {
5850: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5851: }
5852: }
5853: }
5854: }
5855: }
5856: }
5857: return 'ok';
5858: }
5859: return 'error';
5860: }
5861:
1.242 www 5862: sub get_query_reply {
5863: my $queryid=shift;
1.240 www 5864: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5865: my $reply='';
5866: for (1..100) {
5867: sleep 2;
5868: if (-e $replyfile.'.end') {
1.448 albertel 5869: if (open(my $fh,$replyfile)) {
1.904 albertel 5870: $reply = join('',<$fh>);
5871: close($fh);
1.240 www 5872: } else { return 'error: reply_file_error'; }
1.242 www 5873: return &unescape($reply);
5874: }
1.240 www 5875: }
1.242 www 5876: return 'timeout:'.$queryid;
1.240 www 5877: }
5878:
5879: sub courselog_query {
1.241 www 5880: #
5881: # possible filters:
5882: # url: url or symb
5883: # username
5884: # domain
5885: # action: view, submit, grade
5886: # start: timestamp
5887: # end: timestamp
5888: #
1.240 www 5889: my (%filters)=@_;
1.620 albertel 5890: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5891: if ($filters{'url'}) {
5892: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5893: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5894: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5895: }
1.620 albertel 5896: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5897: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5898: return &log_query($cname,$cdom,'courselog',%filters);
5899: }
5900:
5901: sub userlog_query {
1.858 raeburn 5902: #
5903: # possible filters:
5904: # action: log check role
5905: # start: timestamp
5906: # end: timestamp
5907: #
1.240 www 5908: my ($uname,$udom,%filters)=@_;
5909: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5910: }
5911:
1.506 raeburn 5912: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5913:
5914: sub auto_run {
1.508 raeburn 5915: my ($cnum,$cdom) = @_;
1.876 raeburn 5916: my $response = 0;
5917: my $settings;
5918: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5919: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5920: $settings = $domconfig{'autoenroll'};
5921: if ($settings->{'run'} eq '1') {
5922: $response = 1;
5923: }
5924: } else {
1.934 raeburn 5925: my $homeserver;
5926: if (&is_course($cdom,$cnum)) {
5927: $homeserver = &homeserver($cnum,$cdom);
5928: } else {
5929: $homeserver = &domain($cdom,'primary');
5930: }
5931: if ($homeserver ne 'no_host') {
5932: $response = &reply('autorun:'.$cdom,$homeserver);
5933: }
1.876 raeburn 5934: }
1.506 raeburn 5935: return $response;
5936: }
1.776 albertel 5937:
1.506 raeburn 5938: sub auto_get_sections {
1.508 raeburn 5939: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 5940: my $homeserver;
5941: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5942: $homeserver = &homeserver($cnum,$cdom);
5943: }
5944: if (!defined($homeserver)) {
5945: if ($cdom =~ /^$match_domain$/) {
5946: $homeserver = &domain($cdom,'primary');
5947: }
5948: }
5949: my @secs;
5950: if (defined($homeserver)) {
5951: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5952: unless ($response eq 'refused') {
5953: @secs = split(/:/,$response);
5954: }
1.506 raeburn 5955: }
5956: return @secs;
5957: }
1.776 albertel 5958:
1.506 raeburn 5959: sub auto_new_course {
1.508 raeburn 5960: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5961: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5962: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5963: return $response;
5964: }
1.776 albertel 5965:
1.506 raeburn 5966: sub auto_validate_courseID {
1.508 raeburn 5967: my ($cnum,$cdom,$inst_course_id) = @_;
5968: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5969: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5970: return $response;
5971: }
1.776 albertel 5972:
1.1007 raeburn 5973: sub auto_validate_instcode {
1.1020 raeburn 5974: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 5975: my ($homeserver,$response);
5976: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5977: $homeserver = &homeserver($cnum,$cdom);
5978: }
5979: if (!defined($homeserver)) {
5980: if ($cdom =~ /^$match_domain$/) {
5981: $homeserver = &domain($cdom,'primary');
5982: }
5983: }
1.1065 raeburn 5984: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
5985: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 5986: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
5987: return ($outcome,$description);
1.1007 raeburn 5988: }
5989:
1.506 raeburn 5990: sub auto_create_password {
1.873 raeburn 5991: my ($cnum,$cdom,$authparam,$udom) = @_;
5992: my ($homeserver,$response);
1.506 raeburn 5993: my $create_passwd = 0;
5994: my $authchk = '';
1.873 raeburn 5995: if ($udom =~ /^$match_domain$/) {
5996: $homeserver = &domain($udom,'primary');
5997: }
5998: if ($homeserver eq '') {
5999: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6000: $homeserver = &homeserver($cnum,$cdom);
6001: }
6002: }
6003: if ($homeserver eq '') {
6004: $authchk = 'nodomain';
1.506 raeburn 6005: } else {
1.873 raeburn 6006: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6007: if ($response eq 'refused') {
6008: $authchk = 'refused';
6009: } else {
1.901 albertel 6010: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6011: }
1.506 raeburn 6012: }
6013: return ($authparam,$create_passwd,$authchk);
6014: }
6015:
1.706 raeburn 6016: sub auto_photo_permission {
6017: my ($cnum,$cdom,$students) = @_;
6018: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6019: my ($outcome,$perm_reqd,$conditions) =
6020: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6021: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6022: return (undef,undef);
6023: }
1.706 raeburn 6024: return ($outcome,$perm_reqd,$conditions);
6025: }
6026:
6027: sub auto_checkphotos {
6028: my ($uname,$udom,$pid) = @_;
6029: my $homeserver = &homeserver($uname,$udom);
6030: my ($result,$resulttype);
6031: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6032: &escape($uname).':'.&escape($pid),
6033: $homeserver));
1.709 albertel 6034: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6035: return (undef,undef);
6036: }
1.706 raeburn 6037: if ($outcome) {
6038: ($result,$resulttype) = split(/:/,$outcome);
6039: }
6040: return ($result,$resulttype);
6041: }
6042:
6043: sub auto_photochoice {
6044: my ($cnum,$cdom) = @_;
6045: my $homeserver = &homeserver($cnum,$cdom);
6046: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6047: &escape($cdom),
6048: $homeserver)));
1.709 albertel 6049: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6050: return (undef,undef);
6051: }
1.706 raeburn 6052: return ($update,$comment);
6053: }
6054:
6055: sub auto_photoupdate {
6056: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6057: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6058: my $host=&hostname($homeserver);
1.706 raeburn 6059: my $cmd = '';
6060: my $maxtries = 1;
1.800 albertel 6061: foreach my $affiliate (keys(%{$affiliatesref})) {
6062: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6063: }
6064: $cmd =~ s/%%$//;
6065: $cmd = &escape($cmd);
6066: my $query = 'institutionalphotos';
6067: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6068: unless ($queryid=~/^\Q$host\E\_/) {
6069: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6070: return 'error: '.$queryid;
6071: }
6072: my $reply = &get_query_reply($queryid);
6073: my $tries = 1;
6074: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6075: $reply = &get_query_reply($queryid);
6076: $tries ++;
6077: }
6078: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6079: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6080: } else {
6081: my @responses = split(/:/,$reply);
6082: my $outcome = shift(@responses);
6083: foreach my $item (@responses) {
6084: my ($key,$value) = split(/=/,$item);
6085: $$photo{$key} = $value;
6086: }
6087: return $outcome;
6088: }
6089: return 'error';
6090: }
6091:
1.521 raeburn 6092: sub auto_instcode_format {
1.793 albertel 6093: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6094: $cat_order) = @_;
1.521 raeburn 6095: my $courses = '';
1.772 raeburn 6096: my @homeservers;
1.521 raeburn 6097: if ($caller eq 'global') {
1.841 albertel 6098: my %servers = &get_servers($codedom,'library');
6099: foreach my $tryserver (keys(%servers)) {
6100: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6101: push(@homeservers,$tryserver);
6102: }
1.584 raeburn 6103: }
1.1022 raeburn 6104: } elsif ($caller eq 'requests') {
6105: if ($codedom =~ /^$match_domain$/) {
6106: my $chome = &domain($codedom,'primary');
6107: unless ($chome eq 'no_host') {
6108: push(@homeservers,$chome);
6109: }
6110: }
1.521 raeburn 6111: } else {
1.772 raeburn 6112: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6113: }
1.793 albertel 6114: foreach my $code (keys(%{$instcodes})) {
6115: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6116: }
6117: chop($courses);
1.772 raeburn 6118: my $ok_response = 0;
6119: my $response;
6120: while (@homeservers > 0 && $ok_response == 0) {
6121: my $server = shift(@homeservers);
6122: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6123: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6124: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6125: split(/:/,$response);
1.772 raeburn 6126: %{$codes} = (%{$codes},&str2hash($codes_str));
6127: push(@{$codetitles},&str2array($codetitles_str));
6128: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6129: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6130: $ok_response = 1;
6131: }
6132: }
6133: if ($ok_response) {
1.521 raeburn 6134: return 'ok';
1.772 raeburn 6135: } else {
6136: return $response;
1.521 raeburn 6137: }
6138: }
6139:
1.792 raeburn 6140: sub auto_instcode_defaults {
6141: my ($domain,$returnhash,$code_order) = @_;
6142: my @homeservers;
1.841 albertel 6143:
6144: my %servers = &get_servers($domain,'library');
6145: foreach my $tryserver (keys(%servers)) {
6146: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6147: push(@homeservers,$tryserver);
6148: }
1.792 raeburn 6149: }
1.841 albertel 6150:
1.792 raeburn 6151: my $response;
1.841 albertel 6152: foreach my $server (@homeservers) {
1.792 raeburn 6153: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6154: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6155:
6156: foreach my $pair (split(/\&/,$response)) {
6157: my ($name,$value)=split(/\=/,$pair);
6158: if ($name eq 'code_order') {
6159: @{$code_order} = split(/\&/,&unescape($value));
6160: } else {
6161: $returnhash->{&unescape($name)}=&unescape($value);
6162: }
6163: }
6164: return 'ok';
1.792 raeburn 6165: }
1.841 albertel 6166:
6167: return $response;
1.1003 raeburn 6168: }
6169:
6170: sub auto_possible_instcodes {
1.1007 raeburn 6171: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6172: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6173: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6174: return;
6175: }
1.1003 raeburn 6176: my (@homeservers,$uhome);
6177: if (defined(&domain($domain,'primary'))) {
6178: $uhome=&domain($domain,'primary');
6179: push(@homeservers,&domain($domain,'primary'));
6180: } else {
6181: my %servers = &get_servers($domain,'library');
6182: foreach my $tryserver (keys(%servers)) {
6183: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6184: push(@homeservers,$tryserver);
6185: }
6186: }
6187: }
6188: my $response;
6189: foreach my $server (@homeservers) {
6190: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6191: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6192: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6193: split(':',$response);
6194: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6195: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6196: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6197: my ($name,$value)=split('=',$item);
6198: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6199: }
6200: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6201: my ($name,$value)=split('=',$item);
6202: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6203: }
6204: return 'ok';
6205: }
6206: return $response;
6207: }
1.792 raeburn 6208:
1.1010 raeburn 6209: sub auto_courserequest_checks {
6210: my ($dom) = @_;
1.1020 raeburn 6211: my ($homeserver,%validations);
6212: if ($dom =~ /^$match_domain$/) {
6213: $homeserver = &domain($dom,'primary');
6214: }
6215: unless ($homeserver eq 'no_host') {
6216: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6217: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6218: my @items = split(/&/,$response);
6219: foreach my $item (@items) {
6220: my ($key,$value) = split('=',$item);
6221: $validations{&unescape($key)} = &thaw_unescape($value);
6222: }
6223: }
6224: }
1.1010 raeburn 6225: return %validations;
6226: }
6227:
1.1020 raeburn 6228: sub auto_courserequest_validation {
6229: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6230: my ($homeserver,$response);
6231: if ($dom =~ /^$match_domain$/) {
6232: $homeserver = &domain($dom,'primary');
6233: }
6234: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6235:
1.1020 raeburn 6236: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6237: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6238: ':'.&escape($instcode).':'.&escape($instseclist),
6239: $homeserver));
6240: }
6241: return $response;
6242: }
6243:
1.777 albertel 6244: sub auto_validate_class_sec {
1.918 raeburn 6245: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6246: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6247: my $ownerlist;
6248: if (ref($owners) eq 'ARRAY') {
6249: $ownerlist = join(',',@{$owners});
6250: } else {
6251: $ownerlist = $owners;
6252: }
1.773 raeburn 6253: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6254: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6255: return $response;
6256: }
6257:
1.679 raeburn 6258: # ------------------------------------------------------- Course Group routines
6259:
6260: sub get_coursegroups {
1.809 raeburn 6261: my ($cdom,$cnum,$group,$namespace) = @_;
6262: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6263: }
6264:
1.679 raeburn 6265: sub modify_coursegroup {
6266: my ($cdom,$cnum,$groupsettings) = @_;
6267: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6268: }
6269:
1.809 raeburn 6270: sub toggle_coursegroup_status {
6271: my ($cdom,$cnum,$group,$action) = @_;
6272: my ($from_namespace,$to_namespace);
6273: if ($action eq 'delete') {
6274: $from_namespace = 'coursegroups';
6275: $to_namespace = 'deleted_groups';
6276: } else {
6277: $from_namespace = 'deleted_groups';
6278: $to_namespace = 'coursegroups';
6279: }
6280: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6281: if (my $tmp = &error(%curr_group)) {
6282: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6283: return ('read error',$tmp);
6284: } else {
6285: my %savedsettings = %curr_group;
1.809 raeburn 6286: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6287: my $deloutcome;
6288: if ($result eq 'ok') {
1.809 raeburn 6289: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6290: } else {
6291: return ('write error',$result);
6292: }
6293: if ($deloutcome eq 'ok') {
6294: return 'ok';
6295: } else {
6296: return ('delete error',$deloutcome);
6297: }
6298: }
6299: }
6300:
1.679 raeburn 6301: sub modify_group_roles {
1.957 raeburn 6302: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6303: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6304: my $role = 'gr/'.&escape($userprivs);
6305: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6306: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6307: if ($result eq 'ok') {
6308: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6309: }
1.679 raeburn 6310: return $result;
6311: }
6312:
6313: sub modify_coursegroup_membership {
6314: my ($cdom,$cnum,$membership) = @_;
6315: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6316: return $result;
6317: }
6318:
1.682 raeburn 6319: sub get_active_groups {
6320: my ($udom,$uname,$cdom,$cnum) = @_;
6321: my $now = time;
6322: my %groups = ();
6323: foreach my $key (keys(%env)) {
1.811 albertel 6324: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6325: my ($start,$end) = split(/\./,$env{$key});
6326: if (($end!=0) && ($end<$now)) { next; }
6327: if (($start!=0) && ($start>$now)) { next; }
6328: if ($1 eq $cdom && $2 eq $cnum) {
6329: $groups{$3} = $env{$key} ;
6330: }
6331: }
6332: }
6333: return %groups;
6334: }
6335:
1.683 raeburn 6336: sub get_group_membership {
6337: my ($cdom,$cnum,$group) = @_;
6338: return(&dump('groupmembership',$cdom,$cnum,$group));
6339: }
6340:
6341: sub get_users_groups {
6342: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6343: my @usersgroups;
1.683 raeburn 6344: my $cachetime=1800;
6345:
6346: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6347: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6348: if (defined($cached)) {
1.734 albertel 6349: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6350: } else {
6351: $grouplist = '';
1.816 raeburn 6352: my $courseurl = &courseid_to_courseurl($courseid);
6353: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 6354: my $access_end = $env{'course.'.$courseid.
6355: '.default_enrollment_end_date'};
6356: my $now = time;
6357: foreach my $key (keys(%roleshash)) {
6358: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6359: my $group = $1;
6360: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6361: my $start = $2;
6362: my $end = $1;
6363: if ($start == -1) { next; } # deleted from group
6364: if (($start!=0) && ($start>$now)) { next; }
6365: if (($end!=0) && ($end<$now)) {
6366: if ($access_end && $access_end < $now) {
6367: if ($access_end - $end < 86400) {
6368: push(@usersgroups,$group);
1.733 raeburn 6369: }
6370: }
1.817 raeburn 6371: next;
1.733 raeburn 6372: }
1.817 raeburn 6373: push(@usersgroups,$group);
1.683 raeburn 6374: }
6375: }
6376: }
1.817 raeburn 6377: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6378: $grouplist = join(':',@usersgroups);
6379: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6380: }
1.733 raeburn 6381: return @usersgroups;
1.683 raeburn 6382: }
6383:
6384: sub devalidate_getgroups_cache {
6385: my ($udom,$uname,$cdom,$cnum)=@_;
6386: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6387:
1.683 raeburn 6388: my $hashid="$udom:$uname:$courseid";
6389: &devalidate_cache_new('getgroups',$hashid);
6390: }
6391:
1.12 www 6392: # ------------------------------------------------------------------ Plain Text
6393:
6394: sub plaintext {
1.988 raeburn 6395: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6396: if ($short =~ m{^cr/}) {
1.758 albertel 6397: return (split('/',$short))[-1];
6398: }
1.742 raeburn 6399: if (!defined($cid)) {
6400: $cid = $env{'request.course.id'};
6401: }
6402: my %rolenames = (
1.1008 raeburn 6403: Course => 'std',
6404: Community => 'alt1',
1.742 raeburn 6405: );
1.1037 raeburn 6406: if ($cid ne '') {
6407: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6408: unless ($forcedefault) {
6409: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6410: &Apache::lonlocal::mt_escape(\$roletext);
6411: return &Apache::lonlocal::mt($roletext);
6412: }
6413: }
6414: }
6415: if ((defined($type)) && (defined($rolenames{$type})) &&
6416: (defined($rolenames{$type})) &&
6417: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6418: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6419: } elsif ($cid ne '') {
6420: my $crstype = $env{'course.'.$cid.'.type'};
6421: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6422: (defined($prp{$short}{$rolenames{$crstype}}))) {
6423: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6424: }
1.742 raeburn 6425: }
1.1037 raeburn 6426: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6427: }
6428:
6429: # ----------------------------------------------------------------- Assign Role
6430:
6431: sub assignrole {
1.957 raeburn 6432: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6433: $context)=@_;
1.21 www 6434: my $mrole;
6435: if ($role =~ /^cr\//) {
1.393 www 6436: my $cwosec=$url;
1.811 albertel 6437: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6438: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6439: my $refused = 1;
6440: if ($context eq 'requestcourses') {
6441: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6442: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6443: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6444: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6445: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6446: if ($crsenv{'internal.courseowner'} eq
6447: $env{'user.name'}.':'.$env{'user.domain'}) {
6448: $refused = '';
6449: }
6450: }
6451: }
6452: }
6453: }
6454: if ($refused) {
6455: &logthis('Refused custom assignrole: '.
6456: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6457: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6458: return 'refused';
6459: }
1.104 www 6460: }
1.21 www 6461: $mrole='cr';
1.678 raeburn 6462: } elsif ($role =~ /^gr\//) {
6463: my $cwogrp=$url;
1.811 albertel 6464: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6465: unless (&allowed('mdg',$cwogrp)) {
6466: &logthis('Refused group assignrole: '.
6467: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6468: $env{'user.name'}.' at '.$env{'user.domain'});
6469: return 'refused';
6470: }
6471: $mrole='gr';
1.21 www 6472: } else {
1.82 www 6473: my $cwosec=$url;
1.811 albertel 6474: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6475: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6476: my $refused;
6477: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6478: if (!(&allowed('c'.$role,$url))) {
6479: $refused = 1;
6480: }
6481: } else {
6482: $refused = 1;
6483: }
1.947 raeburn 6484: if ($refused) {
1.1045 raeburn 6485: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6486: if (!$selfenroll && $context eq 'course') {
6487: my %crsenv;
6488: if ($role eq 'cc' || $role eq 'co') {
6489: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6490: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6491: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6492: if ($crsenv{'internal.courseowner'} eq
6493: $env{'user.name'}.':'.$env{'user.domain'}) {
6494: $refused = '';
6495: }
6496: }
6497: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6498: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6499: if ($crsenv{'internal.courseowner'} eq
6500: $env{'user.name'}.':'.$env{'user.domain'}) {
6501: $refused = '';
6502: }
6503: }
6504: }
6505: }
6506: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6507: $refused = '';
1.1017 raeburn 6508: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6509: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6510: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6511: my $wrongcc;
6512: if ($cnum =~ /^$match_community$/) {
6513: $wrongcc = 1 if ($role eq 'cc');
6514: } else {
6515: $wrongcc = 1 if ($role eq 'co');
6516: }
6517: unless ($wrongcc) {
6518: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6519: if ($crsenv{'internal.courseowner'} eq
6520: $env{'user.name'}.':'.$env{'user.domain'}) {
6521: $refused = '';
6522: }
1.1017 raeburn 6523: }
6524: }
6525: }
6526: if ($refused) {
1.947 raeburn 6527: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6528: ' '.$role.' '.$end.' '.$start.' by '.
6529: $env{'user.name'}.' at '.$env{'user.domain'});
6530: return 'refused';
6531: }
1.932 raeburn 6532: }
1.104 www 6533: }
1.21 www 6534: $mrole=$role;
6535: }
1.620 albertel 6536: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6537: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6538: if ($end) { $command.='_'.$end; }
1.21 www 6539: if ($start) {
6540: if ($end) {
1.81 www 6541: $command.='_'.$start;
1.21 www 6542: } else {
1.81 www 6543: $command.='_0_'.$start;
1.21 www 6544: }
6545: }
1.739 raeburn 6546: my $origstart = $start;
6547: my $origend = $end;
1.957 raeburn 6548: my $delflag;
1.357 www 6549: # actually delete
6550: if ($deleteflag) {
1.373 www 6551: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6552: # modify command to delete the role
1.620 albertel 6553: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6554: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6555: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6556: # set start and finish to negative values for userrolelog
6557: $start=-1;
6558: $end=-1;
1.957 raeburn 6559: $delflag = 1;
1.357 www 6560: }
6561: }
6562: # send command
1.349 www 6563: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6564: # log new user role if status is ok
1.349 www 6565: if ($answer eq 'ok') {
1.663 raeburn 6566: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6567: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6568: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6569: unless ($role =~ /^gr/) {
6570: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6571: $origstart,$selfenroll,$context);
1.739 raeburn 6572: }
1.1053 raeburn 6573: if ($role eq 'cc') {
6574: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6575: }
1.349 www 6576: }
6577: return $answer;
1.169 harris41 6578: }
6579:
1.1053 raeburn 6580: sub autoupdate_coowners {
6581: my ($url,$end,$start,$uname,$udom) = @_;
6582: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6583: if (($cdom ne '') && ($cnum ne '')) {
6584: my $now = time;
6585: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6586: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6587: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6588: my $instcode = $coursehash{'internal.coursecode'};
6589: if ($instcode ne '') {
1.1056 raeburn 6590: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6591: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6592: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6593: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6594: if ($result eq 'valid') {
6595: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6596: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6597: push(@newcoowners,$coowner);
6598: }
6599: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6600: push(@newcoowners,$uname.':'.$udom);
6601: }
6602: @newcoowners = sort(@newcoowners);
6603: } else {
6604: push(@newcoowners,$uname.':'.$udom);
6605: }
6606: } else {
6607: if ($coursehash{'internal.co-owners'}) {
6608: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6609: unless ($coowner eq $uname.':'.$udom) {
6610: push(@newcoowners,$coowner);
6611: }
6612: }
6613: unless (@newcoowners > 0) {
6614: $delcoowners = 1;
6615: $coowners = '';
6616: }
6617: }
6618: }
6619: if (@newcoowners || $delcoowners) {
6620: &store_coowners($cdom,$cnum,$coursehash{'home'},
6621: $delcoowners,@newcoowners);
6622: }
6623: }
6624: }
6625: }
6626: }
6627: }
6628: }
6629:
6630: sub store_coowners {
6631: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6632: my $cid = $cdom.'_'.$cnum;
6633: my ($coowners,$delresult,$putresult);
6634: if (@newcoowners) {
6635: $coowners = join(',',@newcoowners);
6636: my %coownershash = (
6637: 'internal.co-owners' => $coowners,
6638: );
6639: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6640: if ($putresult eq 'ok') {
6641: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6642: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6643: }
6644: }
6645: }
6646: if ($delcoowners) {
6647: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6648: if ($delresult eq 'ok') {
6649: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6650: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6651: }
6652: }
6653: }
6654: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6655: my %crsinfo =
6656: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6657: if (ref($crsinfo{$cid}) eq 'HASH') {
6658: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6659: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6660: }
6661: }
6662: }
6663:
1.169 harris41 6664: # -------------------------------------------------- Modify user authentication
1.197 www 6665: # Overrides without validation
6666:
1.169 harris41 6667: sub modifyuserauth {
6668: my ($udom,$uname,$umode,$upass)=@_;
6669: my $uhome=&homeserver($uname,$udom);
1.197 www 6670: unless (&allowed('mau',$udom)) { return 'refused'; }
6671: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6672: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6673: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6674: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6675: &escape($upass),$uhome);
1.620 albertel 6676: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6677: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6678: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6679: &log($udom,,$uname,$uhome,
1.620 albertel 6680: 'Authentication changed by '.$env{'user.domain'}.', '.
6681: $env{'user.name'}.', '.$umode.
1.197 www 6682: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6683: unless ($reply eq 'ok') {
1.197 www 6684: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6685: return 'error: '.$reply;
6686: }
1.170 harris41 6687: return 'ok';
1.80 www 6688: }
6689:
1.81 www 6690: # --------------------------------------------------------------- Modify a user
1.80 www 6691:
1.81 www 6692: sub modifyuser {
1.206 matthew 6693: my ($udom, $uname, $uid,
6694: $umode, $upass, $first,
6695: $middle, $last, $gene,
1.1058 raeburn 6696: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6697: $udom= &LONCAPA::clean_domain($udom);
6698: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 6699: my $showcandelete = 'none';
6700: if (ref($candelete) eq 'ARRAY') {
6701: if (@{$candelete} > 0) {
6702: $showcandelete = join(', ',@{$candelete});
6703: }
6704: }
1.81 www 6705: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6706: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 6707: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6708: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6709: ' desiredhome not specified').
1.620 albertel 6710: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6711: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6712: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 6713: my $newuser;
6714: if ($uhome eq 'no_host') {
6715: $newuser = 1;
6716: }
1.80 www 6717: # ----------------------------------------------------------------- Create User
1.406 albertel 6718: if (($uhome eq 'no_host') &&
6719: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6720: my $unhome='';
1.844 albertel 6721: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6722: $unhome = $desiredhome;
1.620 albertel 6723: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6724: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6725: } else { # load balancing routine for determining $unhome
1.81 www 6726: my $loadm=10000000;
1.841 albertel 6727: my %servers = &get_servers($udom,'library');
6728: foreach my $tryserver (keys(%servers)) {
6729: my $answer=reply('load',$tryserver);
6730: if (($answer=~/\d+/) && ($answer<$loadm)) {
6731: $loadm=$answer;
6732: $unhome=$tryserver;
6733: }
1.80 www 6734: }
6735: }
6736: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6737: return 'error: unable to find a home server for '.$uname.
6738: ' in domain '.$udom;
1.80 www 6739: }
6740: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6741: &escape($upass),$unhome);
6742: unless ($reply eq 'ok') {
6743: return 'error: '.$reply;
6744: }
1.230 stredwic 6745: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6746: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6747: return 'error: unable verify users home machine.';
1.80 www 6748: }
1.209 matthew 6749: } # End of creation of new user
1.80 www 6750: # ---------------------------------------------------------------------- Add ID
6751: if ($uid) {
6752: $uid=~tr/A-Z/a-z/;
6753: my %uidhash=&idrget($udom,$uname);
1.196 www 6754: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6755: && (!$forceid)) {
1.80 www 6756: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6757: return 'error: user id "'.$uid.'" does not match '.
6758: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6759: }
6760: } else {
6761: &idput($udom,($uname => $uid));
6762: }
6763: }
6764: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6765: my @tmp=&get('environment',
1.899 raeburn 6766: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6767: 'permanentemail','inststatus'],
1.134 albertel 6768: $udom,$uname);
1.1075 raeburn 6769: my (%names,%oldnames);
1.313 matthew 6770: if ($tmp[0] =~ m/^error:.*/) {
6771: %names=();
6772: } else {
6773: %names = @tmp;
1.1075 raeburn 6774: %oldnames = %names;
1.313 matthew 6775: }
1.388 www 6776: #
1.1058 raeburn 6777: # If name, email and/or uid are blank (e.g., because an uploaded file
6778: # of users did not contain them), do not overwrite existing values
6779: # unless field is in $candelete array ref.
6780: #
6781:
6782: my @fields = ('firstname','middlename','lastname','generation',
6783: 'permanentemail','id');
6784: my %newvalues;
6785: if (ref($candelete) eq 'ARRAY') {
6786: foreach my $field (@fields) {
6787: if (grep(/^\Q$field\E$/,@{$candelete})) {
6788: if ($field eq 'firstname') {
6789: $names{$field} = $first;
6790: } elsif ($field eq 'middlename') {
6791: $names{$field} = $middle;
6792: } elsif ($field eq 'lastname') {
6793: $names{$field} = $last;
6794: } elsif ($field eq 'generation') {
6795: $names{$field} = $gene;
6796: } elsif ($field eq 'permanentemail') {
6797: $names{$field} = $email;
6798: } elsif ($field eq 'id') {
6799: $names{$field} = $uid;
6800: }
6801: }
6802: }
6803: }
1.388 www 6804: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6805: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6806: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6807: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6808: if ($email) {
6809: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6810: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6811: }
1.899 raeburn 6812: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6813: if (defined($inststatus)) {
6814: $names{'inststatus'} = '';
6815: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6816: if (ref($usertypes) eq 'HASH') {
6817: my @okstatuses;
6818: foreach my $item (split(/:/,$inststatus)) {
6819: if (defined($usertypes->{$item})) {
6820: push(@okstatuses,$item);
6821: }
6822: }
6823: if (@okstatuses) {
6824: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6825: }
6826: }
6827: }
1.1075 raeburn 6828: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 6829: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 6830: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 6831: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6832: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6833: } else {
6834: $logmsg .= ' during self creation';
6835: }
1.1075 raeburn 6836: my $changed;
6837: if ($newuser) {
6838: $changed = 1;
6839: } else {
6840: foreach my $field (@fields) {
6841: if ($names{$field} ne $oldnames{$field}) {
6842: $changed = 1;
6843: last;
6844: }
6845: }
6846: }
6847: unless ($changed) {
6848: $logmsg = 'No changes in user information needed for: '.$logmsg;
6849: &logthis($logmsg);
6850: return 'ok';
6851: }
6852: my $reply = &put('environment', \%names, $udom,$uname);
6853: if ($reply ne 'ok') {
6854: return 'error: '.$reply;
6855: }
6856: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
6857: &devalidate_cache_new('namescache',$uname.':'.$udom);
6858: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 6859: &logthis($logmsg);
1.134 albertel 6860: return 'ok';
1.80 www 6861: }
6862:
1.81 www 6863: # -------------------------------------------------------------- Modify student
1.80 www 6864:
1.81 www 6865: sub modifystudent {
6866: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6867: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6868: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6869: if (!$cid) {
1.620 albertel 6870: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6871: return 'not_in_class';
6872: }
1.80 www 6873: }
6874: # --------------------------------------------------------------- Make the user
1.81 www 6875: my $reply=&modifyuser
1.209 matthew 6876: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6877: $desiredhome,$email,$inststatus);
1.80 www 6878: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6879: # This will cause &modify_student_enrollment to get the uid from the
6880: # students environment
6881: $uid = undef if (!$forceid);
1.455 albertel 6882: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 6883: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 6884: return $reply;
6885: }
6886:
6887: sub modify_student_enrollment {
1.957 raeburn 6888: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 6889: my ($cdom,$cnum,$chome);
6890: if (!$cid) {
1.620 albertel 6891: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6892: return 'not_in_class';
6893: }
1.620 albertel 6894: $cdom=$env{'course.'.$cid.'.domain'};
6895: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 6896: } else {
6897: ($cdom,$cnum)=split(/_/,$cid);
6898: }
1.620 albertel 6899: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 6900: if (!$chome) {
1.457 raeburn 6901: $chome=&homeserver($cnum,$cdom);
1.297 matthew 6902: }
1.455 albertel 6903: if (!$chome) { return 'unknown_course'; }
1.297 matthew 6904: # Make sure the user exists
1.81 www 6905: my $uhome=&homeserver($uname,$udom);
6906: if (($uhome eq '') || ($uhome eq 'no_host')) {
6907: return 'error: no such user';
6908: }
1.297 matthew 6909: # Get student data if we were not given enough information
6910: if (!defined($first) || $first eq '' ||
6911: !defined($last) || $last eq '' ||
6912: !defined($uid) || $uid eq '' ||
6913: !defined($middle) || $middle eq '' ||
6914: !defined($gene) || $gene eq '') {
1.294 matthew 6915: # They did not supply us with enough data to enroll the student, so
6916: # we need to pick up more information.
1.297 matthew 6917: my %tmp = &get('environment',
1.294 matthew 6918: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 6919: ,$udom,$uname);
6920:
1.800 albertel 6921: #foreach my $key (keys(%tmp)) {
6922: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 6923: #}
1.294 matthew 6924: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6925: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6926: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 6927: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 6928: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6929: }
1.556 albertel 6930: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 6931: my $reply=cput('classlist',
6932: {"$uname:$udom" =>
1.515 raeburn 6933: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 6934: $cdom,$cnum);
1.81 www 6935: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6936: return 'error: '.$reply;
1.652 albertel 6937: } else {
6938: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 6939: }
1.297 matthew 6940: # Add student role to user
1.83 www 6941: my $uurl='/'.$cid;
1.81 www 6942: $uurl=~s/\_/\//g;
6943: if ($usec) {
6944: $uurl.='/'.$usec;
6945: }
1.957 raeburn 6946: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 6947: }
6948:
1.556 albertel 6949: sub format_name {
6950: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6951: my $name;
6952: if ($first ne 'lastname') {
6953: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6954: } else {
6955: if ($lastname=~/\S/) {
6956: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6957: $name=~s/\s+,/,/;
6958: } else {
6959: $name.= $firstname.' '.$middlename.' '.$generation;
6960: }
6961: }
6962: $name=~s/^\s+//;
6963: $name=~s/\s+$//;
6964: $name=~s/\s+/ /g;
6965: return $name;
6966: }
6967:
1.84 www 6968: # ------------------------------------------------- Write to course preferences
6969:
6970: sub writecoursepref {
6971: my ($courseid,%prefs)=@_;
6972: $courseid=~s/^\///;
6973: $courseid=~s/\_/\//g;
6974: my ($cdomain,$cnum)=split(/\//,$courseid);
6975: my $chome=homeserver($cnum,$cdomain);
6976: if (($chome eq '') || ($chome eq 'no_host')) {
6977: return 'error: no such course';
6978: }
6979: my $cstring='';
1.800 albertel 6980: foreach my $pref (keys(%prefs)) {
6981: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 6982: }
1.84 www 6983: $cstring=~s/\&$//;
6984: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6985: }
6986:
6987: # ---------------------------------------------------------- Make/modify course
6988:
6989: sub createcourse {
1.741 raeburn 6990: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 6991: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 6992: $url=&declutter($url);
6993: my $cid='';
1.1028 raeburn 6994: if ($context eq 'requestcourses') {
6995: my $can_create = 0;
6996: my ($ownername,$ownerdom) = split(':',$course_owner);
6997: if ($udom eq $ownerdom) {
6998: if (&usertools_access($ownername,$ownerdom,$category,undef,
6999: $context)) {
7000: $can_create = 1;
7001: }
7002: } else {
7003: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7004: $category);
7005: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7006: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7007: if (@curr > 0) {
7008: my @options = qw(approval validate autolimit);
7009: my $optregex = join('|',@options);
7010: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7011: $can_create = 1;
7012: }
7013: }
7014: }
7015: }
7016: if ($can_create) {
7017: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7018: unless (&allowed('ccc',$udom)) {
7019: return 'refused';
7020: }
1.1017 raeburn 7021: }
7022: } else {
7023: return 'refused';
7024: }
1.1028 raeburn 7025: } elsif (!&allowed('ccc',$udom)) {
7026: return 'refused';
1.84 www 7027: }
1.1011 raeburn 7028: # --------------------------------------------------------------- Get Unique ID
7029: my $uname;
7030: if ($cnum =~ /^$match_courseid$/) {
7031: my $chome=&homeserver($cnum,$udom,'true');
7032: if (($chome eq '') || ($chome eq 'no_host')) {
7033: $uname = $cnum;
7034: } else {
1.1038 raeburn 7035: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7036: }
7037: } else {
1.1038 raeburn 7038: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7039: }
7040: return $uname if ($uname =~ /^error/);
7041: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7042: if (!defined($course_server)) {
7043: if (defined(&domain($udom,'primary'))) {
7044: $course_server = &domain($udom,'primary');
7045: } else {
7046: $course_server = $env{'user.home'};
7047: }
7048: }
7049: my %host_servers =
7050: &Apache::lonnet::get_servers($udom,'library');
7051: unless ($host_servers{$course_server}) {
7052: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7053: }
1.84 www 7054: # ------------------------------------------------------------- Make the course
7055: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7056: $course_server);
1.84 www 7057: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7058: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7059: if (($uhome eq '') || ($uhome eq 'no_host')) {
7060: return 'error: no such course';
7061: }
1.271 www 7062: # ----------------------------------------------------------------- Course made
1.516 raeburn 7063: # log existence
1.1029 raeburn 7064: my $now = time;
1.918 raeburn 7065: my $newcourse = {
7066: $udom.'_'.$uname => {
1.921 raeburn 7067: description => $description,
7068: inst_code => $inst_code,
7069: owner => $course_owner,
7070: type => $crstype,
1.1029 raeburn 7071: creator => $env{'user.name'}.':'.
7072: $env{'user.domain'},
7073: created => $now,
7074: context => $context,
1.918 raeburn 7075: },
7076: };
1.921 raeburn 7077: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7078: # set toplevel url
1.271 www 7079: my $topurl=$url;
7080: unless ($nonstandard) {
7081: # ------------------------------------------ For standard courses, make top url
7082: my $mapurl=&clutter($url);
1.278 www 7083: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7084: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7085: <map>
7086: <resource id="1" type="start"></resource>
7087: <resource id="2" src="$mapurl"></resource>
7088: <resource id="3" type="finish"></resource>
7089: <link index="1" from="1" to="2"></link>
7090: <link index="2" from="2" to="3"></link>
7091: </map>
7092: ENDINITMAP
7093: $topurl=&declutter(
1.638 albertel 7094: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7095: );
7096: }
7097: # ----------------------------------------------------------- Write preferences
1.84 www 7098: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7099: ('description' => $description,
7100: 'url' => $topurl,
7101: 'internal.creator' => $env{'user.name'}.':'.
7102: $env{'user.domain'},
7103: 'internal.created' => $now,
7104: 'internal.creationcontext' => $context)
7105: );
1.84 www 7106: return '/'.$udom.'/'.$uname;
7107: }
7108:
1.1011 raeburn 7109: # ------------------------------------------------------------------- Create ID
7110: sub generate_coursenum {
1.1038 raeburn 7111: my ($udom,$crstype) = @_;
1.1011 raeburn 7112: my $domdesc = &domain($udom);
7113: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7114: my $first;
7115: if ($crstype eq 'Community') {
7116: $first = '0';
7117: } else {
7118: $first = int(1+rand(9));
7119: }
7120: my $uname=$first.
1.1011 raeburn 7121: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7122: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7123: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7124: # ----------------------------------------------- Make sure that does not exist
7125: my $uhome=&homeserver($uname,$udom,'true');
7126: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7127: if ($crstype eq 'Community') {
7128: $first = '0';
7129: } else {
7130: $first = int(1+rand(9));
7131: }
7132: $uname=$first.
1.1011 raeburn 7133: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7134: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7135: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7136: $uhome=&homeserver($uname,$udom,'true');
7137: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7138: return 'error: unable to generate unique course-ID';
7139: }
7140: }
7141: return $uname;
7142: }
7143:
1.813 albertel 7144: sub is_course {
7145: my ($cdom,$cnum) = @_;
7146: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7147: undef,'.');
1.813 albertel 7148: if (exists($courses{$cdom.'_'.$cnum})) {
7149: return 1;
7150: }
7151: return 0;
7152: }
7153:
1.1015 raeburn 7154: sub store_userdata {
7155: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7156: my $result;
1.1016 raeburn 7157: if ($datakey ne '') {
1.1013 raeburn 7158: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7159: if ($udom eq '' || $uname eq '') {
7160: $udom = $env{'user.domain'};
7161: $uname = $env{'user.name'};
7162: }
7163: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7164: if (($uhome eq '') || ($uhome eq 'no_host')) {
7165: $result = 'error: no_host';
7166: } else {
7167: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7168: $storehash->{'host'} = $perlvar{'lonHostID'};
7169:
7170: my $namevalue='';
7171: foreach my $key (keys(%{$storehash})) {
7172: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7173: }
7174: $namevalue=~s/\&$//;
7175: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 raeburn 7176: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 7177: }
7178: } else {
7179: $result = 'error: data to store was not a hash reference';
7180: }
7181: } else {
7182: $result= 'error: invalid requestkey';
7183: }
7184: return $result;
7185: }
7186:
1.21 www 7187: # ---------------------------------------------------------- Assign Custom Role
7188:
7189: sub assigncustomrole {
1.957 raeburn 7190: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7191: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7192: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7193: }
7194:
7195: # ----------------------------------------------------------------- Revoke Role
7196:
7197: sub revokerole {
1.957 raeburn 7198: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7199: my $now=time;
1.965 raeburn 7200: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7201: }
7202:
7203: # ---------------------------------------------------------- Revoke Custom Role
7204:
7205: sub revokecustomrole {
1.957 raeburn 7206: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7207: my $now=time;
1.357 www 7208: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7209: $deleteflag,$selfenroll,$context);
1.17 www 7210: }
7211:
1.533 banghart 7212: # ------------------------------------------------------------ Disk usage
1.535 albertel 7213: sub diskusage {
1.955 raeburn 7214: my ($udom,$uname,$directorypath,$getpropath)=@_;
7215: $directorypath =~ s/\/$//;
7216: my $listing=&reply('du2:'.&escape($directorypath).':'
7217: .&escape($getpropath).':'.&escape($uname).':'
7218: .&escape($udom),homeserver($uname,$udom));
7219: if ($listing eq 'unknown_cmd') {
7220: if ($getpropath) {
7221: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7222: }
7223: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7224: }
1.514 albertel 7225: return $listing;
1.512 banghart 7226: }
7227:
1.566 banghart 7228: sub is_locked {
7229: my ($file_name, $domain, $user) = @_;
7230: my @check;
7231: my $is_locked;
7232: push @check, $file_name;
1.613 albertel 7233: my %locked = &get('file_permissions',\@check,
1.620 albertel 7234: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7235: my ($tmp)=keys(%locked);
7236: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7237:
1.566 banghart 7238: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7239: $is_locked = 'false';
7240: foreach my $entry (@{$locked{$file_name}}) {
7241: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7242: $is_locked = 'true';
7243: last;
1.745 raeburn 7244: }
7245: }
1.566 banghart 7246: } else {
7247: $is_locked = 'false';
7248: }
7249: }
7250:
1.759 albertel 7251: sub declutter_portfile {
7252: my ($file) = @_;
1.833 albertel 7253: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7254: return $file;
7255: }
7256:
1.559 banghart 7257: # ------------------------------------------------------------- Mark as Read Only
7258:
7259: sub mark_as_readonly {
7260: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7261: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7262: my ($tmp)=keys(%current_permissions);
7263: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7264: foreach my $file (@{$files}) {
1.759 albertel 7265: $file = &declutter_portfile($file);
1.561 banghart 7266: push(@{$current_permissions{$file}},$what);
1.559 banghart 7267: }
1.613 albertel 7268: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7269: return;
7270: }
7271:
1.572 banghart 7272: # ------------------------------------------------------------Save Selected Files
7273:
7274: sub save_selected_files {
7275: my ($user, $path, @files) = @_;
7276: my $filename = $user."savedfiles";
1.573 banghart 7277: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7278: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7279: foreach my $file (@files) {
1.620 albertel 7280: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7281: }
7282: foreach my $file (@other_files) {
1.574 banghart 7283: print (OUT $file."\n");
1.572 banghart 7284: }
1.574 banghart 7285: close (OUT);
1.572 banghart 7286: return 'ok';
7287: }
7288:
1.574 banghart 7289: sub clear_selected_files {
7290: my ($user) = @_;
7291: my $filename = $user."savedfiles";
7292: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7293: print (OUT undef);
7294: close (OUT);
7295: return ("ok");
7296: }
7297:
1.572 banghart 7298: sub files_in_path {
7299: my ($user, $path) = @_;
7300: my $filename = $user."savedfiles";
7301: my %return_files;
1.574 banghart 7302: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7303: while (my $line_in = <IN>) {
1.574 banghart 7304: chomp ($line_in);
7305: my @paths_and_file = split (m!/!, $line_in);
7306: my $file_part = pop (@paths_and_file);
7307: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7308: $path_part.='/';
7309: my $path_and_file = $path_part.$file_part;
7310: if ($path_part eq $path) {
7311: $return_files{$file_part}= 'selected';
7312: }
7313: }
1.574 banghart 7314: close (IN);
7315: return (\%return_files);
1.572 banghart 7316: }
7317:
7318: # called in portfolio select mode, to show files selected NOT in current directory
7319: sub files_not_in_path {
7320: my ($user, $path) = @_;
7321: my $filename = $user."savedfiles";
7322: my @return_files;
7323: my $path_part;
1.800 albertel 7324: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7325: while (my $line = <IN>) {
1.572 banghart 7326: #ok, I know it's clunky, but I want it to work
1.800 albertel 7327: my @paths_and_file = split(m|/|, $line);
7328: my $file_part = pop(@paths_and_file);
7329: chomp($file_part);
7330: my $path_part = join('/', @paths_and_file);
1.572 banghart 7331: $path_part .= '/';
7332: my $path_and_file = $path_part.$file_part;
7333: if ($path_part ne $path) {
1.800 albertel 7334: push(@return_files, ($path_and_file));
1.572 banghart 7335: }
7336: }
1.800 albertel 7337: close(OUT);
1.574 banghart 7338: return (@return_files);
1.572 banghart 7339: }
7340:
1.745 raeburn 7341: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7342:
1.745 raeburn 7343: sub get_portfile_permissions {
7344: my ($domain,$user) = @_;
1.613 albertel 7345: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7346: my ($tmp)=keys(%current_permissions);
7347: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7348: return \%current_permissions;
7349: }
7350:
7351: #---------------------------------------------Get portfolio file access controls
7352:
1.749 raeburn 7353: sub get_access_controls {
1.745 raeburn 7354: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7355: my %access;
7356: my $real_file = $file;
7357: $file =~ s/\.meta$//;
1.745 raeburn 7358: if (defined($file)) {
1.749 raeburn 7359: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7360: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7361: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7362: }
7363: }
1.745 raeburn 7364: } else {
1.749 raeburn 7365: foreach my $key (keys(%{$current_permissions})) {
7366: if ($key =~ /\0accesscontrol$/) {
7367: if (defined($group)) {
7368: if ($key !~ m-^\Q$group\E/-) {
7369: next;
7370: }
7371: }
7372: my ($fullpath) = split(/\0/,$key);
7373: if (ref($$current_permissions{$key}) eq 'HASH') {
7374: foreach my $control (keys(%{$$current_permissions{$key}})) {
7375: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7376: }
7377: }
7378: }
7379: }
7380: }
7381: return %access;
7382: }
7383:
7384: sub modify_access_controls {
7385: my ($file_name,$changes,$domain,$user)=@_;
7386: my ($outcome,$deloutcome);
7387: my %store_permissions;
7388: my %new_values;
7389: my %new_control;
7390: my %translation;
7391: my @deletions = ();
7392: my $now = time;
7393: if (exists($$changes{'activate'})) {
7394: if (ref($$changes{'activate'}) eq 'HASH') {
7395: my @newitems = sort(keys(%{$$changes{'activate'}}));
7396: my $numnew = scalar(@newitems);
7397: for (my $i=0; $i<$numnew; $i++) {
7398: my $newkey = $newitems[$i];
7399: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7400: if ($newkey =~ /^\d+:/) {
7401: $newkey =~ s/^(\d+)/$newid/;
7402: $translation{$1} = $newid;
7403: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7404: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7405: $translation{$1} = $newid;
7406: }
1.749 raeburn 7407: $new_values{$file_name."\0".$newkey} =
7408: $$changes{'activate'}{$newitems[$i]};
7409: $new_control{$newkey} = $now;
7410: }
7411: }
7412: }
7413: my %todelete;
7414: my %changed_items;
7415: foreach my $action ('delete','update') {
7416: if (exists($$changes{$action})) {
7417: if (ref($$changes{$action}) eq 'HASH') {
7418: foreach my $key (keys(%{$$changes{$action}})) {
7419: my ($itemnum) = ($key =~ /^([^:]+):/);
7420: if ($action eq 'delete') {
7421: $todelete{$itemnum} = 1;
7422: } else {
7423: $changed_items{$itemnum} = $key;
7424: }
7425: }
1.745 raeburn 7426: }
7427: }
1.749 raeburn 7428: }
7429: # get lock on access controls for file.
7430: my $lockhash = {
7431: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7432: ':'.$env{'user.domain'},
7433: };
7434: my $tries = 0;
7435: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7436:
7437: while (($gotlock ne 'ok') && $tries <3) {
7438: $tries ++;
7439: sleep 1;
7440: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7441: }
7442: if ($gotlock eq 'ok') {
7443: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7444: my ($tmp)=keys(%curr_permissions);
7445: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7446: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7447: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7448: if (ref($curr_controls) eq 'HASH') {
7449: foreach my $control_item (keys(%{$curr_controls})) {
7450: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7451: if (defined($todelete{$itemnum})) {
7452: push(@deletions,$file_name."\0".$control_item);
7453: } else {
7454: if (defined($changed_items{$itemnum})) {
7455: $new_control{$changed_items{$itemnum}} = $now;
7456: push(@deletions,$file_name."\0".$control_item);
7457: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7458: } else {
7459: $new_control{$control_item} = $$curr_controls{$control_item};
7460: }
7461: }
1.745 raeburn 7462: }
7463: }
7464: }
1.970 raeburn 7465: my ($group);
7466: if (&is_course($domain,$user)) {
7467: ($group,my $file) = split(/\//,$file_name,2);
7468: }
1.749 raeburn 7469: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7470: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7471: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7472: # remove lock
7473: my @del_lock = ($file_name."\0".'locked_access_records');
7474: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7475: my $sqlresult =
1.970 raeburn 7476: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7477: $group);
1.749 raeburn 7478: } else {
7479: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7480: }
1.749 raeburn 7481: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7482: }
7483:
1.827 raeburn 7484: sub make_public_indefinitely {
7485: my ($requrl) = @_;
7486: my $now = time;
7487: my $action = 'activate';
7488: my $aclnum = 0;
7489: if (&is_portfolio_url($requrl)) {
7490: my (undef,$udom,$unum,$file_name,$group) =
7491: &parse_portfolio_url($requrl);
7492: my $current_perms = &get_portfile_permissions($udom,$unum);
7493: my %access_controls = &get_access_controls($current_perms,
7494: $group,$file_name);
7495: foreach my $key (keys(%{$access_controls{$file_name}})) {
7496: my ($num,$scope,$end,$start) =
7497: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7498: if ($scope eq 'public') {
7499: if ($start <= $now && $end == 0) {
7500: $action = 'none';
7501: } else {
7502: $action = 'update';
7503: $aclnum = $num;
7504: }
7505: last;
7506: }
7507: }
7508: if ($action eq 'none') {
7509: return 'ok';
7510: } else {
7511: my %changes;
7512: my $newend = 0;
7513: my $newstart = $now;
7514: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7515: $changes{$action}{$newkey} = {
7516: type => 'public',
7517: time => {
7518: start => $newstart,
7519: end => $newend,
7520: },
7521: };
7522: my ($outcome,$deloutcome,$new_values,$translation) =
7523: &modify_access_controls($file_name,\%changes,$udom,$unum);
7524: return $outcome;
7525: }
7526: } else {
7527: return 'invalid';
7528: }
7529: }
7530:
1.745 raeburn 7531: #------------------------------------------------------Get Marked as Read Only
7532:
7533: sub get_marked_as_readonly {
7534: my ($domain,$user,$what,$group) = @_;
7535: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7536: my @readonly_files;
1.629 banghart 7537: my $cmp1=$what;
7538: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7539: while (my ($file_name,$value) = each(%{$current_permissions})) {
7540: if (defined($group)) {
7541: if ($file_name !~ m-^\Q$group\E/-) {
7542: next;
7543: }
7544: }
1.561 banghart 7545: if (ref($value) eq "ARRAY"){
7546: foreach my $stored_what (@{$value}) {
1.629 banghart 7547: my $cmp2=$stored_what;
1.759 albertel 7548: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7549: $cmp2=join('',@{$stored_what});
1.745 raeburn 7550: }
1.629 banghart 7551: if ($cmp1 eq $cmp2) {
1.561 banghart 7552: push(@readonly_files, $file_name);
1.745 raeburn 7553: last;
1.563 banghart 7554: } elsif (!defined($what)) {
7555: push(@readonly_files, $file_name);
1.745 raeburn 7556: last;
1.561 banghart 7557: }
7558: }
1.745 raeburn 7559: }
1.561 banghart 7560: }
7561: return @readonly_files;
7562: }
1.577 banghart 7563: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7564:
1.577 banghart 7565: sub get_marked_as_readonly_hash {
1.745 raeburn 7566: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7567: my %readonly_files;
1.745 raeburn 7568: while (my ($file_name,$value) = each(%{$current_permissions})) {
7569: if (defined($group)) {
7570: if ($file_name !~ m-^\Q$group\E/-) {
7571: next;
7572: }
7573: }
1.577 banghart 7574: if (ref($value) eq "ARRAY"){
7575: foreach my $stored_what (@{$value}) {
1.745 raeburn 7576: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7577: foreach my $lock_descriptor(@{$stored_what}) {
7578: if ($lock_descriptor eq 'graded') {
7579: $readonly_files{$file_name} = 'graded';
7580: } elsif ($lock_descriptor eq 'handback') {
7581: $readonly_files{$file_name} = 'handback';
7582: } else {
7583: if (!exists($readonly_files{$file_name})) {
7584: $readonly_files{$file_name} = 'locked';
7585: }
7586: }
1.745 raeburn 7587: }
1.750 banghart 7588: }
1.577 banghart 7589: }
7590: }
7591: }
7592: return %readonly_files;
7593: }
1.559 banghart 7594: # ------------------------------------------------------------ Unmark as Read Only
7595:
7596: sub unmark_as_readonly {
1.629 banghart 7597: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7598: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7599: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7600: $file_name = &declutter_portfile($file_name);
1.634 albertel 7601: my $symb_crs = $what;
7602: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7603: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7604: my ($tmp)=keys(%current_permissions);
7605: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7606: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7607: foreach my $file (@readonly_files) {
1.759 albertel 7608: my $clean_file = &declutter_portfile($file);
7609: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7610: my $current_locks = $current_permissions{$file};
1.563 banghart 7611: my @new_locks;
7612: my @del_keys;
7613: if (ref($current_locks) eq "ARRAY"){
7614: foreach my $locker (@{$current_locks}) {
1.632 albertel 7615: my $compare=$locker;
1.749 raeburn 7616: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7617: $compare=join('',@{$locker});
1.746 raeburn 7618: if ($compare ne $symb_crs) {
7619: push(@new_locks, $locker);
7620: }
1.563 banghart 7621: }
7622: }
1.650 albertel 7623: if (scalar(@new_locks) > 0) {
1.563 banghart 7624: $current_permissions{$file} = \@new_locks;
7625: } else {
7626: push(@del_keys, $file);
1.613 albertel 7627: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7628: delete($current_permissions{$file});
1.563 banghart 7629: }
7630: }
1.561 banghart 7631: }
1.613 albertel 7632: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7633: return;
7634: }
1.512 banghart 7635:
1.17 www 7636: # ------------------------------------------------------------ Directory lister
7637:
7638: sub dirlist {
1.955 raeburn 7639: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7640: $uri=~s/^\///;
7641: $uri=~s/\/$//;
1.253 stredwic 7642: my ($udom, $uname);
1.955 raeburn 7643: if ($getuserdir) {
1.253 stredwic 7644: $udom = $userdomain;
7645: $uname = $username;
1.955 raeburn 7646: } else {
7647: (undef,$udom,$uname)=split(/\//,$uri);
7648: if(defined($userdomain)) {
7649: $udom = $userdomain;
7650: }
7651: if(defined($username)) {
7652: $uname = $username;
7653: }
1.253 stredwic 7654: }
1.955 raeburn 7655: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7656:
1.955 raeburn 7657: $dirRoot = $perlvar{'lonDocRoot'};
7658: if (defined($getpropath)) {
7659: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7660: $dirRoot =~ s/\/$//;
1.955 raeburn 7661: } elsif (defined($getuserdir)) {
7662: my $subdir=$uname.'__';
7663: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7664: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7665: ."/$udom/$subdir/$uname";
7666: } elsif (defined($alternateRoot)) {
7667: $dirRoot = $alternateRoot;
1.751 banghart 7668: }
1.253 stredwic 7669:
7670: if($udom) {
7671: if($uname) {
1.955 raeburn 7672: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7673: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7674: .':'.&escape($uname).':'.&escape($udom),
7675: &homeserver($uname,$udom));
7676: if ($listing eq 'unknown_cmd') {
7677: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7678: &homeserver($uname,$udom));
7679: } else {
7680: @listing_results = map { &unescape($_); } split(/:/,$listing);
7681: }
1.605 matthew 7682: if ($listing eq 'unknown_cmd') {
1.800 albertel 7683: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7684: &homeserver($uname,$udom));
1.605 matthew 7685: @listing_results = split(/:/,$listing);
7686: } else {
7687: @listing_results = map { &unescape($_); } split(/:/,$listing);
7688: }
7689: return @listing_results;
1.955 raeburn 7690: } elsif(!$alternateRoot) {
1.800 albertel 7691: my %allusers;
1.841 albertel 7692: my %servers = &get_servers($udom,'library');
1.955 raeburn 7693: foreach my $tryserver (keys(%servers)) {
7694: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7695: &escape($udom),$tryserver);
7696: if ($listing eq 'unknown_cmd') {
7697: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7698: $udom, $tryserver);
7699: } else {
7700: @listing_results = map { &unescape($_); } split(/:/,$listing);
7701: }
1.841 albertel 7702: if ($listing eq 'unknown_cmd') {
7703: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7704: $udom, $tryserver);
7705: @listing_results = split(/:/,$listing);
7706: } else {
7707: @listing_results =
7708: map { &unescape($_); } split(/:/,$listing);
7709: }
7710: if ($listing_results[0] ne 'no_such_dir' &&
7711: $listing_results[0] ne 'empty' &&
7712: $listing_results[0] ne 'con_lost') {
7713: foreach my $line (@listing_results) {
7714: my ($entry) = split(/&/,$line,2);
7715: $allusers{$entry} = 1;
7716: }
7717: }
1.253 stredwic 7718: }
7719: my $alluserstr='';
1.800 albertel 7720: foreach my $user (sort(keys(%allusers))) {
7721: $alluserstr.=$user.'&user:';
1.253 stredwic 7722: }
7723: $alluserstr=~s/:$//;
7724: return split(/:/,$alluserstr);
7725: } else {
1.800 albertel 7726: return ('missing user name');
1.253 stredwic 7727: }
1.955 raeburn 7728: } elsif(!defined($getpropath)) {
1.841 albertel 7729: my @all_domains = sort(&all_domains());
1.955 raeburn 7730: foreach my $domain (@all_domains) {
7731: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7732: }
7733: return @all_domains;
7734: } else {
1.800 albertel 7735: return ('missing domain');
1.275 stredwic 7736: }
7737: }
7738:
7739: # --------------------------------------------- GetFileTimestamp
7740: # This function utilizes dirlist and returns the date stamp for
7741: # when it was last modified. It will also return an error of -1
7742: # if an error occurs
7743:
7744: sub GetFileTimestamp {
1.955 raeburn 7745: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7746: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7747: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7748: my ($fileStat) =
7749: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7750: undef,$getuserdir);
1.275 stredwic 7751: my @stats = split('&', $fileStat);
7752: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7753: # @stats contains first the filename, then the stat output
7754: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7755: } else {
7756: return -1;
1.253 stredwic 7757: }
1.26 www 7758: }
7759:
1.712 albertel 7760: sub stat_file {
7761: my ($uri) = @_;
1.787 albertel 7762: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7763:
1.955 raeburn 7764: my ($udom,$uname,$file);
1.712 albertel 7765: if ($uri =~ m-^/(uploaded|editupload)/-) {
7766: ($udom,$uname,$file) =
1.811 albertel 7767: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7768: $file = 'userfiles/'.$file;
7769: }
7770: if ($uri =~ m-^/res/-) {
7771: ($udom,$uname) =
1.807 albertel 7772: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7773: $file = $uri;
7774: }
7775:
7776: if (!$udom || !$uname || !$file) {
7777: # unable to handle the uri
7778: return ();
7779: }
1.956 raeburn 7780: my $getpropath;
7781: if ($file =~ /^userfiles\//) {
7782: $getpropath = 1;
7783: }
1.955 raeburn 7784: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7785: my @stats = split('&', $result);
1.721 banghart 7786:
1.712 albertel 7787: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7788: shift(@stats); #filename is first
7789: return @stats;
7790: }
7791: return ();
7792: }
7793:
1.26 www 7794: # -------------------------------------------------------- Value of a Condition
7795:
1.713 albertel 7796: # gets the value of a specific preevaluated condition
7797: # stored in the string $env{user.state.<cid>}
7798: # or looks up a condition reference in the bighash and if if hasn't
7799: # already been evaluated recurses into docondval to get the value of
7800: # the condition, then memoizing it to
7801: # $env{user.state.<cid>.<condition>}
1.40 www 7802: sub directcondval {
7803: my $number=shift;
1.620 albertel 7804: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7805: &Apache::lonuserstate::evalstate();
7806: }
1.713 albertel 7807: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7808: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7809: } elsif ($number =~ /^_/) {
7810: my $sub_condition;
7811: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7812: &GDBM_READER(),0640)) {
7813: $sub_condition=$bighash{'conditions'.$number};
7814: untie(%bighash);
7815: }
7816: my $value = &docondval($sub_condition);
1.949 raeburn 7817: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7818: return $value;
7819: }
1.620 albertel 7820: if ($env{'user.state.'.$env{'request.course.id'}}) {
7821: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7822: } else {
7823: return 2;
7824: }
7825: }
7826:
1.713 albertel 7827: # get the collection of conditions for this resource
1.26 www 7828: sub condval {
7829: my $condidx=shift;
1.54 www 7830: my $allpathcond='';
1.713 albertel 7831: foreach my $cond (split(/\|/,$condidx)) {
7832: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7833: $allpathcond.=
7834: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7835: }
1.191 harris41 7836: }
1.54 www 7837: $allpathcond=~s/\|$//;
1.713 albertel 7838: return &docondval($allpathcond);
7839: }
7840:
7841: #evaluates an expression of conditions
7842: sub docondval {
7843: my ($allpathcond) = @_;
7844: my $result=0;
7845: if ($env{'request.course.id'}
7846: && defined($allpathcond)) {
7847: my $operand='|';
7848: my @stack;
7849: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7850: if ($chunk eq '(') {
7851: push @stack,($operand,$result);
7852: } elsif ($chunk eq ')') {
7853: my $before=pop @stack;
7854: if (pop @stack eq '&') {
7855: $result=$result>$before?$before:$result;
7856: } else {
7857: $result=$result>$before?$result:$before;
7858: }
7859: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7860: $operand=$chunk;
7861: } else {
7862: my $new=directcondval($chunk);
7863: if ($operand eq '&') {
7864: $result=$result>$new?$new:$result;
7865: } else {
7866: $result=$result>$new?$result:$new;
7867: }
7868: }
7869: }
1.26 www 7870: }
7871: return $result;
1.421 albertel 7872: }
7873:
7874: # ---------------------------------------------------- Devalidate courseresdata
7875:
7876: sub devalidatecourseresdata {
7877: my ($coursenum,$coursedomain)=@_;
7878: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7879: &devalidate_cache_new('courseres',$hashid);
1.28 www 7880: }
7881:
1.763 www 7882:
1.200 www 7883: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 7884: #
7885: # Parameters:
7886: # $coursenum - Number of the course.
7887: # $coursedomain - Domain at which the course was created.
7888: # Returns:
7889: # A hash of the course parameters along (I think) with timestamps
7890: # and version info.
1.877 foxr 7891:
1.624 albertel 7892: sub get_courseresdata {
7893: my ($coursenum,$coursedomain)=@_;
1.200 www 7894: my $coursehom=&homeserver($coursenum,$coursedomain);
7895: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7896: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 7897: my %dumpreply;
1.417 albertel 7898: unless (defined($cached)) {
1.624 albertel 7899: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 7900: $result=\%dumpreply;
1.251 albertel 7901: my ($tmp) = keys(%dumpreply);
7902: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 7903: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 7904: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7905: return $tmp;
1.416 albertel 7906: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 7907: $result=undef;
1.599 albertel 7908: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 7909: }
7910: }
1.624 albertel 7911: return $result;
7912: }
7913:
1.633 albertel 7914: sub devalidateuserresdata {
7915: my ($uname,$udom)=@_;
7916: my $hashid="$udom:$uname";
7917: &devalidate_cache_new('userres',$hashid);
7918: }
7919:
1.624 albertel 7920: sub get_userresdata {
7921: my ($uname,$udom)=@_;
7922: #most student don\'t have any data set, check if there is some data
7923: if (&EXT_cache_status($udom,$uname)) { return undef; }
7924:
7925: my $hashid="$udom:$uname";
7926: my ($result,$cached)=&is_cached_new('userres',$hashid);
7927: if (!defined($cached)) {
7928: my %resourcedata=&dump('resourcedata',$udom,$uname);
7929: $result=\%resourcedata;
7930: &do_cache_new('userres',$hashid,$result,600);
7931: }
7932: my ($tmp)=keys(%$result);
7933: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7934: return $result;
7935: }
7936: #error 2 occurs when the .db doesn't exist
7937: if ($tmp!~/error: 2 /) {
1.672 albertel 7938: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 7939: " Trying to get resource data for ".
7940: $uname." at ".$udom.": ".
7941: $tmp."</font>");
7942: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 7943: #&EXT_cache_set($udom,$uname);
7944: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 7945: undef($tmp); # not really an error so don't send it back
1.624 albertel 7946: }
7947: return $tmp;
7948: }
1.879 foxr 7949: #----------------------------------------------- resdata - return resource data
7950: # Purpose:
7951: # Return resource data for either users or for a course.
7952: # Parameters:
7953: # $name - Course/user name.
7954: # $domain - Name of the domain the user/course is registered on.
7955: # $type - Type of thing $name is (must be 'course' or 'user'
7956: # @which - Array of names of resources desired.
7957: # Returns:
7958: # The value of the first reasource in @which that is found in the
7959: # resource hash.
7960: # Exceptional Conditions:
7961: # If the $type passed in is not valid (not the string 'course' or
7962: # 'user', an undefined reference is returned.
7963: # If none of the resources are found, an undef is returned
1.624 albertel 7964: sub resdata {
7965: my ($name,$domain,$type,@which)=@_;
7966: my $result;
7967: if ($type eq 'course') {
7968: $result=&get_courseresdata($name,$domain);
7969: } elsif ($type eq 'user') {
7970: $result=&get_userresdata($name,$domain);
7971: }
7972: if (!ref($result)) { return $result; }
1.251 albertel 7973: foreach my $item (@which) {
1.927 albertel 7974: if (defined($result->{$item->[0]})) {
7975: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 7976: }
1.250 albertel 7977: }
1.291 albertel 7978: return undef;
1.200 www 7979: }
7980:
1.379 matthew 7981: #
7982: # EXT resource caching routines
7983: #
7984:
7985: sub clear_EXT_cache_status {
1.383 albertel 7986: &delenv('cache.EXT.');
1.379 matthew 7987: }
7988:
7989: sub EXT_cache_status {
7990: my ($target_domain,$target_user) = @_;
1.383 albertel 7991: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 7992: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 7993: # We know already the user has no data
7994: return 1;
7995: } else {
7996: return 0;
7997: }
7998: }
7999:
8000: sub EXT_cache_set {
8001: my ($target_domain,$target_user) = @_;
1.383 albertel 8002: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8003: #&appenv({$cachename => time});
1.379 matthew 8004: }
8005:
1.28 www 8006: # --------------------------------------------------------- Value of a Variable
1.58 www 8007: sub EXT {
1.715 albertel 8008:
1.395 albertel 8009: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8010: unless ($varname) { return ''; }
1.218 albertel 8011: #get real user name/domain, courseid and symb
8012: my $courseid;
1.359 albertel 8013: my $publicuser;
1.427 www 8014: if ($symbparm) {
8015: $symbparm=&get_symb_from_alias($symbparm);
8016: }
1.218 albertel 8017: if (!($uname && $udom)) {
1.790 albertel 8018: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8019: if (!$symbparm) { $symbparm=$cursymb; }
8020: } else {
1.620 albertel 8021: $courseid=$env{'request.course.id'};
1.218 albertel 8022: }
1.48 www 8023: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8024: my $rest;
1.320 albertel 8025: if (defined($therest[0])) {
1.48 www 8026: $rest=join('.',@therest);
8027: } else {
8028: $rest='';
8029: }
1.320 albertel 8030:
1.57 www 8031: my $qualifierrest=$qualifier;
8032: if ($rest) { $qualifierrest.='.'.$rest; }
8033: my $spacequalifierrest=$space;
8034: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8035: if ($realm eq 'user') {
1.48 www 8036: # --------------------------------------------------------------- user.resource
8037: if ($space eq 'resource') {
1.651 albertel 8038: if ( (defined($Apache::lonhomework::parsing_a_problem)
8039: || defined($Apache::lonhomework::parsing_a_task))
8040: &&
1.744 albertel 8041: ($symbparm eq &symbread()) ) {
8042: # if we are in the middle of processing the resource the
8043: # get the value we are planning on committing
8044: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8045: return $Apache::lonhomework::results{$qualifierrest};
8046: } else {
8047: return $Apache::lonhomework::history{$qualifierrest};
8048: }
1.335 albertel 8049: } else {
1.359 albertel 8050: my %restored;
1.620 albertel 8051: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8052: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8053: } else {
8054: %restored=&restore($symbparm,$courseid,$udom,$uname);
8055: }
1.335 albertel 8056: return $restored{$qualifierrest};
8057: }
1.48 www 8058: # ----------------------------------------------------------------- user.access
8059: } elsif ($space eq 'access') {
1.218 albertel 8060: # FIXME - not supporting calls for a specific user
1.48 www 8061: return &allowed($qualifier,$rest);
8062: # ------------------------------------------ user.preferences, user.environment
8063: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8064: if (($uname eq $env{'user.name'}) &&
8065: ($udom eq $env{'user.domain'})) {
8066: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8067: } else {
1.359 albertel 8068: my %returnhash;
8069: if (!$publicuser) {
8070: %returnhash=&userenvironment($udom,$uname,
8071: $qualifierrest);
8072: }
1.218 albertel 8073: return $returnhash{$qualifierrest};
8074: }
1.48 www 8075: # ----------------------------------------------------------------- user.course
8076: } elsif ($space eq 'course') {
1.218 albertel 8077: # FIXME - not supporting calls for a specific user
1.620 albertel 8078: return $env{join('.',('request.course',$qualifier))};
1.48 www 8079: # ------------------------------------------------------------------- user.role
8080: } elsif ($space eq 'role') {
1.218 albertel 8081: # FIXME - not supporting calls for a specific user
1.620 albertel 8082: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8083: if ($qualifier eq 'value') {
8084: return $role;
8085: } elsif ($qualifier eq 'extent') {
8086: return $where;
8087: }
8088: # ----------------------------------------------------------------- user.domain
8089: } elsif ($space eq 'domain') {
1.218 albertel 8090: return $udom;
1.48 www 8091: # ------------------------------------------------------------------- user.name
8092: } elsif ($space eq 'name') {
1.218 albertel 8093: return $uname;
1.48 www 8094: # ---------------------------------------------------- Any other user namespace
1.29 www 8095: } else {
1.359 albertel 8096: my %reply;
8097: if (!$publicuser) {
8098: %reply=&get($space,[$qualifierrest],$udom,$uname);
8099: }
8100: return $reply{$qualifierrest};
1.48 www 8101: }
1.236 www 8102: } elsif ($realm eq 'query') {
8103: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8104: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8105: [$spacequalifierrest]);
1.620 albertel 8106: return $env{'form.'.$spacequalifierrest};
1.236 www 8107: } elsif ($realm eq 'request') {
1.48 www 8108: # ------------------------------------------------------------- request.browser
8109: if ($space eq 'browser') {
1.430 www 8110: if ($qualifier eq 'textremote') {
1.676 albertel 8111: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8112: return 1;
8113: } else {
8114: return 0;
8115: }
8116: } else {
1.620 albertel 8117: return $env{'browser.'.$qualifier};
1.430 www 8118: }
1.57 www 8119: # ------------------------------------------------------------ request.filename
8120: } else {
1.620 albertel 8121: return $env{'request.'.$spacequalifierrest};
1.29 www 8122: }
1.28 www 8123: } elsif ($realm eq 'course') {
1.48 www 8124: # ---------------------------------------------------------- course.description
1.620 albertel 8125: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8126: } elsif ($realm eq 'resource') {
1.165 www 8127:
1.620 albertel 8128: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8129: if (!$symbparm) { $symbparm=&symbread(); }
8130: }
1.693 albertel 8131:
8132: if ($space eq 'title') {
8133: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8134: return &gettitle($symbparm);
8135: }
8136:
8137: if ($space eq 'map') {
8138: my ($map) = &decode_symb($symbparm);
8139: return &symbread($map);
8140: }
1.905 albertel 8141: if ($space eq 'filename') {
8142: if ($symbparm) {
8143: return &clutter((&decode_symb($symbparm))[2]);
8144: }
8145: return &hreflocation('',$env{'request.filename'});
8146: }
1.693 albertel 8147:
8148: my ($section, $group, @groups);
1.593 albertel 8149: my ($courselevelm,$courselevel);
1.539 albertel 8150: if ($symbparm && defined($courseid) &&
1.620 albertel 8151: $courseid eq $env{'request.course.id'}) {
1.165 www 8152:
1.218 albertel 8153: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8154:
1.60 www 8155: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8156: my $symbp=$symbparm;
1.735 albertel 8157: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8158:
8159: my $symbparm=$symbp.'.'.$spacequalifierrest;
8160: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8161:
1.620 albertel 8162: if (($env{'user.name'} eq $uname) &&
8163: ($env{'user.domain'} eq $udom)) {
8164: $section=$env{'request.course.sec'};
1.733 raeburn 8165: @groups = split(/:/,$env{'request.course.groups'});
8166: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8167: } else {
1.539 albertel 8168: if (! defined($usection)) {
1.551 albertel 8169: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8170: } else {
8171: $section = $usection;
8172: }
1.733 raeburn 8173: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8174: }
8175:
8176: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8177: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8178: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8179:
1.593 albertel 8180: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8181: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8182: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8183:
1.60 www 8184: # ----------------------------------------------------------- first, check user
1.624 albertel 8185:
8186: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8187: ([$courselevelr,'resource'],
8188: [$courselevelm,'map' ],
8189: [$courselevel, 'course' ]));
1.931 albertel 8190: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8191:
1.594 albertel 8192: # ------------------------------------------------ second, check some of course
1.684 raeburn 8193: my $coursereply;
1.691 raeburn 8194: if (@groups > 0) {
8195: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8196: $mapparm,$spacequalifierrest);
1.927 albertel 8197: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8198: }
1.96 www 8199:
1.684 raeburn 8200: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8201: $env{'course.'.$courseid.'.domain'},
8202: 'course',
8203: ([$seclevelr, 'resource'],
8204: [$seclevelm, 'map' ],
8205: [$seclevel, 'course' ],
8206: [$courselevelr,'resource']));
8207: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8208:
1.60 www 8209: # ------------------------------------------------------ third, check map parms
1.218 albertel 8210: my %parmhash=();
8211: my $thisparm='';
8212: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8213: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8214: &GDBM_READER(),0640)) {
1.218 albertel 8215: $thisparm=$parmhash{$symbparm};
8216: untie(%parmhash);
8217: }
1.927 albertel 8218: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8219: }
1.594 albertel 8220: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8221:
1.218 albertel 8222: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8223: my $filename;
8224: if (!$symbparm) { $symbparm=&symbread(); }
8225: if ($symbparm) {
1.409 www 8226: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8227: } else {
1.620 albertel 8228: $filename=$env{'request.filename'};
1.282 albertel 8229: }
8230: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8231: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8232: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8233: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8234:
1.927 albertel 8235: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8236: if ($symbparm && defined($courseid) &&
1.620 albertel 8237: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8238: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8239: $env{'course.'.$courseid.'.domain'},
8240: 'course',
1.927 albertel 8241: ([$courselevelm,'map' ],
8242: [$courselevel, 'course']));
8243: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8244: }
1.145 www 8245: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8246: unless ($space eq '0') {
1.336 albertel 8247: my @parts=split(/_/,$space);
8248: my $id=pop(@parts);
8249: my $part=join('_',@parts);
8250: if ($part eq '') { $part='0'; }
1.927 albertel 8251: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8252: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8253: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8254: }
1.395 albertel 8255: if ($recurse) { return undef; }
8256: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8257: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8258: # ---------------------------------------------------- Any other user namespace
8259: } elsif ($realm eq 'environment') {
8260: # ----------------------------------------------------------------- environment
1.620 albertel 8261: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8262: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8263: } else {
1.770 albertel 8264: if ($uname eq 'anonymous' && $udom eq '') {
8265: return '';
8266: }
1.219 albertel 8267: my %returnhash=&userenvironment($udom,$uname,
8268: $spacequalifierrest);
8269: return $returnhash{$spacequalifierrest};
8270: }
1.28 www 8271: } elsif ($realm eq 'system') {
1.48 www 8272: # ----------------------------------------------------------------- system.time
8273: if ($space eq 'time') {
8274: return time;
8275: }
1.696 albertel 8276: } elsif ($realm eq 'server') {
8277: # ----------------------------------------------------------------- system.time
8278: if ($space eq 'name') {
8279: return $ENV{'SERVER_NAME'};
8280: }
1.28 www 8281: }
1.48 www 8282: return '';
1.61 www 8283: }
8284:
1.927 albertel 8285: sub get_reply {
8286: my ($reply_value) = @_;
1.940 raeburn 8287: if (ref($reply_value) eq 'ARRAY') {
8288: if (wantarray) {
8289: return @$reply_value;
8290: }
8291: return $reply_value->[0];
8292: } else {
8293: return $reply_value;
1.927 albertel 8294: }
8295: }
8296:
1.691 raeburn 8297: sub check_group_parms {
8298: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8299: my @groupitems = ();
8300: my $resultitem;
1.927 albertel 8301: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8302: foreach my $group (@{$groups}) {
8303: foreach my $level (@levels) {
1.927 albertel 8304: my $item = $courseid.'.['.$group.'].'.$level->[0];
8305: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8306: }
8307: }
8308: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8309: $env{'course.'.$courseid.'.domain'},
8310: 'course',@groupitems);
8311: return $coursereply;
8312: }
8313:
8314: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8315: my ($courseid,@groups) = @_;
8316: @groups = sort(@groups);
1.691 raeburn 8317: return @groups;
8318: }
8319:
1.395 albertel 8320: sub packages_tab_default {
8321: my ($uri,$varname)=@_;
8322: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8323:
8324: my (@extension,@specifics,$do_default);
8325: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8326: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8327: if ($pack_type eq 'default') {
8328: $do_default=1;
8329: } elsif ($pack_type eq 'extension') {
8330: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8331: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8332: # only look at packages defaults for packages that this id is
1.738 albertel 8333: push(@specifics,[$package,$pack_type,$pack_part]);
8334: }
8335: }
8336: # first look for a package that matches the requested part id
8337: foreach my $package (@specifics) {
8338: my (undef,$pack_type,$pack_part)=@{$package};
8339: next if ($pack_part ne $part);
8340: if (defined($packagetab{"$pack_type&$name&default"})) {
8341: return $packagetab{"$pack_type&$name&default"};
8342: }
8343: }
8344: # look for any possible matching non extension_ package
8345: foreach my $package (@specifics) {
8346: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8347: if (defined($packagetab{"$pack_type&$name&default"})) {
8348: return $packagetab{"$pack_type&$name&default"};
8349: }
1.585 albertel 8350: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8351: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8352: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8353: }
8354: }
1.738 albertel 8355: # look for any posible extension_ match
8356: foreach my $package (@extension) {
8357: my ($package,$pack_type)=@{$package};
8358: if (defined($packagetab{"$pack_type&$name&default"})) {
8359: return $packagetab{"$pack_type&$name&default"};
8360: }
8361: if (defined($packagetab{$package."&$name&default"})) {
8362: return $packagetab{$package."&$name&default"};
8363: }
8364: }
8365: # look for a global default setting
8366: if ($do_default && defined($packagetab{"default&$name&default"})) {
8367: return $packagetab{"default&$name&default"};
8368: }
1.395 albertel 8369: return undef;
8370: }
8371:
1.334 albertel 8372: sub add_prefix_and_part {
8373: my ($prefix,$part)=@_;
8374: my $keyroot;
8375: if (defined($prefix) && $prefix !~ /^__/) {
8376: # prefix that has a part already
8377: $keyroot=$prefix;
8378: } elsif (defined($prefix)) {
8379: # prefix that is missing a part
8380: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8381: } else {
8382: # no prefix at all
8383: if (defined($part)) { $keyroot='_'.$part; }
8384: }
8385: return $keyroot;
8386: }
8387:
1.71 www 8388: # ---------------------------------------------------------------- Get metadata
8389:
1.599 albertel 8390: my %metaentry;
1.1070 www 8391: my %importedpartids;
1.71 www 8392: sub metadata {
1.176 www 8393: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8394: $uri=&declutter($uri);
1.288 albertel 8395: # if it is a non metadata possible uri return quickly
1.529 albertel 8396: if (($uri eq '') ||
8397: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8398: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 8399: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
8400: return undef;
8401: }
8402: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8403: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8404: return undef;
1.288 albertel 8405: }
1.73 www 8406: my $filename=$uri;
8407: $uri=~s/\.meta$//;
1.172 www 8408: #
8409: # Is the metadata already cached?
1.177 www 8410: # Look at timestamp of caching
1.172 www 8411: # Everything is cached by the main uri, libraries are never directly cached
8412: #
1.428 albertel 8413: if (!defined($liburi)) {
1.599 albertel 8414: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8415: if (defined($cached)) { return $result->{':'.$what}; }
8416: }
8417: {
1.1069 www 8418: # Imported parts would go here
1.1070 www 8419: my %importedids=();
8420: my @origfileimportpartids=();
1.1069 www 8421: my $importedparts=0;
1.172 www 8422: #
8423: # Is this a recursive call for a library?
8424: #
1.599 albertel 8425: # if (! exists($metacache{$uri})) {
8426: # $metacache{$uri}={};
8427: # }
1.924 albertel 8428: my $cachetime = 60*60;
1.171 www 8429: if ($liburi) {
8430: $liburi=&declutter($liburi);
8431: $filename=$liburi;
1.401 bowersj2 8432: } else {
1.599 albertel 8433: &devalidate_cache_new('meta',$uri);
8434: undef(%metaentry);
1.401 bowersj2 8435: }
1.140 www 8436: my %metathesekeys=();
1.73 www 8437: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8438: my $metastring;
1.924 albertel 8439: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8440: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8441: $metastring =
1.929 albertel 8442: &Apache::lonnet::ssi_body($which,
1.924 albertel 8443: ('grade_target' => 'meta'));
8444: $cachetime = 1; # only want this cached in the child not long term
8445: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8446: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8447: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8448: $metastring=&getfile($file);
1.489 albertel 8449: }
1.208 albertel 8450: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8451: my $token;
1.140 www 8452: undef %metathesekeys;
1.71 www 8453: while ($token=$parser->get_token) {
1.339 albertel 8454: if ($token->[0] eq 'S') {
8455: if (defined($token->[2]->{'package'})) {
1.172 www 8456: #
8457: # This is a package - get package info
8458: #
1.339 albertel 8459: my $package=$token->[2]->{'package'};
8460: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8461: if (defined($token->[2]->{'id'})) {
8462: $keyroot.='_'.$token->[2]->{'id'};
8463: }
1.599 albertel 8464: if ($metaentry{':packages'}) {
8465: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8466: } else {
1.599 albertel 8467: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8468: }
1.736 albertel 8469: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8470: my $part=$keyroot;
8471: $part=~s/^\_//;
1.736 albertel 8472: if ($pack_entry=~/^\Q$package\E\&/ ||
8473: $pack_entry=~/^\Q$package\E_0\&/) {
8474: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8475: # ignore package.tab specified default values
8476: # here &package_tab_default() will fetch those
8477: if ($subp eq 'default') { next; }
1.736 albertel 8478: my $value=$packagetab{$pack_entry};
1.432 albertel 8479: my $unikey;
8480: if ($pack =~ /_0$/) {
8481: $unikey='parameter_0_'.$name;
8482: $part=0;
8483: } else {
8484: $unikey='parameter'.$keyroot.'_'.$name;
8485: }
1.339 albertel 8486: if ($subp eq 'display') {
8487: $value.=' [Part: '.$part.']';
8488: }
1.599 albertel 8489: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8490: $metathesekeys{$unikey}=1;
1.599 albertel 8491: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8492: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8493: }
1.599 albertel 8494: if (defined($metaentry{':'.$unikey.'.default'})) {
8495: $metaentry{':'.$unikey}=
8496: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8497: }
1.339 albertel 8498: }
8499: }
8500: } else {
1.172 www 8501: #
8502: # This is not a package - some other kind of start tag
1.339 albertel 8503: #
8504: my $entry=$token->[1];
1.1068 www 8505: my $unikey='';
1.175 www 8506:
1.339 albertel 8507: if ($entry eq 'import') {
1.175 www 8508: #
8509: # Importing a library here
1.339 albertel 8510: #
1.1067 www 8511: my $location=$parser->get_text('/import');
8512: my $dir=$filename;
8513: $dir=~s|[^/]*$||;
8514: $location=&filelocation($dir,$location);
1.1069 www 8515:
1.1068 www 8516: my $importmode=$token->[2]->{'importmode'};
8517: if ($importmode eq 'problem') {
1.1069 www 8518: # Import as problem/response
1.1068 www 8519: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8520: } elsif ($importmode eq 'part') {
8521: # Import as part(s)
1.1069 www 8522: $importedparts=1;
8523: # We need to get the original file and the imported file to get the part order correct
8524: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
8525: # Load and inspect original file
1.1070 www 8526: if ($#origfileimportpartids<0) {
8527: undef(%importedpartids);
8528: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
8529: my $origfile=&getfile($origfilelocation);
8530: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8531: }
8532:
1.1069 www 8533: # Load and inspect imported file
8534: my $impfile=&getfile($location);
8535: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8536: if ($#impfilepartids>=0) {
8537: # This problem had parts
1.1070 www 8538: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 8539: } else {
8540: # Importing by turning a single problem into a problem part
8541: # It gets the import-tags ID as part-ID
8542: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 8543: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 8544: }
1.1068 www 8545: } else {
8546: # Normal import
8547: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8548: if (defined($token->[2]->{'id'})) {
8549: $unikey.='_'.$token->[2]->{'id'};
8550: }
1.1067 www 8551: }
8552:
1.339 albertel 8553: if ($depthcount<20) {
1.736 albertel 8554: my $metadata =
8555: &metadata($uri,'keys', $location,$unikey,
8556: $depthcount+1);
8557: foreach my $meta (split(',',$metadata)) {
8558: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8559: $metathesekeys{$meta}=1;
1.339 albertel 8560: }
1.1068 www 8561:
8562: }
1.1067 www 8563: } else {
8564: #
8565: # Not importing, some other kind of non-package, non-library start tag
8566: #
8567: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
8568: if (defined($token->[2]->{'id'})) {
8569: $unikey.='_'.$token->[2]->{'id'};
8570: }
1.339 albertel 8571: if (defined($token->[2]->{'name'})) {
8572: $unikey.='_'.$token->[2]->{'name'};
8573: }
8574: $metathesekeys{$unikey}=1;
1.736 albertel 8575: foreach my $param (@{$token->[3]}) {
8576: $metaentry{':'.$unikey.'.'.$param} =
8577: $token->[2]->{$param};
1.339 albertel 8578: }
8579: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8580: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8581: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8582: # only ws inside the tag, and not in default, so use default
8583: # as value
1.599 albertel 8584: $metaentry{':'.$unikey}=$default;
1.908 albertel 8585: } elsif ( $internaltext =~ /\S/ ) {
8586: # something interesting inside the tag
8587: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8588: } else {
1.908 albertel 8589: # no interesting values, don't set a default
1.339 albertel 8590: }
1.172 www 8591: # end of not-a-package not-a-library import
1.339 albertel 8592: }
1.172 www 8593: # end of not-a-package start tag
1.339 albertel 8594: }
1.172 www 8595: # the next is the end of "start tag"
1.339 albertel 8596: }
8597: }
1.483 albertel 8598: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8599: $extension = lc($extension);
8600: if ($extension eq 'htm') { $extension='html'; }
8601:
1.737 albertel 8602: foreach my $key (keys(%packagetab)) {
1.483 albertel 8603: #no specific packages #how's our extension
8604: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8605: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8606: \%metathesekeys);
8607: }
1.883 albertel 8608:
8609: if (!exists($metaentry{':packages'})
8610: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8611: foreach my $key (keys(%packagetab)) {
1.483 albertel 8612: #no specific packages well let's get default then
8613: if ($key!~/^default&/) { next; }
1.488 albertel 8614: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8615: \%metathesekeys);
8616: }
8617: }
1.338 www 8618: # are there custom rights to evaluate
1.599 albertel 8619: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8620:
1.338 www 8621: #
8622: # Importing a rights file here
1.339 albertel 8623: #
8624: unless ($depthcount) {
1.599 albertel 8625: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8626: my $dir=$filename;
8627: $dir=~s|[^/]*$||;
8628: $location=&filelocation($dir,$location);
1.736 albertel 8629: my $rights_metadata =
8630: &metadata($uri,'keys',$location,'_rights',
8631: $depthcount+1);
8632: foreach my $rights (split(',',$rights_metadata)) {
8633: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8634: $metathesekeys{$rights}=1;
1.339 albertel 8635: }
8636: }
8637: }
1.737 albertel 8638: # uniqifiy package listing
8639: my %seen;
8640: my @uniq_packages =
8641: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8642: $metaentry{':packages'} = join(',',@uniq_packages);
8643:
1.1070 www 8644: if ($importedparts) {
8645: # We had imported parts and need to rebuild partorder
8646: $metaentry{':partorder'}='';
8647: $metathesekeys{'partorder'}=1;
8648: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
8649: if ($origfileimportpartids[$index] eq 'part') {
8650: # original part, part of the problem
8651: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
8652: } else {
8653: # we have imported parts at this position
8654: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
8655: }
8656: }
8657: $metaentry{':partorder'}=~s/^\,//;
8658: }
8659:
1.737 albertel 8660: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8661: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8662: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8663: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8664: # this is the end of "was not already recently cached
1.71 www 8665: }
1.599 albertel 8666: return $metaentry{':'.$what};
1.261 albertel 8667: }
8668:
1.488 albertel 8669: sub metadata_create_package_def {
1.483 albertel 8670: my ($uri,$key,$package,$metathesekeys)=@_;
8671: my ($pack,$name,$subp)=split(/\&/,$key);
8672: if ($subp eq 'default') { next; }
8673:
1.599 albertel 8674: if (defined($metaentry{':packages'})) {
8675: $metaentry{':packages'}.=','.$package;
1.483 albertel 8676: } else {
1.599 albertel 8677: $metaentry{':packages'}=$package;
1.483 albertel 8678: }
8679: my $value=$packagetab{$key};
8680: my $unikey;
8681: $unikey='parameter_0_'.$name;
1.599 albertel 8682: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8683: $$metathesekeys{$unikey}=1;
1.599 albertel 8684: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8685: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8686: }
1.599 albertel 8687: if (defined($metaentry{':'.$unikey.'.default'})) {
8688: $metaentry{':'.$unikey}=
8689: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8690: }
8691: }
8692:
1.261 albertel 8693: sub metadata_generate_part0 {
8694: my ($metadata,$metacache,$uri) = @_;
8695: my %allnames;
1.737 albertel 8696: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8697: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8698: my $part=$$metacache{':'.$metakey.'.part'};
8699: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8700: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8701: $allnames{$name}=$part;
8702: }
8703: }
8704: }
8705: foreach my $name (keys(%allnames)) {
8706: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8707: my $key=":parameter_0_$name";
1.261 albertel 8708: $$metacache{"$key.part"}='0';
8709: $$metacache{"$key.name"}=$name;
1.428 albertel 8710: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8711: $allnames{$name}.'_'.$name.
8712: '.type'};
1.428 albertel 8713: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8714: '.display'};
1.644 www 8715: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8716: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8717: $$metacache{"$key.display"}=$olddis;
8718: }
1.71 www 8719: }
8720:
1.764 albertel 8721: # ------------------------------------------------------ Devalidate title cache
8722:
8723: sub devalidate_title_cache {
8724: my ($url)=@_;
8725: if (!$env{'request.course.id'}) { return; }
8726: my $symb=&symbread($url);
8727: if (!$symb) { return; }
8728: my $key=$env{'request.course.id'}."\0".$symb;
8729: &devalidate_cache_new('title',$key);
8730: }
8731:
1.1014 droeschl 8732: # ------------------------------------------------- Get the title of a course
8733:
8734: sub current_course_title {
8735: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8736: }
1.301 www 8737: # ------------------------------------------------- Get the title of a resource
8738:
8739: sub gettitle {
8740: my $urlsymb=shift;
8741: my $symb=&symbread($urlsymb);
1.534 albertel 8742: if ($symb) {
1.620 albertel 8743: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8744: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8745: if (defined($cached)) {
8746: return $result;
8747: }
1.534 albertel 8748: my ($map,$resid,$url)=&decode_symb($symb);
8749: my $title='';
1.907 albertel 8750: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8751: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8752: } else {
8753: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8754: &GDBM_READER(),0640)) {
8755: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8756: $title=$bighash{'title_'.$mapid.'.'.$resid};
8757: untie(%bighash);
8758: }
1.534 albertel 8759: }
8760: $title=~s/\&colon\;/\:/gs;
8761: if ($title) {
1.599 albertel 8762: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8763: }
8764: $urlsymb=$url;
8765: }
8766: my $title=&metadata($urlsymb,'title');
8767: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8768: return $title;
1.301 www 8769: }
1.613 albertel 8770:
1.614 albertel 8771: sub get_slot {
8772: my ($which,$cnum,$cdom)=@_;
8773: if (!$cnum || !$cdom) {
1.790 albertel 8774: (undef,my $courseid)=&whichuser();
1.620 albertel 8775: $cdom=$env{'course.'.$courseid.'.domain'};
8776: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8777: }
1.703 albertel 8778: my $key=join("\0",'slots',$cdom,$cnum,$which);
8779: my %slotinfo;
8780: if (exists($remembered{$key})) {
8781: $slotinfo{$which} = $remembered{$key};
8782: } else {
8783: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8784: &Apache::lonhomework::showhash(%slotinfo);
8785: my ($tmp)=keys(%slotinfo);
8786: if ($tmp=~/^error:/) { return (); }
8787: $remembered{$key} = $slotinfo{$which};
8788: }
1.616 albertel 8789: if (ref($slotinfo{$which}) eq 'HASH') {
8790: return %{$slotinfo{$which}};
8791: }
8792: return $slotinfo{$which};
1.614 albertel 8793: }
1.31 www 8794: # ------------------------------------------------- Update symbolic store links
8795:
8796: sub symblist {
8797: my ($mapname,%newhash)=@_;
1.438 www 8798: $mapname=&deversion(&declutter($mapname));
1.31 www 8799: my %hash;
1.620 albertel 8800: if (($env{'request.course.fn'}) && (%newhash)) {
8801: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8802: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8803: foreach my $url (keys(%newhash)) {
1.711 albertel 8804: next if ($url eq 'last_known'
8805: && $env{'form.no_update_last_known'});
8806: $hash{declutter($url)}=&encode_symb($mapname,
8807: $newhash{$url}->[1],
8808: $newhash{$url}->[0]);
1.191 harris41 8809: }
1.31 www 8810: if (untie(%hash)) {
8811: return 'ok';
8812: }
8813: }
8814: }
8815: return 'error';
1.212 www 8816: }
8817:
8818: # --------------------------------------------------------------- Verify a symb
8819:
8820: sub symbverify {
1.510 www 8821: my ($symb,$thisurl)=@_;
8822: my $thisfn=$thisurl;
1.439 www 8823: $thisfn=&declutter($thisfn);
1.215 www 8824: # direct jump to resource in page or to a sequence - will construct own symbs
8825: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8826: # check URL part
1.409 www 8827: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8828:
1.431 www 8829: unless ($url eq $thisfn) { return 0; }
1.213 www 8830:
1.216 www 8831: $symb=&symbclean($symb);
1.510 www 8832: $thisurl=&deversion($thisurl);
1.439 www 8833: $thisfn=&deversion($thisfn);
1.213 www 8834:
8835: my %bighash;
8836: my $okay=0;
1.431 www 8837:
1.620 albertel 8838: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8839: &GDBM_READER(),0640)) {
1.1032 raeburn 8840: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8841: $thisurl =~ s/\?.+$//;
8842: }
1.510 www 8843: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8844: unless ($ids) {
1.510 www 8845: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8846: }
8847: if ($ids) {
8848: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8849: foreach my $id (split(/\,/,$ids)) {
8850: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 8851: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8852: $symb =~ s/\?.+$//;
8853: }
1.216 www 8854: if (
8855: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8856: eq $symb) {
1.620 albertel 8857: if (($env{'request.role.adv'}) ||
1.800 albertel 8858: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8859: $okay=1;
8860: }
8861: }
1.216 www 8862: }
8863: }
1.213 www 8864: untie(%bighash);
8865: }
8866: return $okay;
1.31 www 8867: }
8868:
1.210 www 8869: # --------------------------------------------------------------- Clean-up symb
8870:
8871: sub symbclean {
8872: my $symb=shift;
1.568 albertel 8873: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8874: # remove version from map
8875: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8876:
1.210 www 8877: # remove version from URL
8878: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8879:
1.507 www 8880: # remove wrapper
8881:
1.510 www 8882: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8883: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8884: return $symb;
1.409 www 8885: }
8886:
8887: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8888:
8889: sub encode_symb {
8890: my ($map,$resid,$url)=@_;
8891: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8892: }
1.409 www 8893:
8894: sub decode_symb {
1.568 albertel 8895: my $symb=shift;
8896: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8897: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 8898: return (&fixversion($map),$resid,&fixversion($url));
8899: }
8900:
8901: sub fixversion {
8902: my $fn=shift;
1.609 banghart 8903: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 8904: my %bighash;
8905: my $uri=&clutter($fn);
1.620 albertel 8906: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 8907: # is this cached?
1.599 albertel 8908: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 8909: if (defined($cached)) { return $result; }
8910: # unfortunately not cached, or expired
1.620 albertel 8911: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 8912: &GDBM_READER(),0640)) {
8913: if ($bighash{'version_'.$uri}) {
8914: my $version=$bighash{'version_'.$uri};
1.444 www 8915: unless (($version eq 'mostrecent') ||
8916: ($version==&getversion($uri))) {
1.440 www 8917: $uri=~s/\.(\w+)$/\.$version\.$1/;
8918: }
8919: }
8920: untie %bighash;
1.413 www 8921: }
1.599 albertel 8922: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 8923: }
8924:
8925: sub deversion {
8926: my $url=shift;
8927: $url=~s/\.\d+\.(\w+)$/\.$1/;
8928: return $url;
1.210 www 8929: }
8930:
1.31 www 8931: # ------------------------------------------------------ Return symb list entry
8932:
8933: sub symbread {
1.249 www 8934: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 8935: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 8936: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 8937: # no filename provided? try from environment
1.44 www 8938: unless ($thisfn) {
1.620 albertel 8939: if ($env{'request.symb'}) {
8940: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 8941: }
1.620 albertel 8942: $thisfn=$env{'request.filename'};
1.44 www 8943: }
1.569 albertel 8944: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 8945: # is that filename actually a symb? Verify, clean, and return
8946: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 8947: if (&symbverify($thisfn,$1)) {
1.620 albertel 8948: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 8949: }
1.242 www 8950: }
1.44 www 8951: $thisfn=declutter($thisfn);
1.31 www 8952: my %hash;
1.37 www 8953: my %bighash;
8954: my $syval='';
1.620 albertel 8955: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 8956: my $targetfn = $thisfn;
1.609 banghart 8957: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 8958: $targetfn = 'adm/wrapper/'.$thisfn;
8959: }
1.687 albertel 8960: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8961: $targetfn=$1;
8962: }
1.620 albertel 8963: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8964: &GDBM_READER(),0640)) {
1.481 raeburn 8965: $syval=$hash{$targetfn};
1.37 www 8966: untie(%hash);
8967: }
8968: # ---------------------------------------------------------- There was an entry
8969: if ($syval) {
1.601 albertel 8970: #unless ($syval=~/\_\d+$/) {
1.620 albertel 8971: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 8972: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8973: #return $env{$cache_str}='';
1.601 albertel 8974: #}
8975: #$syval.=$1;
8976: #}
1.37 www 8977: } else {
8978: # ------------------------------------------------------- Was not in symb table
1.620 albertel 8979: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8980: &GDBM_READER(),0640)) {
1.37 www 8981: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 8982: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 8983: unless ($ids) {
8984: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 8985: }
8986: unless ($ids) {
8987: # alias?
8988: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 8989: }
1.37 www 8990: if ($ids) {
8991: # ------------------------------------------------------------------- Has ID(s)
8992: my @possibilities=split(/\,/,$ids);
1.39 www 8993: if ($#possibilities==0) {
8994: # ----------------------------------------------- There is only one possibility
1.37 www 8995: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 8996: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8997: $resid,$thisfn);
1.249 www 8998: } elsif (!$donotrecurse) {
1.39 www 8999: # ------------------------------------------ There is more than one possibility
9000: my $realpossible=0;
1.800 albertel 9001: foreach my $id (@possibilities) {
9002: my $file=$bighash{'src_'.$id};
1.39 www 9003: if (&allowed('bre',$file)) {
1.800 albertel 9004: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9005: if ($bighash{'map_type_'.$mapid} ne 'page') {
9006: $realpossible++;
1.626 albertel 9007: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9008: $resid,$thisfn);
1.39 www 9009: }
9010: }
1.191 harris41 9011: }
1.39 www 9012: if ($realpossible!=1) { $syval=''; }
1.249 www 9013: } else {
9014: $syval='';
1.37 www 9015: }
9016: }
9017: untie(%bighash)
1.481 raeburn 9018: }
1.31 www 9019: }
1.62 www 9020: if ($syval) {
1.620 albertel 9021: return $env{$cache_str}=$syval;
1.62 www 9022: }
1.31 www 9023: }
1.949 raeburn 9024: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9025: return $env{$cache_str}='';
1.31 www 9026: }
9027:
9028: # ---------------------------------------------------------- Return random seed
9029:
1.32 www 9030: sub numval {
9031: my $txt=shift;
9032: $txt=~tr/A-J/0-9/;
9033: $txt=~tr/a-j/0-9/;
9034: $txt=~tr/K-T/0-9/;
9035: $txt=~tr/k-t/0-9/;
9036: $txt=~tr/U-Z/0-5/;
9037: $txt=~tr/u-z/0-5/;
9038: $txt=~s/\D//g;
1.564 albertel 9039: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9040: return int($txt);
1.368 albertel 9041: }
9042:
1.484 albertel 9043: sub numval2 {
9044: my $txt=shift;
9045: $txt=~tr/A-J/0-9/;
9046: $txt=~tr/a-j/0-9/;
9047: $txt=~tr/K-T/0-9/;
9048: $txt=~tr/k-t/0-9/;
9049: $txt=~tr/U-Z/0-5/;
9050: $txt=~tr/u-z/0-5/;
9051: $txt=~s/\D//g;
9052: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9053: my $total;
9054: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9055: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9056: return int($total);
9057: }
9058:
1.575 albertel 9059: sub numval3 {
9060: use integer;
9061: my $txt=shift;
9062: $txt=~tr/A-J/0-9/;
9063: $txt=~tr/a-j/0-9/;
9064: $txt=~tr/K-T/0-9/;
9065: $txt=~tr/k-t/0-9/;
9066: $txt=~tr/U-Z/0-5/;
9067: $txt=~tr/u-z/0-5/;
9068: $txt=~s/\D//g;
9069: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9070: my $total;
9071: foreach my $val (@txts) { $total+=$val; }
9072: if ($_64bit) { $total=(($total<<32)>>32); }
9073: return $total;
9074: }
9075:
1.675 albertel 9076: sub digest {
9077: my ($data)=@_;
9078: my $digest=&Digest::MD5::md5($data);
9079: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9080: my ($e,$f);
9081: {
9082: use integer;
9083: $e=($a+$b);
9084: $f=($c+$d);
9085: if ($_64bit) {
9086: $e=(($e<<32)>>32);
9087: $f=(($f<<32)>>32);
9088: }
9089: }
9090: if (wantarray) {
9091: return ($e,$f);
9092: } else {
9093: my $g;
9094: {
9095: use integer;
9096: $g=($e+$f);
9097: if ($_64bit) {
9098: $g=(($g<<32)>>32);
9099: }
9100: }
9101: return $g;
9102: }
9103: }
9104:
1.368 albertel 9105: sub latest_rnd_algorithm_id {
1.675 albertel 9106: return '64bit5';
1.366 albertel 9107: }
1.32 www 9108:
1.503 albertel 9109: sub get_rand_alg {
9110: my ($courseid)=@_;
1.790 albertel 9111: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9112: if ($courseid) {
1.620 albertel 9113: return $env{"course.$courseid.rndseed"};
1.503 albertel 9114: }
9115: return &latest_rnd_algorithm_id();
9116: }
9117:
1.562 albertel 9118: sub validCODE {
9119: my ($CODE)=@_;
9120: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9121: return 0;
9122: }
9123:
1.491 albertel 9124: sub getCODE {
1.620 albertel 9125: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9126: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9127: defined($Apache::lonhomework::parsing_a_task) ) &&
9128: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9129: return $Apache::lonhomework::history{'resource.CODE'};
9130: }
9131: return undef;
9132: }
9133:
1.31 www 9134: sub rndseed {
1.155 albertel 9135: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9136: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9137: if (!defined($symb)) {
1.366 albertel 9138: unless ($symb=$wsymb) { return time; }
9139: }
9140: if (!$courseid) { $courseid=$wcourseid; }
9141: if (!$domain) { $domain=$wdomain; }
9142: if (!$username) { $username=$wusername }
1.503 albertel 9143: my $which=&get_rand_alg();
1.803 albertel 9144:
1.491 albertel 9145: if (defined(&getCODE())) {
1.675 albertel 9146: if ($which eq '64bit5') {
9147: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9148: } elsif ($which eq '64bit4') {
1.575 albertel 9149: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9150: } else {
9151: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9152: }
1.675 albertel 9153: } elsif ($which eq '64bit5') {
9154: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9155: } elsif ($which eq '64bit4') {
9156: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9157: } elsif ($which eq '64bit3') {
9158: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9159: } elsif ($which eq '64bit2') {
9160: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9161: } elsif ($which eq '64bit') {
9162: return &rndseed_64bit($symb,$courseid,$domain,$username);
9163: }
9164: return &rndseed_32bit($symb,$courseid,$domain,$username);
9165: }
9166:
9167: sub rndseed_32bit {
9168: my ($symb,$courseid,$domain,$username)=@_;
9169: {
9170: use integer;
9171: my $symbchck=unpack("%32C*",$symb) << 27;
9172: my $symbseed=numval($symb) << 22;
9173: my $namechck=unpack("%32C*",$username) << 17;
9174: my $nameseed=numval($username) << 12;
9175: my $domainseed=unpack("%32C*",$domain) << 7;
9176: my $courseseed=unpack("%32C*",$courseid);
9177: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9178: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9179: #&logthis("rndseed :$num:$symb");
1.564 albertel 9180: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9181: return $num;
9182: }
9183: }
9184:
9185: sub rndseed_64bit {
9186: my ($symb,$courseid,$domain,$username)=@_;
9187: {
9188: use integer;
9189: my $symbchck=unpack("%32S*",$symb) << 21;
9190: my $symbseed=numval($symb) << 10;
9191: my $namechck=unpack("%32S*",$username);
9192:
9193: my $nameseed=numval($username) << 21;
9194: my $domainseed=unpack("%32S*",$domain) << 10;
9195: my $courseseed=unpack("%32S*",$courseid);
9196:
9197: my $num1=$symbchck+$symbseed+$namechck;
9198: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9199: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9200: #&logthis("rndseed :$num:$symb");
1.564 albertel 9201: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9202: return "$num1,$num2";
1.155 albertel 9203: }
1.366 albertel 9204: }
9205:
1.443 albertel 9206: sub rndseed_64bit2 {
9207: my ($symb,$courseid,$domain,$username)=@_;
9208: {
9209: use integer;
9210: # strings need to be an even # of cahracters long, it it is odd the
9211: # last characters gets thrown away
9212: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9213: my $symbseed=numval($symb) << 10;
9214: my $namechck=unpack("%32S*",$username.' ');
9215:
9216: my $nameseed=numval($username) << 21;
1.501 albertel 9217: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9218: my $courseseed=unpack("%32S*",$courseid.' ');
9219:
9220: my $num1=$symbchck+$symbseed+$namechck;
9221: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9222: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9223: #&logthis("rndseed :$num:$symb");
1.803 albertel 9224: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9225: return "$num1,$num2";
9226: }
9227: }
9228:
9229: sub rndseed_64bit3 {
9230: my ($symb,$courseid,$domain,$username)=@_;
9231: {
9232: use integer;
9233: # strings need to be an even # of cahracters long, it it is odd the
9234: # last characters gets thrown away
9235: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9236: my $symbseed=numval2($symb) << 10;
9237: my $namechck=unpack("%32S*",$username.' ');
9238:
9239: my $nameseed=numval2($username) << 21;
1.443 albertel 9240: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9241: my $courseseed=unpack("%32S*",$courseid.' ');
9242:
9243: my $num1=$symbchck+$symbseed+$namechck;
9244: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9245: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9246: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9247: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9248:
1.503 albertel 9249: return "$num1:$num2";
1.443 albertel 9250: }
9251: }
9252:
1.575 albertel 9253: sub rndseed_64bit4 {
9254: my ($symb,$courseid,$domain,$username)=@_;
9255: {
9256: use integer;
9257: # strings need to be an even # of cahracters long, it it is odd the
9258: # last characters gets thrown away
9259: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9260: my $symbseed=numval3($symb) << 10;
9261: my $namechck=unpack("%32S*",$username.' ');
9262:
9263: my $nameseed=numval3($username) << 21;
9264: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9265: my $courseseed=unpack("%32S*",$courseid.' ');
9266:
9267: my $num1=$symbchck+$symbseed+$namechck;
9268: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9269: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9270: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9271: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9272:
9273: return "$num1:$num2";
9274: }
9275: }
9276:
1.675 albertel 9277: sub rndseed_64bit5 {
9278: my ($symb,$courseid,$domain,$username)=@_;
9279: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9280: return "$num1:$num2";
9281: }
9282:
1.366 albertel 9283: sub rndseed_CODE_64bit {
9284: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9285: {
1.366 albertel 9286: use integer;
1.443 albertel 9287: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9288: my $symbseed=numval2($symb);
1.491 albertel 9289: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9290: my $CODEseed=numval(&getCODE());
1.443 albertel 9291: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9292: my $num1=$symbseed+$CODEchck;
9293: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9294: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9295: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9296: if ($_64bit) { $num1=(($num1<<32)>>32); }
9297: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9298: return "$num1:$num2";
1.366 albertel 9299: }
9300: }
9301:
1.575 albertel 9302: sub rndseed_CODE_64bit4 {
9303: my ($symb,$courseid,$domain,$username)=@_;
9304: {
9305: use integer;
9306: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9307: my $symbseed=numval3($symb);
9308: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9309: my $CODEseed=numval3(&getCODE());
9310: my $courseseed=unpack("%32S*",$courseid.' ');
9311: my $num1=$symbseed+$CODEchck;
9312: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9313: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9314: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9315: if ($_64bit) { $num1=(($num1<<32)>>32); }
9316: if ($_64bit) { $num2=(($num2<<32)>>32); }
9317: return "$num1:$num2";
9318: }
9319: }
9320:
1.675 albertel 9321: sub rndseed_CODE_64bit5 {
9322: my ($symb,$courseid,$domain,$username)=@_;
9323: my $code = &getCODE();
9324: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9325: return "$num1:$num2";
9326: }
9327:
1.366 albertel 9328: sub setup_random_from_rndseed {
9329: my ($rndseed)=@_;
1.503 albertel 9330: if ($rndseed =~/([,:])/) {
9331: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9332: &Math::Random::random_set_seed(abs($num1),abs($num2));
9333: } else {
9334: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9335: }
1.36 albertel 9336: }
9337:
1.474 albertel 9338: sub latest_receipt_algorithm_id {
1.835 albertel 9339: return 'receipt3';
1.474 albertel 9340: }
9341:
1.480 www 9342: sub recunique {
9343: my $fucourseid=shift;
9344: my $unique;
1.835 albertel 9345: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9346: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9347: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9348: } else {
9349: $unique=$perlvar{'lonReceipt'};
9350: }
9351: return unpack("%32C*",$unique);
9352: }
9353:
9354: sub recprefix {
9355: my $fucourseid=shift;
9356: my $prefix;
1.835 albertel 9357: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9358: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9359: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9360: } else {
9361: $prefix=$perlvar{'lonHostID'};
9362: }
9363: return unpack("%32C*",$prefix);
9364: }
9365:
1.76 www 9366: sub ireceipt {
1.474 albertel 9367: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9368:
9369: my $return =&recprefix($fucourseid).'-';
9370:
9371: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9372: $env{'request.state'} eq 'construct') {
9373: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9374: return $return;
9375: }
9376:
1.76 www 9377: my $cuname=unpack("%32C*",$funame);
9378: my $cudom=unpack("%32C*",$fudom);
9379: my $cucourseid=unpack("%32C*",$fucourseid);
9380: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9381: my $cunique=&recunique($fucourseid);
1.474 albertel 9382: my $cpart=unpack("%32S*",$part);
1.835 albertel 9383: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9384:
1.790 albertel 9385: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9386:
9387: $return.= ($cunique%$cuname+
9388: $cunique%$cudom+
9389: $cusymb%$cuname+
9390: $cusymb%$cudom+
9391: $cucourseid%$cuname+
9392: $cucourseid%$cudom+
9393: $cpart%$cuname+
9394: $cpart%$cudom);
9395: } else {
9396: $return.= ($cunique%$cuname+
9397: $cunique%$cudom+
9398: $cusymb%$cuname+
9399: $cusymb%$cudom+
9400: $cucourseid%$cuname+
9401: $cucourseid%$cudom);
9402: }
9403: return $return;
1.76 www 9404: }
9405:
9406: sub receipt {
1.474 albertel 9407: my ($part)=@_;
1.790 albertel 9408: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9409: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9410: }
1.260 ng 9411:
1.790 albertel 9412: sub whichuser {
9413: my ($passedsymb)=@_;
9414: my ($symb,$courseid,$domain,$name,$publicuser);
9415: if (defined($env{'form.grade_symb'})) {
9416: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9417: my $allowed=&allowed('vgr',$tmp_courseid);
9418: if (!$allowed &&
9419: exists($env{'request.course.sec'}) &&
9420: $env{'request.course.sec'} !~ /^\s*$/) {
9421: $allowed=&allowed('vgr',$tmp_courseid.
9422: '/'.$env{'request.course.sec'});
9423: }
9424: if ($allowed) {
9425: ($symb)=&get_env_multiple('form.grade_symb');
9426: $courseid=$tmp_courseid;
9427: ($domain)=&get_env_multiple('form.grade_domain');
9428: ($name)=&get_env_multiple('form.grade_username');
9429: return ($symb,$courseid,$domain,$name,$publicuser);
9430: }
9431: }
9432: if (!$passedsymb) {
9433: $symb=&symbread();
9434: } else {
9435: $symb=$passedsymb;
9436: }
9437: $courseid=$env{'request.course.id'};
9438: $domain=$env{'user.domain'};
9439: $name=$env{'user.name'};
9440: if ($name eq 'public' && $domain eq 'public') {
9441: if (!defined($env{'form.username'})) {
9442: $env{'form.username'}.=time.rand(10000000);
9443: }
9444: $name.=$env{'form.username'};
9445: }
9446: return ($symb,$courseid,$domain,$name,$publicuser);
9447:
9448: }
9449:
1.36 albertel 9450: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9451: # returns either the contents of the file or
9452: # -1 if the file doesn't exist
1.481 raeburn 9453: #
9454: # if the target is a file that was uploaded via DOCS,
9455: # a check will be made to see if a current copy exists on the local server,
9456: # if it does this will be served, otherwise a copy will be retrieved from
9457: # the home server for the course and stored in /home/httpd/html/userfiles on
9458: # the local server.
1.472 albertel 9459:
1.36 albertel 9460: sub getfile {
1.538 albertel 9461: my ($file) = @_;
1.609 banghart 9462: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9463: &repcopy($file);
9464: return &readfile($file);
9465: }
9466:
9467: sub repcopy_userfile {
9468: my ($file)=@_;
1.609 banghart 9469: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9470: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9471: my ($cdom,$cnum,$filename) =
1.811 albertel 9472: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9473: my $uri="/uploaded/$cdom/$cnum/$filename";
9474: if (-e "$file") {
1.828 www 9475: # we already have a local copy, check it out
1.538 albertel 9476: my @fileinfo = stat($file);
1.828 www 9477: my $rtncode;
9478: my $info;
1.538 albertel 9479: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9480: if ($lwpresp ne 'ok') {
1.828 www 9481: # there is no such file anymore, even though we had a local copy
1.482 albertel 9482: if ($rtncode eq '404') {
1.538 albertel 9483: unlink($file);
1.482 albertel 9484: }
9485: return -1;
9486: }
9487: if ($info < $fileinfo[9]) {
1.828 www 9488: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9489: return 'ok';
1.828 www 9490: } else {
9491: # the file is outdated, get rid of it
9492: unlink($file);
1.482 albertel 9493: }
1.828 www 9494: }
9495: # one way or the other, at this point, we don't have the file
9496: # construct the correct path for the file
9497: my @parts = ($cdom,$cnum);
9498: if ($filename =~ m|^(.+)/[^/]+$|) {
9499: push @parts, split(/\//,$1);
9500: }
9501: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9502: foreach my $part (@parts) {
9503: $path .= '/'.$part;
9504: if (!-e $path) {
9505: mkdir($path,0770);
1.482 albertel 9506: }
9507: }
1.828 www 9508: # now the path exists for sure
9509: # get a user agent
9510: my $ua=new LWP::UserAgent;
9511: my $transferfile=$file.'.in.transfer';
9512: # FIXME: this should flock
9513: if (-e $transferfile) { return 'ok'; }
9514: my $request;
9515: $uri=~s/^\///;
1.980 raeburn 9516: my $homeserver = &homeserver($cnum,$cdom);
9517: my $protocol = $protocol{$homeserver};
9518: $protocol = 'http' if ($protocol ne 'https');
9519: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9520: my $response=$ua->request($request,$transferfile);
9521: # did it work?
9522: if ($response->is_error()) {
9523: unlink($transferfile);
9524: &logthis("Userfile repcopy failed for $uri");
9525: return -1;
9526: }
9527: # worked, rename the transfer file
9528: rename($transferfile,$file);
1.607 raeburn 9529: return 'ok';
1.481 raeburn 9530: }
9531:
1.517 albertel 9532: sub tokenwrapper {
9533: my $uri=shift;
1.980 raeburn 9534: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9535: $uri=~s|^/||;
1.620 albertel 9536: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9537: my $token=$1;
1.552 albertel 9538: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9539: if ($udom && $uname && $file) {
9540: $file=~s|(\?\.*)*$||;
1.949 raeburn 9541: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9542: my $homeserver = &homeserver($uname,$udom);
9543: my $protocol = $protocol{$homeserver};
9544: $protocol = 'http' if ($protocol ne 'https');
9545: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9546: (($uri=~/\?/)?'&':'?').'token='.$token.
9547: '&tokenissued='.$perlvar{'lonHostID'};
9548: } else {
9549: return '/adm/notfound.html';
9550: }
9551: }
9552:
1.828 www 9553: # call with reqtype HEAD: get last modification time
9554: # call with reqtype GET: get the file contents
9555: # Do not call this with reqtype GET for large files! It loads everything into memory
9556: #
1.481 raeburn 9557: sub getuploaded {
9558: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9559: $uri=~s/^\///;
1.980 raeburn 9560: my $homeserver = &homeserver($cnum,$cdom);
9561: my $protocol = $protocol{$homeserver};
9562: $protocol = 'http' if ($protocol ne 'https');
9563: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9564: my $ua=new LWP::UserAgent;
9565: my $request=new HTTP::Request($reqtype,$uri);
9566: my $response=$ua->request($request);
9567: $$rtncode = $response->code;
1.482 albertel 9568: if (! $response->is_success()) {
9569: return 'failed';
9570: }
9571: if ($reqtype eq 'HEAD') {
1.486 www 9572: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9573: } elsif ($reqtype eq 'GET') {
9574: $$info = $response->content;
1.472 albertel 9575: }
1.482 albertel 9576: return 'ok';
1.36 albertel 9577: }
9578:
1.481 raeburn 9579: sub readfile {
9580: my $file = shift;
9581: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9582: my $fh;
9583: open($fh,"<$file");
9584: my $a='';
1.800 albertel 9585: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9586: return $a;
9587: }
9588:
1.36 albertel 9589: sub filelocation {
1.590 banghart 9590: my ($dir,$file) = @_;
9591: my $location;
9592: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9593:
9594: if ($file =~ m-^/adm/-) {
9595: $file=~s-^/adm/wrapper/-/-;
9596: $file=~s-^/adm/coursedocs/showdoc/-/-;
9597: }
1.882 albertel 9598:
1.590 banghart 9599: if ($file=~m:^/~:) { # is a contruction space reference
9600: $location = $file;
9601: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9602: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9603: # is a correct contruction space reference
9604: $location = $file;
1.956 raeburn 9605: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9606: $location = $file;
1.609 banghart 9607: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9608: my ($udom,$uname,$filename)=
1.811 albertel 9609: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9610: my $home=&homeserver($uname,$udom);
9611: my $is_me=0;
9612: my @ids=¤t_machine_ids();
9613: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9614: if ($is_me) {
1.955 raeburn 9615: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9616: } else {
9617: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9618: $udom.'/'.$uname.'/'.$filename;
9619: }
1.882 albertel 9620: } elsif ($file =~ m-^/adm/-) {
9621: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9622: } else {
9623: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9624: $file=~s:^/res/:/:;
9625: if ( !( $file =~ m:^/:) ) {
9626: $location = $dir. '/'.$file;
9627: } else {
9628: $location = '/home/httpd/html/res'.$file;
9629: }
1.59 albertel 9630: }
1.590 banghart 9631: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9632: while ($location=~m{/\.\./}) {
9633: if ($location =~ m{/[^/]+/\.\./}) {
9634: $location=~ s{/[^/]+/\.\./}{/}g;
9635: } else {
9636: $location=~ s{/\.\./}{/}g;
9637: }
9638: } #remove dir/..
1.590 banghart 9639: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9640: return $location;
1.46 www 9641: }
1.36 albertel 9642:
1.46 www 9643: sub hreflocation {
9644: my ($dir,$file)=@_;
1.980 raeburn 9645: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9646: $file=filelocation($dir,$file);
1.700 albertel 9647: } elsif ($file=~m-^/adm/-) {
9648: $file=~s-^/adm/wrapper/-/-;
9649: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9650: }
9651: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9652: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9653: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9654: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9655: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9656: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9657: -/uploaded/$1/$2/-x;
1.46 www 9658: }
1.913 albertel 9659: if ($file=~ m{^/userfiles/}) {
9660: $file =~ s{^/userfiles/}{/uploaded/};
9661: }
1.462 albertel 9662: return $file;
1.465 albertel 9663: }
9664:
9665: sub current_machine_domains {
1.853 albertel 9666: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9667: }
9668:
9669: sub machine_domains {
9670: my ($hostname) = @_;
1.465 albertel 9671: my @domains;
1.838 albertel 9672: my %hostname = &all_hostnames();
1.465 albertel 9673: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9674: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9675: if ($hostname eq $name) {
1.844 albertel 9676: push(@domains,&host_domain($id));
1.465 albertel 9677: }
9678: }
9679: return @domains;
9680: }
9681:
9682: sub current_machine_ids {
1.853 albertel 9683: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9684: }
9685:
9686: sub machine_ids {
9687: my ($hostname) = @_;
9688: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9689: my @ids;
1.888 albertel 9690: my %name_to_host = &all_names();
1.889 albertel 9691: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9692: return @{ $name_to_host{$hostname} };
9693: }
9694: return;
1.31 www 9695: }
9696:
1.824 raeburn 9697: sub additional_machine_domains {
9698: my @domains;
9699: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9700: while( my $line = <$fh>) {
9701: $line =~ s/\s//g;
9702: push(@domains,$line);
9703: }
9704: return @domains;
9705: }
9706:
9707: sub default_login_domain {
9708: my $domain = $perlvar{'lonDefDomain'};
9709: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9710: foreach my $posdom (¤t_machine_domains(),
9711: &additional_machine_domains()) {
9712: if (lc($posdom) eq lc($testdomain)) {
9713: $domain=$posdom;
9714: last;
9715: }
9716: }
9717: return $domain;
9718: }
9719:
1.31 www 9720: # ------------------------------------------------------------- Declutters URLs
9721:
9722: sub declutter {
9723: my $thisfn=shift;
1.569 albertel 9724: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9725: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9726: $thisfn=~s/^\///;
1.697 albertel 9727: $thisfn=~s|^adm/wrapper/||;
9728: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9729: $thisfn=~s/^res\///;
1.1032 raeburn 9730: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9731: $thisfn=~s/\?.+$//;
9732: }
1.268 www 9733: return $thisfn;
9734: }
9735:
9736: # ------------------------------------------------------------- Clutter up URLs
9737:
9738: sub clutter {
9739: my $thisfn='/'.&declutter(shift);
1.887 albertel 9740: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9741: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9742: $thisfn='/res'.$thisfn;
9743: }
1.1031 raeburn 9744: if ($thisfn !~m|^/adm|) {
9745: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9746: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9747: } else {
9748: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9749: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9750: if ($embstyle eq 'ssi'
9751: || ($embstyle eq 'hdn')
9752: || ($embstyle eq 'rat')
9753: || ($embstyle eq 'prv')
9754: || ($embstyle eq 'ign')) {
9755: #do nothing with these
9756: } elsif (($embstyle eq 'img')
1.695 albertel 9757: || ($embstyle eq 'emb')
9758: || ($embstyle eq 'wrp')) {
9759: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9760: } elsif ($embstyle eq 'unk'
9761: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9762: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9763: } else {
1.718 www 9764: # &logthis("Got a blank emb style");
1.695 albertel 9765: }
1.694 albertel 9766: }
9767: }
1.31 www 9768: return $thisfn;
1.12 www 9769: }
9770:
1.787 albertel 9771: sub clutter_with_no_wrapper {
9772: my $uri = &clutter(shift);
9773: if ($uri =~ m-^/adm/-) {
9774: $uri =~ s-^/adm/wrapper/-/-;
9775: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9776: }
9777: return $uri;
9778: }
9779:
1.557 albertel 9780: sub freeze_escape {
9781: my ($value)=@_;
9782: if (ref($value)) {
9783: $value=&nfreeze($value);
9784: return '__FROZEN__'.&escape($value);
9785: }
9786: return &escape($value);
9787: }
9788:
1.11 www 9789:
1.557 albertel 9790: sub thaw_unescape {
9791: my ($value)=@_;
9792: if ($value =~ /^__FROZEN__/) {
9793: substr($value,0,10,undef);
9794: $value=&unescape($value);
9795: return &thaw($value);
9796: }
9797: return &unescape($value);
9798: }
9799:
1.436 albertel 9800: sub correct_line_ends {
9801: my ($result)=@_;
9802: $$result =~s/\r\n/\n/mg;
9803: $$result =~s/\r/\n/mg;
1.415 albertel 9804: }
1.1 albertel 9805: # ================================================================ Main Program
9806:
1.184 www 9807: sub goodbye {
1.204 albertel 9808: &logthis("Starting Shut down");
1.443 albertel 9809: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9810: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9811: #converted
1.599 albertel 9812: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9813: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9814: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9815: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9816: #1.1 only
1.870 albertel 9817: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9818: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9819: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9820: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9821: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9822: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9823: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9824: &flushcourselogs();
9825: &logthis("Shutting down");
9826: }
9827:
1.852 albertel 9828: sub get_dns {
1.869 albertel 9829: my ($url,$func,$ignore_cache) = @_;
9830: if (!$ignore_cache) {
9831: my ($content,$cached)=
9832: &Apache::lonnet::is_cached_new('dns',$url);
9833: if ($cached) {
9834: &$func($content);
9835: return;
9836: }
9837: }
9838:
9839: my %alldns;
1.852 albertel 9840: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9841: foreach my $dns (<$config>) {
9842: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9843: my $line = $1;
9844: my ($host,$protocol) = split(/:/,$line);
9845: if ($protocol ne 'https') {
9846: $protocol = 'http';
9847: }
9848: $alldns{$host} = $protocol;
1.869 albertel 9849: }
9850: while (%alldns) {
9851: my ($dns) = keys(%alldns);
1.852 albertel 9852: my $ua=new LWP::UserAgent;
1.979 raeburn 9853: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9854: my $response=$ua->request($request);
1.979 raeburn 9855: delete($alldns{$dns});
1.852 albertel 9856: next if ($response->is_error());
9857: my @content = split("\n",$response->content);
1.869 albertel 9858: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9859: &$func(\@content);
1.869 albertel 9860: return;
1.852 albertel 9861: }
9862: close($config);
1.871 albertel 9863: my $which = (split('/',$url))[3];
9864: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9865: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9866: my @content = <$config>;
9867: &$func(\@content);
9868: return;
1.852 albertel 9869: }
1.327 albertel 9870: # ------------------------------------------------------------ Read domain file
9871: {
1.852 albertel 9872: my $loaded;
1.846 albertel 9873: my %domain;
9874:
1.852 albertel 9875: sub parse_domain_tab {
9876: my ($lines) = @_;
9877: foreach my $line (@$lines) {
9878: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9879:
1.846 albertel 9880: chomp($line);
1.852 albertel 9881: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9882: my %this_domain;
9883: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9884: 'lang_def', 'city', 'longi', 'lati',
9885: 'primary') {
9886: $this_domain{$field} = shift(@elements);
9887: }
9888: $domain{$name} = \%this_domain;
1.852 albertel 9889: }
9890: }
1.864 albertel 9891:
9892: sub reset_domain_info {
9893: undef($loaded);
9894: undef(%domain);
9895: }
9896:
1.852 albertel 9897: sub load_domain_tab {
1.869 albertel 9898: my ($ignore_cache) = @_;
9899: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 9900: my $fh;
9901: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9902: my @lines = <$fh>;
9903: &parse_domain_tab(\@lines);
1.448 albertel 9904: }
1.852 albertel 9905: close($fh);
9906: $loaded = 1;
1.327 albertel 9907: }
1.846 albertel 9908:
9909: sub domain {
1.852 albertel 9910: &load_domain_tab() if (!$loaded);
9911:
1.846 albertel 9912: my ($name,$what) = @_;
9913: return if ( !exists($domain{$name}) );
9914:
9915: if (!$what) {
9916: return $domain{$name}{'description'};
9917: }
9918: return $domain{$name}{$what};
9919: }
1.974 raeburn 9920:
9921: sub domain_info {
9922: &load_domain_tab() if (!$loaded);
9923: return %domain;
9924: }
9925:
1.327 albertel 9926: }
9927:
9928:
1.1 albertel 9929: # ------------------------------------------------------------- Read hosts file
9930: {
1.838 albertel 9931: my %hostname;
1.844 albertel 9932: my %hostdom;
1.845 albertel 9933: my %libserv;
1.852 albertel 9934: my $loaded;
1.888 albertel 9935: my %name_to_host;
1.1074 raeburn 9936: my %internetdom;
1.852 albertel 9937:
9938: sub parse_hosts_tab {
9939: my ($file) = @_;
9940: foreach my $configline (@$file) {
9941: next if ($configline =~ /^(\#|\s*$ )/x);
9942: next if ($configline =~ /^\^/);
9943: chomp($configline);
1.1074 raeburn 9944: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 9945: $name=~s/\s//g;
9946: if ($id && $domain && $role && $name) {
9947: $hostname{$id}=$name;
1.888 albertel 9948: push(@{$name_to_host{$name}}, $id);
1.852 albertel 9949: $hostdom{$id}=$domain;
9950: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 9951: if (defined($protocol)) {
9952: if ($protocol eq 'https') {
9953: $protocol{$id} = $protocol;
9954: } else {
9955: $protocol{$id} = 'http';
9956: }
1.968 raeburn 9957: } else {
1.969 raeburn 9958: $protocol{$id} = 'http';
1.968 raeburn 9959: }
1.1074 raeburn 9960: if (defined($intdom)) {
9961: $internetdom{$id} = $intdom;
9962: }
1.852 albertel 9963: }
9964: }
9965: }
1.864 albertel 9966:
9967: sub reset_hosts_info {
1.897 albertel 9968: &purge_remembered();
1.864 albertel 9969: &reset_domain_info();
9970: &reset_hosts_ip_info();
1.892 albertel 9971: undef(%name_to_host);
1.864 albertel 9972: undef(%hostname);
9973: undef(%hostdom);
9974: undef(%libserv);
9975: undef($loaded);
9976: }
1.1 albertel 9977:
1.852 albertel 9978: sub load_hosts_tab {
1.869 albertel 9979: my ($ignore_cache) = @_;
9980: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 9981: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9982: my @config = <$config>;
9983: &parse_hosts_tab(\@config);
9984: close($config);
9985: $loaded=1;
1.1 albertel 9986: }
1.852 albertel 9987:
1.838 albertel 9988: sub hostname {
1.852 albertel 9989: &load_hosts_tab() if (!$loaded);
9990:
1.838 albertel 9991: my ($lonid) = @_;
9992: return $hostname{$lonid};
9993: }
1.845 albertel 9994:
1.838 albertel 9995: sub all_hostnames {
1.852 albertel 9996: &load_hosts_tab() if (!$loaded);
9997:
1.838 albertel 9998: return %hostname;
9999: }
1.845 albertel 10000:
1.888 albertel 10001: sub all_names {
10002: &load_hosts_tab() if (!$loaded);
10003:
10004: return %name_to_host;
10005: }
10006:
1.974 raeburn 10007: sub all_host_domain {
10008: &load_hosts_tab() if (!$loaded);
10009: return %hostdom;
10010: }
10011:
1.845 albertel 10012: sub is_library {
1.852 albertel 10013: &load_hosts_tab() if (!$loaded);
10014:
1.845 albertel 10015: return exists($libserv{$_[0]});
10016: }
10017:
10018: sub all_library {
1.852 albertel 10019: &load_hosts_tab() if (!$loaded);
10020:
1.845 albertel 10021: return %libserv;
10022: }
10023:
1.1062 droeschl 10024: sub unique_library {
10025: #2x reverse removes all hostnames that appear more than once
10026: my %unique = reverse &all_library();
10027: return reverse %unique;
10028: }
10029:
1.841 albertel 10030: sub get_servers {
1.852 albertel 10031: &load_hosts_tab() if (!$loaded);
10032:
1.841 albertel 10033: my ($domain,$type) = @_;
10034: my %possible_hosts = ($type eq 'library') ? %libserv
10035: : %hostname;
10036: my %result;
1.842 albertel 10037: if (ref($domain) eq 'ARRAY') {
10038: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10039: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10040: $result{$host} = $hostname;
10041: }
10042: }
10043: } else {
10044: while ( my ($host,$hostname) = each(%possible_hosts)) {
10045: if ($hostdom{$host} eq $domain) {
10046: $result{$host} = $hostname;
10047: }
1.841 albertel 10048: }
10049: }
10050: return %result;
10051: }
1.845 albertel 10052:
1.1062 droeschl 10053: sub get_unique_servers {
10054: my %unique = reverse &get_servers(@_);
10055: return reverse %unique;
10056: }
10057:
1.844 albertel 10058: sub host_domain {
1.852 albertel 10059: &load_hosts_tab() if (!$loaded);
10060:
1.844 albertel 10061: my ($lonid) = @_;
10062: return $hostdom{$lonid};
10063: }
10064:
1.841 albertel 10065: sub all_domains {
1.852 albertel 10066: &load_hosts_tab() if (!$loaded);
10067:
1.841 albertel 10068: my %seen;
10069: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10070: return @uniq;
10071: }
1.1074 raeburn 10072:
10073: sub internet_dom {
10074: &load_hosts_tab() if (!$loaded);
10075:
10076: my ($lonid) = @_;
10077: return $internetdom{$lonid};
10078: }
1.1 albertel 10079: }
10080:
1.847 albertel 10081: {
10082: my %iphost;
1.856 albertel 10083: my %name_to_ip;
10084: my %lonid_to_ip;
1.869 albertel 10085:
1.847 albertel 10086: sub get_hosts_from_ip {
10087: my ($ip) = @_;
10088: my %iphosts = &get_iphost();
10089: if (ref($iphosts{$ip})) {
10090: return @{$iphosts{$ip}};
10091: }
10092: return;
1.839 albertel 10093: }
1.864 albertel 10094:
10095: sub reset_hosts_ip_info {
10096: undef(%iphost);
10097: undef(%name_to_ip);
10098: undef(%lonid_to_ip);
10099: }
1.856 albertel 10100:
10101: sub get_host_ip {
10102: my ($lonid) = @_;
10103: if (exists($lonid_to_ip{$lonid})) {
10104: return $lonid_to_ip{$lonid};
10105: }
10106: my $name=&hostname($lonid);
10107: my $ip = gethostbyname($name);
10108: return if (!$ip || length($ip) ne 4);
10109: $ip=inet_ntoa($ip);
10110: $name_to_ip{$name} = $ip;
10111: $lonid_to_ip{$lonid} = $ip;
10112: return $ip;
10113: }
1.847 albertel 10114:
10115: sub get_iphost {
1.869 albertel 10116: my ($ignore_cache) = @_;
1.894 albertel 10117:
1.869 albertel 10118: if (!$ignore_cache) {
10119: if (%iphost) {
10120: return %iphost;
10121: }
10122: my ($ip_info,$cached)=
10123: &Apache::lonnet::is_cached_new('iphost','iphost');
10124: if ($cached) {
10125: %iphost = %{$ip_info->[0]};
10126: %name_to_ip = %{$ip_info->[1]};
10127: %lonid_to_ip = %{$ip_info->[2]};
10128: return %iphost;
10129: }
10130: }
1.894 albertel 10131:
10132: # get yesterday's info for fallback
10133: my %old_name_to_ip;
10134: my ($ip_info,$cached)=
10135: &Apache::lonnet::is_cached_new('iphost','iphost');
10136: if ($cached) {
10137: %old_name_to_ip = %{$ip_info->[1]};
10138: }
10139:
1.888 albertel 10140: my %name_to_host = &all_names();
10141: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10142: my $ip;
10143: if (!exists($name_to_ip{$name})) {
10144: $ip = gethostbyname($name);
10145: if (!$ip || length($ip) ne 4) {
1.894 albertel 10146: if (defined($old_name_to_ip{$name})) {
10147: $ip = $old_name_to_ip{$name};
10148: &logthis("Can't find $name defaulting to old $ip");
10149: } else {
10150: &logthis("Name $name no IP found");
10151: next;
10152: }
10153: } else {
10154: $ip=inet_ntoa($ip);
1.847 albertel 10155: }
10156: $name_to_ip{$name} = $ip;
10157: } else {
10158: $ip = $name_to_ip{$name};
1.653 albertel 10159: }
1.888 albertel 10160: foreach my $id (@{ $name_to_host{$name} }) {
10161: $lonid_to_ip{$id} = $ip;
10162: }
10163: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10164: }
1.869 albertel 10165: &Apache::lonnet::do_cache_new('iphost','iphost',
10166: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10167: 48*60*60);
1.869 albertel 10168:
1.847 albertel 10169: return %iphost;
1.598 albertel 10170: }
10171:
1.992 raeburn 10172: #
10173: # Given a DNS returns the loncapa host name for that DNS
10174: #
10175: sub host_from_dns {
10176: my ($dns) = @_;
10177: my @hosts;
10178: my $ip;
10179:
1.993 raeburn 10180: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10181: $ip = $name_to_ip{$dns};
10182: }
10183: if (!$ip) {
10184: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10185: if (length($ip) == 4) {
10186: $ip = &IO::Socket::inet_ntoa($ip);
10187: }
10188: }
10189: if ($ip) {
10190: @hosts = get_hosts_from_ip($ip);
10191: return $hosts[0];
10192: }
10193: return undef;
1.986 foxr 10194: }
1.992 raeburn 10195:
1.1074 raeburn 10196: sub get_internet_names {
10197: my ($lonid) = @_;
10198: return if ($lonid eq '');
10199: my ($idnref,$cached)=
10200: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10201: if ($cached) {
10202: return $idnref;
10203: }
10204: my $ip = &get_host_ip($lonid);
10205: my @hosts = &get_hosts_from_ip($ip);
10206: my %iphost = &get_iphost();
10207: my (@idns,%seen);
10208: foreach my $id (@hosts) {
10209: my $dom = &host_domain($id);
10210: my $prim_id = &domain($dom,'primary');
10211: my $prim_ip = &get_host_ip($prim_id);
10212: next if ($seen{$prim_ip});
10213: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10214: foreach my $id (@{$iphost{$prim_ip}}) {
10215: my $intdom = &internet_dom($id);
10216: unless (grep(/^\Q$intdom\E$/,@idns)) {
10217: push(@idns,$intdom);
10218: }
10219: }
10220: }
10221: $seen{$prim_ip} = 1;
10222: }
10223: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10224: }
10225:
1.986 foxr 10226: }
10227:
1.1079 raeburn 10228: sub all_loncaparevs {
10229: 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);
10230: }
10231:
1.862 albertel 10232: BEGIN {
10233:
10234: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10235: unless ($readit) {
10236: {
10237: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10238: %perlvar = (%perlvar,%{$configvars});
10239: }
10240:
10241:
1.1 albertel 10242: # ------------------------------------------------------ Read spare server file
10243: {
1.448 albertel 10244: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10245:
10246: while (my $configline=<$config>) {
10247: chomp($configline);
1.284 matthew 10248: if ($configline) {
1.784 albertel 10249: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10250: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10251: push(@{ $spareid{$type} }, $host);
1.1 albertel 10252: }
10253: }
1.448 albertel 10254: close($config);
1.1 albertel 10255: }
1.11 www 10256: # ------------------------------------------------------------ Read permissions
10257: {
1.448 albertel 10258: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10259:
10260: while (my $configline=<$config>) {
1.448 albertel 10261: chomp($configline);
10262: if ($configline) {
10263: my ($role,$perm)=split(/ /,$configline);
10264: if ($perm ne '') { $pr{$role}=$perm; }
10265: }
1.11 www 10266: }
1.448 albertel 10267: close($config);
1.11 www 10268: }
10269:
10270: # -------------------------------------------- Read plain texts for permissions
10271: {
1.448 albertel 10272: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10273:
10274: while (my $configline=<$config>) {
1.448 albertel 10275: chomp($configline);
10276: if ($configline) {
1.742 raeburn 10277: my ($short,@plain)=split(/:/,$configline);
10278: %{$prp{$short}} = ();
10279: if (@plain > 0) {
10280: $prp{$short}{'std'} = $plain[0];
10281: for (my $i=1; $i<@plain; $i++) {
10282: $prp{$short}{'alt'.$i} = $plain[$i];
10283: }
10284: }
1.448 albertel 10285: }
1.135 www 10286: }
1.448 albertel 10287: close($config);
1.135 www 10288: }
10289:
10290: # ---------------------------------------------------------- Read package table
10291: {
1.448 albertel 10292: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10293:
10294: while (my $configline=<$config>) {
1.483 albertel 10295: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10296: chomp($configline);
10297: my ($short,$plain)=split(/:/,$configline);
10298: my ($pack,$name)=split(/\&/,$short);
10299: if ($plain ne '') {
10300: $packagetab{$pack.'&'.$name.'&name'}=$name;
10301: $packagetab{$short}=$plain;
10302: }
1.11 www 10303: }
1.448 albertel 10304: close($config);
1.329 matthew 10305: }
10306:
1.1073 raeburn 10307: # ---------------------------------------------------------- Read loncaparev table
10308: {
10309: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10310: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10311: while (my $configline=<$config>) {
10312: chomp($configline);
10313: my ($hostid,$loncaparev)=split(/:/,$configline);
10314: $loncaparevs{$hostid}=$loncaparev;
10315: }
10316: close($config);
10317: }
10318: }
10319: }
10320:
1.1074 raeburn 10321: # ---------------------------------------------------------- Read serverhostID table
10322: {
10323: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10324: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10325: while (my $configline=<$config>) {
10326: chomp($configline);
10327: my ($name,$id)=split(/:/,$configline);
10328: $serverhomeIDs{$name}=$id;
10329: }
10330: close($config);
10331: }
10332: }
10333: }
10334:
1.1079 raeburn 10335: {
10336: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10337: if (-e $file) {
10338: my $parser = HTML::LCParser->new($file);
10339: while (my $token = $parser->get_token()) {
10340: if ($token->[0] eq 'S') {
10341: my $item = $token->[1];
10342: my $name = $token->[2]{'name'};
10343: my $value = $token->[2]{'value'};
10344: if ($item ne '' && $name ne '' && $value ne '') {
10345: my $release = $parser->get_text();
10346: $release =~ s/(^\s*|\s*$ )//gx;
10347: $needsrelease{$item.':'.$name.':'.$value} = $release;
10348: }
10349: }
10350: }
10351: }
1.1073 raeburn 10352: }
10353:
1.329 matthew 10354: # ------------- set up temporary directory
10355: {
10356: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10357:
1.11 www 10358: }
10359:
1.794 albertel 10360: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10361: 'compress_threshold'=> 20_000,
10362: });
1.185 www 10363:
1.281 www 10364: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10365: $dumpcount=0;
1.958 www 10366: $locknum=0;
1.22 www 10367:
1.163 harris41 10368: &logtouch();
1.672 albertel 10369: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10370: $readit=1;
1.564 albertel 10371: {
10372: use integer;
10373: my $test=(2**32)+1;
1.568 albertel 10374: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10375: &logthis(" Detected 64bit platform ($_64bit)");
10376: }
1.195 www 10377: }
1.1 albertel 10378: }
1.179 www 10379:
1.1 albertel 10380: 1;
1.191 harris41 10381: __END__
10382:
1.243 albertel 10383: =pod
10384:
1.191 harris41 10385: =head1 NAME
10386:
1.243 albertel 10387: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10388:
10389: =head1 SYNOPSIS
10390:
1.243 albertel 10391: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10392:
10393: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10394:
1.243 albertel 10395: Common parameters:
10396:
10397: =over 4
10398:
10399: =item *
10400:
10401: $uname : an internal username (if $cname expecting a course Id specifically)
10402:
10403: =item *
10404:
10405: $udom : a domain (if $cdom expecting a course's domain specifically)
10406:
10407: =item *
10408:
10409: $symb : a resource instance identifier
10410:
10411: =item *
10412:
10413: $namespace : the name of a .db file that contains the data needed or
10414: being set.
10415:
10416: =back
10417:
1.394 bowersj2 10418: =head1 OVERVIEW
1.191 harris41 10419:
1.394 bowersj2 10420: lonnet provides subroutines which interact with the
10421: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10422: about classes, users, and resources.
1.243 albertel 10423:
10424: For many of these objects you can also use this to store data about
10425: them or modify them in various ways.
1.191 harris41 10426:
1.394 bowersj2 10427: =head2 Symbs
1.191 harris41 10428:
1.394 bowersj2 10429: To identify a specific instance of a resource, LON-CAPA uses symbols
10430: or "symbs"X<symb>. These identifiers are built from the URL of the
10431: map, the resource number of the resource in the map, and the URL of
10432: the resource itself. The latter is somewhat redundant, but might help
10433: if maps change.
10434:
10435: An example is
10436:
10437: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10438:
10439: The respective map entry is
10440:
10441: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10442: title="Problem 2">
10443: </resource>
10444:
10445: Symbs are used by the random number generator, as well as to store and
10446: restore data specific to a certain instance of for example a problem.
10447:
10448: =head2 Storing And Retrieving Data
10449:
10450: X<store()>X<cstore()>X<restore()>Three of the most important functions
10451: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10452: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10453: is is the non-critical message twin of cstore. These functions are for
10454: handlers to store a perl hash to a user's permanent data space in an
10455: easy manner, and to retrieve it again on another call. It is expected
10456: that a handler would use this once at the beginning to retrieve data,
10457: and then again once at the end to send only the new data back.
10458:
10459: The data is stored in the user's data directory on the user's
10460: homeserver under the ID of the course.
10461:
10462: The hash that is returned by restore will have all of the previous
10463: value for all of the elements of the hash.
10464:
10465: Example:
10466:
10467: #creating a hash
10468: my %hash;
10469: $hash{'foo'}='bar';
10470:
10471: #storing it
10472: &Apache::lonnet::cstore(\%hash);
10473:
10474: #changing a value
10475: $hash{'foo'}='notbar';
10476:
10477: #adding a new value
10478: $hash{'bar'}='foo';
10479: &Apache::lonnet::cstore(\%hash);
10480:
10481: #retrieving the hash
10482: my %history=&Apache::lonnet::restore();
10483:
10484: #print the hash
10485: foreach my $key (sort(keys(%history))) {
10486: print("\%history{$key} = $history{$key}");
10487: }
10488:
10489: Will print out:
1.191 harris41 10490:
1.394 bowersj2 10491: %history{1:foo} = bar
10492: %history{1:keys} = foo:timestamp
10493: %history{1:timestamp} = 990455579
10494: %history{2:bar} = foo
10495: %history{2:foo} = notbar
10496: %history{2:keys} = foo:bar:timestamp
10497: %history{2:timestamp} = 990455580
10498: %history{bar} = foo
10499: %history{foo} = notbar
10500: %history{timestamp} = 990455580
10501: %history{version} = 2
10502:
10503: Note that the special hash entries C<keys>, C<version> and
10504: C<timestamp> were added to the hash. C<version> will be equal to the
10505: total number of versions of the data that have been stored. The
10506: C<timestamp> attribute will be the UNIX time the hash was
10507: stored. C<keys> is available in every historical section to list which
10508: keys were added or changed at a specific historical revision of a
10509: hash.
10510:
10511: B<Warning>: do not store the hash that restore returns directly. This
10512: will cause a mess since it will restore the historical keys as if the
10513: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10514:
1.394 bowersj2 10515: Calling convention:
1.191 harris41 10516:
1.394 bowersj2 10517: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10518: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10519:
1.394 bowersj2 10520: For more detailed information, see lonnet specific documentation.
1.191 harris41 10521:
1.394 bowersj2 10522: =head1 RETURN MESSAGES
1.191 harris41 10523:
1.394 bowersj2 10524: =over 4
1.191 harris41 10525:
1.394 bowersj2 10526: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10527:
1.394 bowersj2 10528: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10529: when the connection is brought back up
1.191 harris41 10530:
1.394 bowersj2 10531: =item * B<con_failed>: unable to contact remote host and unable to save message
10532: for later delivery
1.191 harris41 10533:
1.967 bisitz 10534: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10535:
1.394 bowersj2 10536: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10537: that was requested
1.191 harris41 10538:
1.243 albertel 10539: =back
1.191 harris41 10540:
1.243 albertel 10541: =head1 PUBLIC SUBROUTINES
1.191 harris41 10542:
1.243 albertel 10543: =head2 Session Environment Functions
1.191 harris41 10544:
1.243 albertel 10545: =over 4
1.191 harris41 10546:
1.394 bowersj2 10547: =item *
10548: X<appenv()>
1.949 raeburn 10549: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10550: the user envirnoment file, and will be restored for each access this
1.620 albertel 10551: user makes during this session, also modifies the %env for the current
1.949 raeburn 10552: process. Optional rolesarrayref - if defined contains a reference to an array
10553: of roles which are exempt from the restriction on modifying user.role entries
10554: in the user's environment.db and in %env.
1.191 harris41 10555:
10556: =item *
1.394 bowersj2 10557: X<delenv()>
1.987 raeburn 10558: B<delenv($delthis,$regexp)>: removes all items from the session
10559: environment file that begin with $delthis. If the
10560: optional second arg - $regexp - is true, $delthis is treated as a
10561: regular expression, otherwise \Q$delthis\E is used.
10562: The values are also deleted from the current processes %env.
1.191 harris41 10563:
1.795 albertel 10564: =item * get_env_multiple($name)
10565:
10566: gets $name from the %env hash, it seemlessly handles the cases where multiple
10567: values may be defined and end up as an array ref.
10568:
10569: returns an array of values
10570:
1.243 albertel 10571: =back
10572:
10573: =head2 User Information
1.191 harris41 10574:
1.243 albertel 10575: =over 4
1.191 harris41 10576:
10577: =item *
1.394 bowersj2 10578: X<queryauthenticate()>
10579: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10580: authentication scheme
10581:
10582: =item *
1.394 bowersj2 10583: X<authenticate()>
1.1073 raeburn 10584: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 10585: authenticate user from domain's lib servers (first use the current
10586: one). C<$upass> should be the users password.
1.1073 raeburn 10587: $checkdefauth is optional (value is 1 if a check should be made to
10588: authenticate user using default authentication method, and allow
10589: account creation if username does not have account in the domain).
10590: $clientcancheckhost is optional (value is 1 if checking whether the
10591: server can host will occur on the client side in lonauth.pm).
1.191 harris41 10592:
10593: =item *
1.394 bowersj2 10594: X<homeserver()>
10595: B<homeserver($uname,$udom)>: find the server which has
10596: the user's directory and files (there must be only one), this caches
10597: the answer, and also caches if there is a borken connection.
1.191 harris41 10598:
10599: =item *
1.394 bowersj2 10600: X<idget()>
10601: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10602: (IDs are a unique resource in a domain, there must be only 1 ID per
10603: username, and only 1 username per ID in a specific domain) (returns
10604: hash: id=>name,id=>name)
1.191 harris41 10605:
10606: =item *
1.394 bowersj2 10607: X<idrget()>
10608: B<idrget($udom,@unames)>: find the IDs behind a list of
10609: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10610:
10611: =item *
1.394 bowersj2 10612: X<idput()>
10613: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10614:
10615: =item *
1.394 bowersj2 10616: X<rolesinit()>
10617: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10618:
10619: =item *
1.551 albertel 10620: X<getsection()>
10621: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10622: course $cname, return section name/number or '' for "not in course"
10623: and '-1' for "no section"
10624:
10625: =item *
1.394 bowersj2 10626: X<userenvironment()>
10627: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10628: passed in @what from the requested user's environment, returns a hash
10629:
1.858 raeburn 10630: =item *
10631: X<userlog_query()>
1.859 albertel 10632: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10633: activity.log file. %filters defines filters applied when parsing the
10634: log file. These can be start or end timestamps, or the type of action
10635: - log to look for Login or Logout events, check for Checkin or
10636: Checkout, role for role selection. The response is in the form
10637: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10638: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10639:
1.243 albertel 10640: =back
10641:
10642: =head2 User Roles
10643:
10644: =over 4
10645:
10646: =item *
10647:
1.810 raeburn 10648: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10649: F: full access
10650: U,I,K: authentication modes (cxx only)
10651: '': forbidden
10652: 1: user needs to choose course
10653: 2: browse allowed
1.766 albertel 10654: A: passphrase authentication needed
1.243 albertel 10655:
10656: =item *
10657:
10658: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10659: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10660: and course level
10661:
10662: =item *
10663:
1.988 raeburn 10664: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10665: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10666: $type is Course (default) or Community.
1.988 raeburn 10667: If $forcedefault evaluates to true, text returned will be default
10668: text for $type. Otherwise, if this is a course, the text returned
10669: will be a custom name for the role (if defined in the course's
10670: environment). If no custom name is defined the default is returned.
10671:
1.832 raeburn 10672: =item *
10673:
1.935 raeburn 10674: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10675: All arguments are optional. Returns a hash of a roles, either for
10676: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10677: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10678: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10679: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10680: For each key, value is set to colon-separated start and end times for
10681: the role. If no username and domain are specified, will default to
1.934 raeburn 10682: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10683: of role statuses (active, future or previous), roles
10684: (e.g., cc,in, st etc.) and domains of the roles which can be used
10685: to restrict the list of roles reported. If no array ref is
10686: provided for types, will default to return only active roles.
1.834 albertel 10687:
1.243 albertel 10688: =back
10689:
10690: =head2 User Modification
10691:
10692: =over 4
10693:
10694: =item *
10695:
1.957 raeburn 10696: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10697: user for the level given by URL. Optional start and end dates (leave empty
10698: string or zero for "no date")
1.191 harris41 10699:
10700: =item *
10701:
1.243 albertel 10702: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10703: change a users, password, possible return values are: ok,
10704: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10705: refused
1.191 harris41 10706:
10707: =item *
10708:
1.243 albertel 10709: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10710:
10711: =item *
10712:
1.1058 raeburn 10713: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10714: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10715:
10716: will update user information (firstname,middlename,lastname,generation,
10717: permanentemail), and if forceid is true, student/employee ID also.
10718: A user's institutional affiliation(s) can also be updated.
10719: User information fields will not be overwritten with empty entries
10720: unless the field is included in the $candelete array reference.
10721: This array is included when a single user is modified via "Manage Users",
10722: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10723:
10724: =item *
10725:
1.286 matthew 10726: modifystudent
10727:
1.957 raeburn 10728: modify a student's enrollment and identification information.
1.286 matthew 10729: The course id is resolved based on the current users environment.
10730: This means the envoking user must be a course coordinator or otherwise
10731: associated with a course.
10732:
1.297 matthew 10733: This call is essentially a wrapper for lonnet::modifyuser and
10734: lonnet::modify_student_enrollment
1.286 matthew 10735:
10736: Inputs:
10737:
10738: =over 4
10739:
1.957 raeburn 10740: =item B<$udom> Student's loncapa domain
1.286 matthew 10741:
1.957 raeburn 10742: =item B<$uname> Student's loncapa login name
1.286 matthew 10743:
1.964 bisitz 10744: =item B<$uid> Student/Employee ID
1.286 matthew 10745:
1.957 raeburn 10746: =item B<$umode> Student's authentication mode
1.286 matthew 10747:
1.957 raeburn 10748: =item B<$upass> Student's password
1.286 matthew 10749:
1.957 raeburn 10750: =item B<$first> Student's first name
1.286 matthew 10751:
1.957 raeburn 10752: =item B<$middle> Student's middle name
1.286 matthew 10753:
1.957 raeburn 10754: =item B<$last> Student's last name
1.286 matthew 10755:
1.957 raeburn 10756: =item B<$gene> Student's generation
1.286 matthew 10757:
1.957 raeburn 10758: =item B<$usec> Student's section in course
1.286 matthew 10759:
10760: =item B<$end> Unix time of the roles expiration
10761:
10762: =item B<$start> Unix time of the roles start date
10763:
10764: =item B<$forceid> If defined, allow $uid to be changed
10765:
10766: =item B<$desiredhome> server to use as home server for student
10767:
1.957 raeburn 10768: =item B<$email> Student's permanent e-mail address
10769:
10770: =item B<$type> Type of enrollment (auto or manual)
10771:
1.963 raeburn 10772: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10773:
10774: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10775:
1.963 raeburn 10776: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10777:
1.963 raeburn 10778: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10779:
1.963 raeburn 10780: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10781:
1.286 matthew 10782: =back
1.297 matthew 10783:
10784: =item *
10785:
10786: modify_student_enrollment
10787:
10788: Change a students enrollment status in a class. The environment variable
10789: 'role.request.course' must be defined for this function to proceed.
10790:
10791: Inputs:
10792:
10793: =over 4
10794:
10795: =item $udom, students domain
10796:
10797: =item $uname, students name
10798:
10799: =item $uid, students user id
10800:
10801: =item $first, students first name
10802:
10803: =item $middle
10804:
10805: =item $last
10806:
10807: =item $gene
10808:
10809: =item $usec
10810:
10811: =item $end
10812:
10813: =item $start
10814:
1.957 raeburn 10815: =item $type
10816:
10817: =item $locktype
10818:
10819: =item $cid
10820:
10821: =item $selfenroll
10822:
10823: =item $context
10824:
1.297 matthew 10825: =back
10826:
1.191 harris41 10827:
10828: =item *
10829:
1.243 albertel 10830: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10831: custom role; give a custom role to a user for the level given by URL. Specify
10832: name and domain of role author, and role name
1.191 harris41 10833:
10834: =item *
10835:
1.243 albertel 10836: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10837:
10838: =item *
10839:
1.243 albertel 10840: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10841:
10842: =back
10843:
10844: =head2 Course Infomation
10845:
10846: =over 4
1.191 harris41 10847:
10848: =item *
10849:
1.631 albertel 10850: coursedescription($courseid) : returns a hash of information about the
10851: specified course id, including all environment settings for the
10852: course, the description of the course will be in the hash under the
10853: key 'description'
1.191 harris41 10854:
10855: =item *
10856:
1.624 albertel 10857: resdata($name,$domain,$type,@which) : request for current parameter
10858: setting for a specific $type, where $type is either 'course' or 'user',
10859: @what should be a list of parameters to ask about. This routine caches
10860: answers for 5 minutes.
1.243 albertel 10861:
1.877 foxr 10862: =item *
10863:
10864: get_courseresdata($courseid, $domain) : dump the entire course resource
10865: data base, returning a hash that is keyed by the resource name and has
10866: values that are the resource value. I believe that the timestamps and
10867: versions are also returned.
10868:
10869:
1.243 albertel 10870: =back
10871:
10872: =head2 Course Modification
10873:
10874: =over 4
1.191 harris41 10875:
10876: =item *
10877:
1.243 albertel 10878: writecoursepref($courseid,%prefs) : write preferences (environment
10879: database) for a course
1.191 harris41 10880:
10881: =item *
10882:
1.1011 raeburn 10883: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10884:
10885: =item *
10886:
1.1038 raeburn 10887: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 10888:
10889: =back
10890:
10891: =head2 Resource Subroutines
10892:
10893: =over 4
1.191 harris41 10894:
10895: =item *
10896:
1.243 albertel 10897: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 10898:
10899: =item *
10900:
1.243 albertel 10901: repcopy($filename) : subscribes to the requested file, and attempts to
10902: replicate from the owning library server, Might return
1.607 raeburn 10903: 'unavailable', 'not_found', 'forbidden', 'ok', or
10904: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 10905: resource. Expects the local filesystem pathname
10906: (/home/httpd/html/res/....)
10907:
10908: =back
10909:
10910: =head2 Resource Information
10911:
10912: =over 4
1.191 harris41 10913:
10914: =item *
10915:
1.243 albertel 10916: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10917: a vairety of different possible values, $varname should be a request
10918: string, and the other parameters can be used to specify who and what
10919: one is asking about.
10920:
10921: Possible values for $varname are environment.lastname (or other item
10922: from the envirnment hash), user.name (or someother aspect about the
10923: user), resource.0.maxtries (or some other part and parameter of a
10924: resource)
1.204 albertel 10925:
10926: =item *
10927:
1.243 albertel 10928: directcondval($number) : get current value of a condition; reads from a state
10929: string
1.204 albertel 10930:
10931: =item *
10932:
1.243 albertel 10933: condval($condidx) : value of condition index based on state
1.204 albertel 10934:
10935: =item *
10936:
1.243 albertel 10937: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10938: resource's metadata, $what should be either a specific key, or either
10939: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10940: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10941:
10942: this function automatically caches all requests
1.191 harris41 10943:
10944: =item *
10945:
1.243 albertel 10946: metadata_query($query,$custom,$customshow) : make a metadata query against the
10947: network of library servers; returns file handle of where SQL and regex results
10948: will be stored for query
1.191 harris41 10949:
10950: =item *
10951:
1.243 albertel 10952: symbread($filename) : return symbolic list entry (filename argument optional);
10953: returns the data handle
1.191 harris41 10954:
10955: =item *
10956:
1.243 albertel 10957: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 10958: a possible symb for the URL in $thisfn, and if is an encryypted
10959: resource that the user accessed using /enc/ returns a 1 on success, 0
10960: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 10961: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 10962:
1.191 harris41 10963:
10964: =item *
10965:
1.243 albertel 10966: symbclean($symb) : removes versions numbers from a symb, returns the
10967: cleaned symb
1.191 harris41 10968:
10969: =item *
10970:
1.243 albertel 10971: is_on_map($uri) : checks if the $uri is somewhere on the current
10972: course map, user must be in a course for it to work.
1.191 harris41 10973:
10974: =item *
10975:
1.243 albertel 10976: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 10977:
10978: =item *
10979:
1.243 albertel 10980: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10981: a random seed, all arguments are optional, if they aren't sent it uses the
10982: environment to derive them. Note: if symb isn't sent and it can't get one
10983: from &symbread it will use the current time as its return value
1.191 harris41 10984:
10985: =item *
10986:
1.243 albertel 10987: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10988: unfakeable, receipt
1.191 harris41 10989:
10990: =item *
10991:
1.620 albertel 10992: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 10993:
10994: =item *
10995:
1.243 albertel 10996: countacc($url) : count the number of accesses to a given URL
1.191 harris41 10997:
10998: =item *
10999:
1.243 albertel 11000: 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 11001:
11002: =item *
11003:
1.243 albertel 11004: 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 11005:
11006: =item *
11007:
1.243 albertel 11008: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11009:
11010: =item *
11011:
1.243 albertel 11012: devalidate($symb) : devalidate temporary spreadsheet calculations,
11013: forcing spreadsheet to reevaluate the resource scores next time.
11014:
11015: =back
11016:
11017: =head2 Storing/Retreiving Data
11018:
11019: =over 4
1.191 harris41 11020:
11021: =item *
11022:
1.243 albertel 11023: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11024: for this url; hashref needs to be given and should be a \%hashname; the
11025: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11026: be derived from the env
1.191 harris41 11027:
11028: =item *
11029:
1.243 albertel 11030: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11031: uses critical subroutine
1.191 harris41 11032:
11033: =item *
11034:
1.243 albertel 11035: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11036: all args are optional
1.191 harris41 11037:
11038: =item *
11039:
1.717 albertel 11040: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11041: dumps the complete (or key matching regexp) namespace into a hash
11042: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11043: normally &store()ed into
11044:
11045: $range should be either an integer '100' (give me the first 100
11046: matching records)
11047: or be two integers sperated by a - with no spaces
11048: '30-50' (give me the 30th through the 50th matching
11049: records)
11050:
11051:
11052: =item *
11053:
11054: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11055: replaces a &store() version of data with a replacement set of data
11056: for a particular resource in a namespace passed in the $storehash hash
11057: reference
11058:
11059: =item *
11060:
1.243 albertel 11061: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11062: works very similar to store/cstore, but all data is stored in a
11063: temporary location and can be reset using tmpreset, $storehash should
11064: be a hash reference, returns nothing on success
1.191 harris41 11065:
11066: =item *
11067:
1.243 albertel 11068: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11069: similar to restore, but all data is stored in a temporary location and
11070: can be reset using tmpreset. Returns a hash of values on success,
11071: error string otherwise.
1.191 harris41 11072:
11073: =item *
11074:
1.243 albertel 11075: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11076: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11077:
11078: =item *
11079:
1.243 albertel 11080: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11081: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11082:
11083: =item *
11084:
1.243 albertel 11085: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11086: namesp ($udom and $uname are optional)
1.191 harris41 11087:
11088: =item *
11089:
1.702 albertel 11090: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11091: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11092: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11093:
1.702 albertel 11094: $range should be either an integer '100' (give me the first 100
11095: matching records)
11096: or be two integers sperated by a - with no spaces
11097: '30-50' (give me the 30th through the 50th matching
11098: records)
1.449 matthew 11099: =item *
11100:
11101: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11102: $store can be a scalar, an array reference, or if the amount to be
11103: incremented is > 1, a hash reference.
11104:
11105: ($udom and $uname are optional)
1.191 harris41 11106:
11107: =item *
11108:
1.243 albertel 11109: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11110: ($udom and $uname are optional)
1.191 harris41 11111:
11112: =item *
11113:
1.243 albertel 11114: cput($namespace,$storehash,$udom,$uname) : critical put
11115: ($udom and $uname are optional)
1.191 harris41 11116:
11117: =item *
11118:
1.748 albertel 11119: newput($namespace,$storehash,$udom,$uname) :
11120:
11121: Attempts to store the items in the $storehash, but only if they don't
11122: currently exist, if this succeeds you can be certain that you have
11123: successfully created a new key value pair in the $namespace db.
11124:
11125:
11126: Args:
11127: $namespace: name of database to store values to
11128: $storehash: hashref to store to the db
11129: $udom: (optional) domain of user containing the db
11130: $uname: (optional) name of user caontaining the db
11131:
11132: Returns:
11133: 'ok' -> succeeded in storing all keys of $storehash
11134: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11135: least <key> already existed in the db (other
11136: requested keys may also already exist)
1.967 bisitz 11137: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11138: 'con_lost' -> unable to contact request server
11139: 'refused' -> action was not allowed by remote machine
11140:
11141:
11142: =item *
11143:
1.243 albertel 11144: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11145: reference filled in from namesp (encrypts the return communication)
11146: ($udom and $uname are optional)
1.191 harris41 11147:
11148: =item *
11149:
1.243 albertel 11150: log($udom,$name,$home,$message) : write to permanent log for user; use
11151: critical subroutine
11152:
1.806 raeburn 11153: =item *
11154:
1.860 raeburn 11155: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11156: array reference filled in from namespace found in domain level on either
11157: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11158:
11159: =item *
11160:
1.860 raeburn 11161: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11162: domain level either on specified domain server ($uhome) or primary domain
11163: server ($udom and $uhome are optional)
1.806 raeburn 11164:
1.943 raeburn 11165: =item *
11166:
11167: get_domain_defaults($target_domain) : returns hash with defaults for
11168: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11169: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11170: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11171: Values are retrieved from cache (if current), or from domain's configuration.db
11172: (if available), or lastly from values in lonTabs/dns_domain,tab,
11173: or lonTabs/domain.tab.
11174:
11175: %domdefaults = &get_auth_defaults($target_domain);
11176:
1.243 albertel 11177: =back
11178:
11179: =head2 Network Status Functions
11180:
11181: =over 4
1.191 harris41 11182:
11183: =item *
11184:
11185: dirlist($uri) : return directory list based on URI
11186:
11187: =item *
11188:
1.243 albertel 11189: spareserver() : find server with least workload from spare.tab
11190:
1.986 foxr 11191:
11192: =item *
11193:
11194: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11195: if there is no corresponding loncapa host.
11196:
1.243 albertel 11197: =back
11198:
1.986 foxr 11199:
1.243 albertel 11200: =head2 Apache Request
11201:
11202: =over 4
1.191 harris41 11203:
11204: =item *
11205:
1.243 albertel 11206: ssi($url,%hash) : server side include, does a complete request cycle on url to
11207: localhost, posts hash
11208:
11209: =back
11210:
11211: =head2 Data to String to Data
11212:
11213: =over 4
1.191 harris41 11214:
11215: =item *
11216:
1.243 albertel 11217: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11218: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11219:
11220: =item *
11221:
1.243 albertel 11222: hashref2str($hashref) : convert a hashref into a string complete with
11223: escaping and '=' and '&' separators, supports elements that are
11224: arrayrefs and hashrefs
1.191 harris41 11225:
11226: =item *
11227:
1.243 albertel 11228: arrayref2str($arrayref) : convert an arrayref into a string complete
11229: with escaping and '&' separators, supports elements that are arrayrefs
11230: and hashrefs
1.191 harris41 11231:
11232: =item *
11233:
1.243 albertel 11234: str2hash($string) : convert string to hash using unescaping and
11235: splitting on '=' and '&', supports elements that are arrayrefs and
11236: hashrefs
1.191 harris41 11237:
11238: =item *
11239:
1.243 albertel 11240: str2array($string) : convert string to hash using unescaping and
11241: splitting on '&', supports elements that are arrayrefs and hashrefs
11242:
11243: =back
11244:
11245: =head2 Logging Routines
11246:
11247: =over 4
11248:
11249: These routines allow one to make log messages in the lonnet.log and
11250: lonnet.perm logfiles.
1.191 harris41 11251:
11252: =item *
11253:
1.243 albertel 11254: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11255:
11256: =item *
11257:
1.243 albertel 11258: logthis() : append message to the normal lonnet.log file, it gets
11259: preiodically rolled over and deleted.
1.191 harris41 11260:
11261: =item *
11262:
1.243 albertel 11263: logperm() : append a permanent message to lonnet.perm.log, this log
11264: file never gets deleted by any automated portion of the system, only
11265: messages of critical importance should go in here.
11266:
11267: =back
11268:
11269: =head2 General File Helper Routines
11270:
11271: =over 4
1.191 harris41 11272:
11273: =item *
11274:
1.481 raeburn 11275: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11276: (a) files in /uploaded
11277: (i) If a local copy of the file exists -
11278: compares modification date of local copy with last-modified date for
11279: definitive version stored on home server for course. If local copy is
11280: stale, requests a new version from the home server and stores it.
11281: If the original has been removed from the home server, then local copy
11282: is unlinked.
11283: (ii) If local copy does not exist -
11284: requests the file from the home server and stores it.
11285:
11286: If $caller is 'uploadrep':
11287: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11288: for request for files originally uploaded via DOCS.
11289: - returns 'ok' if fresh local copy now available, -1 otherwise.
11290:
11291: Otherwise:
11292: This indicates a call from the content generation phase of the request.
11293: - returns the entire contents of the file or -1.
11294:
11295: (b) files in /res
11296: - returns the entire contents of a file or -1;
11297: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11298:
1.712 albertel 11299:
11300: =item *
11301:
11302: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11303: reference
11304:
11305: returns either a stat() list of data about the file or an empty list
11306: if the file doesn't exist or couldn't find out about it (connection
11307: problems or user unknown)
11308:
1.191 harris41 11309: =item *
11310:
1.243 albertel 11311: filelocation($dir,$file) : returns file system location of a file
11312: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11313: directory that relative $file lookups are to looked in ($dir of /a/dir
11314: and a file of ../bob will become /a/bob)
1.191 harris41 11315:
11316: =item *
11317:
11318: hreflocation($dir,$file) : returns file system location or a URL; same as
11319: filelocation except for hrefs
11320:
11321: =item *
11322:
11323: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11324:
1.243 albertel 11325: =back
11326:
1.608 albertel 11327: =head2 Usererfile file routines (/uploaded*)
11328:
11329: =over 4
11330:
11331: =item *
11332:
11333: userfileupload(): main rotine for putting a file in a user or course's
11334: filespace, arguments are,
11335:
1.620 albertel 11336: formname - required - this is the name of the element in $env where the
1.608 albertel 11337: filename, and the contents of the file to create/modifed exist
1.620 albertel 11338: the filename is in $env{'form.'.$formname.'.filename'} and the
11339: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 11340: coursedoc - if true, store the file in the course of the active role
11341: of the current user
11342: subdir - required - subdirectory to put the file in under ../userfiles/
11343: if undefined, it will be placed in "unknown"
11344:
11345: (This routine calls clean_filename() to remove any dangerous
11346: characters from the filename, and then calls finuserfileupload() to
11347: complete the transaction)
11348:
11349: returns either the url of the uploaded file (/uploaded/....) if successful
11350: and /adm/notfound.html if unsuccessful
11351:
11352: =item *
11353:
11354: clean_filename(): routine for cleaing a filename up for storage in
11355: userfile space, argument is:
11356:
11357: filename - proposed filename
11358:
11359: returns: the new clean filename
11360:
11361: =item *
11362:
11363: finishuserfileupload(): routine that creaes and sends the file to
11364: userspace, probably shouldn't be called directly
11365:
11366: docuname: username or courseid of destination for the file
11367: docudom: domain of user/course of destination for the file
11368: formname: same as for userfileupload()
11369: fname: filename (inculding subdirectories) for the file
11370:
11371: returns either the url of the uploaded file (/uploaded/....) if successful
11372: and /adm/notfound.html if unsuccessful
11373:
11374: =item *
11375:
11376: renameuserfile(): renames an existing userfile to a new name
11377:
11378: Args:
11379: docuname: username or courseid of destination for the file
11380: docudom: domain of user/course of destination for the file
11381: old: current file name (including any subdirs under userfiles)
11382: new: desired file name (including any subdirs under userfiles)
11383:
11384: =item *
11385:
11386: mkdiruserfile(): creates a directory is a userfiles dir
11387:
11388: Args:
11389: docuname: username or courseid of destination for the file
11390: docudom: domain of user/course of destination for the file
11391: dir: dir to create (including any subdirs under userfiles)
11392:
11393: =item *
11394:
11395: removeuserfile(): removes a file that exists in userfiles
11396:
11397: Args:
11398: docuname: username or courseid of destination for the file
11399: docudom: domain of user/course of destination for the file
11400: fname: filname to delete (including any subdirs under userfiles)
11401:
11402: =item *
11403:
11404: removeuploadedurl(): convience function for removeuserfile()
11405:
11406: Args:
11407: url: a full /uploaded/... url to delete
11408:
1.747 albertel 11409: =item *
11410:
11411: get_portfile_permissions():
11412: Args:
11413: domain: domain of user or course contain the portfolio files
11414: user: name of user or num of course contain the portfolio files
11415: Returns:
11416: hashref of a dump of the proper file_permissions.db
11417:
11418:
11419: =item *
11420:
11421: get_access_controls():
11422:
11423: Args:
11424: current_permissions: the hash ref returned from get_portfile_permissions()
11425: group: (optional) the group you want the files associated with
11426: file: (optional) the file you want access info on
11427:
11428: Returns:
1.749 raeburn 11429: a hash (keys are file names) of hashes containing
11430: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11431: values are XML containing access control settings (see below)
1.747 albertel 11432:
11433: Internal notes:
11434:
1.749 raeburn 11435: access controls are stored in file_permissions.db as key=value pairs.
11436: key -> path to file/file_name\0uniqueID:scope_end_start
11437: where scope -> public,guest,course,group,domains or users.
11438: end -> UNIX time for end of access (0 -> no end date)
11439: start -> UNIX time for start of access
11440:
11441: value -> XML description of access control
11442: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11443: <start></start>
11444: <end></end>
11445:
11446: <password></password> for scope type = guest
11447:
11448: <domain></domain> for scope type = course or group
11449: <number></number>
11450: <roles id="">
11451: <role></role>
11452: <access></access>
11453: <section></section>
11454: <group></group>
11455: </roles>
11456:
11457: <dom></dom> for scope type = domains
11458:
11459: <users> for scope type = users
11460: <user>
11461: <uname></uname>
11462: <udom></udom>
11463: </user>
11464: </users>
11465: </scope>
11466:
11467: Access data is also aggregated for each file in an additional key=value pair:
11468: key -> path to file/file_name\0accesscontrol
11469: value -> reference to hash
11470: hash contains key = value pairs
11471: where key = uniqueID:scope_end_start
11472: value = UNIX time record was last updated
11473:
11474: Used to improve speed of look-ups of access controls for each file.
11475:
11476: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11477:
11478: modify_access_controls():
11479:
11480: Modifies access controls for a portfolio file
11481: Args
11482: 1. file name
11483: 2. reference to hash of required changes,
11484: 3. domain
11485: 4. username
11486: where domain,username are the domain of the portfolio owner
11487: (either a user or a course)
11488:
11489: Returns:
11490: 1. result of additions or updates ('ok' or 'error', with error message).
11491: 2. result of deletions ('ok' or 'error', with error message).
11492: 3. reference to hash of any new or updated access controls.
11493: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11494: key = integer (inbound ID)
11495: value = uniqueID
1.747 albertel 11496:
1.608 albertel 11497: =back
11498:
1.243 albertel 11499: =head2 HTTP Helper Routines
11500:
11501: =over 4
11502:
1.191 harris41 11503: =item *
11504:
11505: escape() : unpack non-word characters into CGI-compatible hex codes
11506:
11507: =item *
11508:
11509: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11510:
1.243 albertel 11511: =back
11512:
11513: =head1 PRIVATE SUBROUTINES
11514:
11515: =head2 Underlying communication routines (Shouldn't call)
11516:
11517: =over 4
11518:
11519: =item *
11520:
11521: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11522:
11523: =item *
11524:
11525: reply() : uses subreply to send a message to remote machine, logs all failures
11526:
11527: =item *
11528:
11529: critical() : passes a critical message to another server; if cannot
11530: get through then place message in connection buffer directory and
11531: returns con_delayed, if incapable of saving message, returns
11532: con_failed
11533:
11534: =item *
11535:
11536: reconlonc() : tries to reconnect lonc client processes.
11537:
11538: =back
11539:
11540: =head2 Resource Access Logging
11541:
11542: =over 4
11543:
11544: =item *
11545:
11546: flushcourselogs() : flush (save) buffer logs and access logs
11547:
11548: =item *
11549:
11550: courselog($what) : save message for course in hash
11551:
11552: =item *
11553:
11554: courseacclog($what) : save message for course using &courselog(). Perform
11555: special processing for specific resource types (problems, exams, quizzes, etc).
11556:
1.191 harris41 11557: =item *
11558:
11559: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11560: as a PerlChildExitHandler
1.243 albertel 11561:
11562: =back
11563:
11564: =head2 Other
11565:
11566: =over 4
11567:
11568: =item *
11569:
11570: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11571:
11572: =back
11573:
11574: =cut
1.877 foxr 11575:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>