Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.861
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.861 ! albertel 4: # $Id: lonnet.pm,v 1.860 2007/04/03 18:47:29 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.1 albertel 30: package Apache::lonnet;
31:
32: use strict;
1.8 www 33: use LWP::UserAgent();
1.15 www 34: use HTTP::Headers;
1.486 www 35: use HTTP::Date;
36: # use Date::Parse;
1.11 www 37: use vars
1.847 albertel 38: qw(%perlvar %badServerCache %spareid
1.845 albertel 39: %pr %prp $memcache %packagetab
1.662 raeburn 40: %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount
1.741 raeburn 41: %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.685 raeburn 42: $tmpdir $_64bit %env);
1.403 www 43:
1.1 albertel 44: use IO::Socket;
1.31 www 45: use GDBM_File;
1.208 albertel 46: use HTML::LCParser;
1.637 raeburn 47: use HTML::Parser;
1.88 www 48: use Fcntl qw(:flock);
1.557 albertel 49: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539 albertel 50: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 51: use Cache::Memcached;
1.676 albertel 52: use Digest::MD5;
1.790 albertel 53: use Math::Random;
1.807 albertel 54: use LONCAPA qw(:DEFAULT :match);
1.740 www 55: use LONCAPA::Configuration;
1.676 albertel 56:
1.195 www 57: my $readit;
1.550 foxr 58: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 59:
1.619 albertel 60: require Exporter;
61:
62: our @ISA = qw (Exporter);
63: our @EXPORT = qw(%env);
64:
1.449 matthew 65: =pod
66:
67: =head1 Package Variables
68:
69: These are largely undocumented, so if you decipher one please note it here.
70:
71: =over 4
72:
73: =item $processmarker
74:
75: Contains the time this process was started and this servers host id.
76:
77: =item $dumpcount
78:
79: Counts the number of times a message log flush has been attempted (regardless
80: of success) by this process. Used as part of the filename when messages are
81: delayed.
82:
83: =back
84:
85: =cut
86:
87:
1.1 albertel 88: # --------------------------------------------------------------------- Logging
1.729 www 89: {
90: my $logid;
91: sub instructor_log {
92: my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
93: $logid++;
94: my $id=time().'00000'.$$.'00000'.$logid;
95: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 96: { $id => {
97: 'exe_uname' => $env{'user.name'},
98: 'exe_udom' => $env{'user.domain'},
99: 'exe_time' => time(),
100: 'exe_ip' => $ENV{'REMOTE_ADDR'},
101: 'delflag' => $delflag,
102: 'logentry' => $storehash,
103: 'uname' => $uname,
104: 'udom' => $udom,
105: }
106: },
1.729 www 107: $env{'course.'.$env{'request.course.id'}.'.domain'},
108: $env{'course.'.$env{'request.course.id'}.'.num'}
109: );
110: }
111: }
1.1 albertel 112:
1.163 harris41 113: sub logtouch {
114: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 115: unless (-e "$execdir/logs/lonnet.log") {
116: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 117: close $fh;
118: }
119: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
120: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
121: }
122:
1.1 albertel 123: sub logthis {
124: my $message=shift;
125: my $execdir=$perlvar{'lonDaemons'};
126: my $now=time;
127: my $local=localtime($now);
1.448 albertel 128: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
129: print $fh "$local ($$): $message\n";
130: close($fh);
131: }
1.1 albertel 132: return 1;
133: }
134:
135: sub logperm {
136: my $message=shift;
137: my $execdir=$perlvar{'lonDaemons'};
138: my $now=time;
139: my $local=localtime($now);
1.448 albertel 140: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
141: print $fh "$now:$message:$local\n";
142: close($fh);
143: }
1.1 albertel 144: return 1;
145: }
146:
1.850 albertel 147: sub create_connection {
1.853 albertel 148: my ($hostname,$lonid) = @_;
1.851 albertel 149: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 150: Type => SOCK_STREAM,
151: Timeout => 10);
152: return 0 if (!$client);
1.854 albertel 153: print $client (join(':',$hostname,$lonid,&machine_ids($lonid))."\n");
1.850 albertel 154: my $result = <$client>;
155: chomp($result);
156: return 1 if ($result eq 'done');
157: return 0;
158: }
159:
160:
1.1 albertel 161: # -------------------------------------------------- Non-critical communication
162: sub subreply {
163: my ($cmd,$server)=@_;
1.838 albertel 164: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 165: #
166: # With loncnew process trimming, there's a timing hole between lonc server
167: # process exit and the master server picking up the listen on the AF_UNIX
168: # socket. In that time interval, a lock file will exist:
169:
170: my $lockfile=$peerfile.".lock";
171: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
172: sleep(1);
173: }
174: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 175: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 176: #
1.550 foxr 177: # We'll give the connection a few tries before abandoning it. If
178: # connection is not possible, we'll con_lost back to the client.
179: #
180: my $client;
181: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
182: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
183: Type => SOCK_STREAM,
184: Timeout => 10);
185: if($client) {
186: last; # Connected!
1.850 albertel 187: } else {
1.853 albertel 188: &create_connection(&hostname($server),$server);
1.550 foxr 189: }
1.850 albertel 190: sleep(1); # Try again later if failed connection.
1.550 foxr 191: }
192: my $answer;
193: if ($client) {
1.704 albertel 194: print $client "sethost:$server:$cmd\n";
1.550 foxr 195: $answer=<$client>;
196: if (!$answer) { $answer="con_lost"; }
197: chomp($answer);
198: } else {
199: $answer = 'con_lost'; # Failed connection.
200: }
1.1 albertel 201: return $answer;
202: }
203:
204: sub reply {
205: my ($cmd,$server)=@_;
1.838 albertel 206: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 207: my $answer=subreply($cmd,$server);
1.65 www 208: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 209: &logthis("<font color=\"blue\">WARNING:".
1.12 www 210: " $cmd to $server returned $answer</font>");
211: }
1.1 albertel 212: return $answer;
213: }
214:
215: # ----------------------------------------------------------- Send USR1 to lonc
216:
217: sub reconlonc {
1.836 www 218: &logthis("Trying to reconnect lonc");
1.1 albertel 219: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 220: if (open(my $fh,"<$loncfile")) {
1.1 albertel 221: my $loncpid=<$fh>;
222: chomp($loncpid);
223: if (kill 0 => $loncpid) {
224: &logthis("lonc at pid $loncpid responding, sending USR1");
225: kill USR1 => $loncpid;
226: sleep 1;
1.836 www 227: } else {
1.12 www 228: &logthis(
1.672 albertel 229: "<font color=\"blue\">WARNING:".
1.12 www 230: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 231: }
232: } else {
1.836 www 233: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 234: }
235: }
236:
237: # ------------------------------------------------------ Critical communication
1.12 www 238:
1.1 albertel 239: sub critical {
240: my ($cmd,$server)=@_;
1.838 albertel 241: unless (&hostname($server)) {
1.672 albertel 242: &logthis("<font color=\"blue\">WARNING:".
1.89 www 243: " Critical message to unknown server ($server)</font>");
244: return 'no_such_host';
245: }
1.1 albertel 246: my $answer=reply($cmd,$server);
247: if ($answer eq 'con_lost') {
248: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 249: my $answer=reply($cmd,$server);
1.1 albertel 250: if ($answer eq 'con_lost') {
251: my $now=time;
252: my $middlename=$cmd;
1.5 www 253: $middlename=substr($middlename,0,16);
1.1 albertel 254: $middlename=~s/\W//g;
255: my $dfilename=
1.305 www 256: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
257: $dumpcount++;
1.1 albertel 258: {
1.448 albertel 259: my $dfh;
260: if (open($dfh,">$dfilename")) {
261: print $dfh "$cmd\n";
262: close($dfh);
263: }
1.1 albertel 264: }
265: sleep 2;
266: my $wcmd='';
267: {
1.448 albertel 268: my $dfh;
269: if (open($dfh,"<$dfilename")) {
270: $wcmd=<$dfh>;
271: close($dfh);
272: }
1.1 albertel 273: }
274: chomp($wcmd);
1.7 www 275: if ($wcmd eq $cmd) {
1.672 albertel 276: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 277: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 278: &logperm("D:$server:$cmd");
279: return 'con_delayed';
280: } else {
1.672 albertel 281: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 282: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 283: &logperm("F:$server:$cmd");
284: return 'con_failed';
285: }
286: }
287: }
288: return $answer;
1.405 albertel 289: }
290:
1.755 albertel 291: # ------------------------------------------- check if return value is an error
292:
293: sub error {
294: my ($result) = @_;
1.756 albertel 295: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 296: if ($2 == 2) { return undef; }
297: return $1;
298: }
299: return undef;
300: }
301:
1.783 albertel 302: sub convert_and_load_session_env {
303: my ($lonidsdir,$handle)=@_;
304: my @profile;
305: {
306: open(my $idf,"$lonidsdir/$handle.id");
307: flock($idf,LOCK_SH);
308: @profile=<$idf>;
309: close($idf);
310: }
311: my %temp_env;
312: foreach my $line (@profile) {
1.786 albertel 313: if ($line !~ m/=/) {
314: return 0;
315: }
1.783 albertel 316: chomp($line);
317: my ($envname,$envvalue)=split(/=/,$line,2);
318: $temp_env{&unescape($envname)} = &unescape($envvalue);
319: }
320: unlink("$lonidsdir/$handle.id");
321: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
322: 0640)) {
323: %disk_env = %temp_env;
324: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
325: untie(%disk_env);
326: }
1.786 albertel 327: return 1;
1.783 albertel 328: }
329:
1.374 www 330: # ------------------------------------------- Transfer profile into environment
1.780 albertel 331: my $env_loaded;
332: sub transfer_profile_to_env {
1.788 albertel 333: my ($lonidsdir,$handle,$force_transfer) = @_;
334: if (!$force_transfer && $env_loaded) { return; }
1.374 www 335:
1.720 albertel 336: if (!defined($lonidsdir)) {
337: $lonidsdir = $perlvar{'lonIDsDir'};
338: }
339: if (!defined($handle)) {
340: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
341: }
342:
1.786 albertel 343: my $convert;
344: {
345: open(my $idf,"$lonidsdir/$handle.id");
346: flock($idf,LOCK_SH);
347: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
348: &GDBM_READER(),0640)) {
349: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
350: untie(%disk_env);
351: } else {
352: $convert = 1;
353: }
354: }
355: if ($convert) {
356: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
357: &logthis("Failed to load session, or convert session.");
358: }
1.374 www 359: }
1.783 albertel 360:
1.786 albertel 361: my %remove;
1.783 albertel 362: while ( my $envname = each(%env) ) {
1.433 matthew 363: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
364: if ($time < time-300) {
1.783 albertel 365: $remove{$key}++;
1.433 matthew 366: }
367: }
368: }
1.783 albertel 369:
1.619 albertel 370: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 371: $env_loaded=1;
1.783 albertel 372: foreach my $expired_key (keys(%remove)) {
1.433 matthew 373: &delenv($expired_key);
1.374 www 374: }
1.1 albertel 375: }
376:
1.830 albertel 377: sub timed_flock {
378: my ($file,$lock_type) = @_;
379: my $failed=0;
380: eval {
381: local $SIG{__DIE__}='DEFAULT';
382: local $SIG{ALRM}=sub {
383: $failed=1;
384: die("failed lock");
385: };
386: alarm(13);
387: flock($file,$lock_type);
388: alarm(0);
389: };
390: if ($failed) {
391: return undef;
392: } else {
393: return 1;
394: }
395: }
396:
1.5 www 397: # ---------------------------------------------------------- Append Environment
398:
399: sub appenv {
1.6 www 400: my %newenv=@_;
1.692 albertel 401: foreach my $key (keys(%newenv)) {
402: if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672 albertel 403: &logthis("<font color=\"blue\">WARNING: ".
1.692 albertel 404: "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151 www 405: .'</font>');
1.692 albertel 406: delete($newenv{$key});
1.35 www 407: } else {
1.692 albertel 408: $env{$key}=$newenv{$key};
1.35 www 409: }
1.191 harris41 410: }
1.830 albertel 411: open(my $env_file,$env{'user.environment'});
412: if (&timed_flock($env_file,LOCK_EX)
413: &&
414: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
415: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 416: while (my ($key,$value) = each(%newenv)) {
417: $disk_env{$key} = $value;
1.448 albertel 418: }
1.783 albertel 419: untie(%disk_env);
1.56 www 420: }
421: return 'ok';
422: }
423: # ----------------------------------------------------- Delete from Environment
424:
425: sub delenv {
426: my $delthis=shift;
427: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 428: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 429: "Attempt to delete from environment ".$delthis);
430: return 'error';
431: }
1.830 albertel 432: open(my $env_file,$env{'user.environment'});
433: if (&timed_flock($env_file,LOCK_EX)
434: &&
435: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
436: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 437: foreach my $key (keys(%disk_env)) {
438: if ($key=~/^$delthis/) {
1.619 albertel 439: delete($env{$key});
1.783 albertel 440: delete($disk_env{$key});
1.473 matthew 441: }
1.448 albertel 442: }
1.783 albertel 443: untie(%disk_env);
1.5 www 444: }
445: return 'ok';
1.369 albertel 446: }
447:
1.790 albertel 448: sub get_env_multiple {
449: my ($name) = @_;
450: my @values;
451: if (defined($env{$name})) {
452: # exists is it an array
453: if (ref($env{$name})) {
454: @values=@{ $env{$name} };
455: } else {
456: $values[0]=$env{$name};
457: }
458: }
459: return(@values);
460: }
461:
1.369 albertel 462: # ------------------------------------------ Find out current server userload
463: # there is a copy in lond
464: sub userload {
465: my $numusers=0;
466: {
467: opendir(LONIDS,$perlvar{'lonIDsDir'});
468: my $filename;
469: my $curtime=time;
470: while ($filename=readdir(LONIDS)) {
471: if ($filename eq '.' || $filename eq '..') {next;}
1.404 albertel 472: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 473: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 474: }
475: closedir(LONIDS);
476: }
477: my $userloadpercent=0;
478: my $maxuserload=$perlvar{'lonUserLoadLim'};
479: if ($maxuserload) {
1.371 albertel 480: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 481: }
1.372 albertel 482: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 483: return $userloadpercent;
1.283 www 484: }
485:
486: # ------------------------------------------ Fight off request when overloaded
487:
488: sub overloaderror {
489: my ($r,$checkserver)=@_;
490: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
491: my $loadavg;
492: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 493: open(my $loadfile,'/proc/loadavg');
1.283 www 494: $loadavg=<$loadfile>;
495: $loadavg =~ s/\s.*//g;
1.285 matthew 496: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 497: close($loadfile);
1.283 www 498: } else {
499: $loadavg=&reply('load',$checkserver);
500: }
1.285 matthew 501: my $overload=$loadavg-100;
1.283 www 502: if ($overload>0) {
1.285 matthew 503: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 504: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 505: return 413;
1.283 www 506: }
507: return '';
1.5 www 508: }
1.1 albertel 509:
510: # ------------------------------ Find server with least workload from spare.tab
1.11 www 511:
1.1 albertel 512: sub spareserver {
1.670 albertel 513: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 514: my $spare_server;
1.370 albertel 515: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 516: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
517: : $userloadpercent;
518:
519: foreach my $try_server (@{ $spareid{'primary'} }) {
520: ($spare_server, $lowest_load) =
521: &compare_server_load($try_server, $spare_server, $lowest_load);
522: }
523:
524: my $found_server = ($spare_server ne '' && $lowest_load < 100);
525:
526: if (!$found_server) {
527: foreach my $try_server (@{ $spareid{'default'} }) {
528: ($spare_server, $lowest_load) =
529: &compare_server_load($try_server, $spare_server, $lowest_load);
530: }
531: }
532:
533: if (!$want_server_name) {
1.838 albertel 534: $spare_server="http://".&hostname($spare_server);
1.784 albertel 535: }
536: return $spare_server;
537: }
538:
539: sub compare_server_load {
540: my ($try_server, $spare_server, $lowest_load) = @_;
541:
542: my $loadans = &reply('load', $try_server);
543: my $userloadans = &reply('userload',$try_server);
544:
545: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
546: next; #didn't get a number from the server
547: }
548:
549: my $load;
550: if ($loadans =~ /\d/) {
551: if ($userloadans =~ /\d/) {
552: #both are numbers, pick the bigger one
553: $load = ($loadans > $userloadans) ? $loadans
554: : $userloadans;
1.411 albertel 555: } else {
1.784 albertel 556: $load = $loadans;
1.411 albertel 557: }
1.784 albertel 558: } else {
559: $load = $userloadans;
560: }
561:
562: if (($load =~ /\d/) && ($load < $lowest_load)) {
563: $spare_server = $try_server;
564: $lowest_load = $load;
1.370 albertel 565: }
1.784 albertel 566: return ($spare_server,$lowest_load);
1.202 matthew 567: }
568: # --------------------------------------------- Try to change a user's password
569:
570: sub changepass {
1.799 raeburn 571: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 572: $currentpass = &escape($currentpass);
573: $newpass = &escape($newpass);
1.799 raeburn 574: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202 matthew 575: $server);
576: if (! $answer) {
577: &logthis("No reply on password change request to $server ".
578: "by $uname in domain $udom.");
579: } elsif ($answer =~ "^ok") {
580: &logthis("$uname in $udom successfully changed their password ".
581: "on $server.");
582: } elsif ($answer =~ "^pwchange_failure") {
583: &logthis("$uname in $udom was unable to change their password ".
584: "on $server. The action was blocked by either lcpasswd ".
585: "or pwchange");
586: } elsif ($answer =~ "^non_authorized") {
587: &logthis("$uname in $udom did not get their password correct when ".
588: "attempting to change it on $server.");
589: } elsif ($answer =~ "^auth_mode_error") {
590: &logthis("$uname in $udom attempted to change their password despite ".
591: "not being locally or internally authenticated on $server.");
592: } elsif ($answer =~ "^unknown_user") {
593: &logthis("$uname in $udom attempted to change their password ".
594: "on $server but were unable to because $server is not ".
595: "their home server.");
596: } elsif ($answer =~ "^refused") {
597: &logthis("$server refused to change $uname in $udom password because ".
598: "it was sent an unencrypted request to change the password.");
599: }
600: return $answer;
1.1 albertel 601: }
602:
1.169 harris41 603: # ----------------------- Try to determine user's current authentication scheme
604:
605: sub queryauthenticate {
606: my ($uname,$udom)=@_;
1.456 albertel 607: my $uhome=&homeserver($uname,$udom);
608: if (!$uhome) {
609: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
610: return 'no_host';
611: }
612: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
613: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
614: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 615: }
1.456 albertel 616: return $answer;
1.169 harris41 617: }
618:
1.1 albertel 619: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 620:
1.1 albertel 621: sub authenticate {
622: my ($uname,$upass,$udom)=@_;
1.807 albertel 623: $upass=&escape($upass);
624: $uname= &LONCAPA::clean_username($uname);
1.836 www 625: my $uhome=&homeserver($uname,$udom,1);
626: if ((!$uhome) || ($uhome eq 'no_host')) {
627: # Maybe the machine was offline and only re-appeared again recently?
628: &reconlonc();
629: # One more
630: my $uhome=&homeserver($uname,$udom,1);
631: if ((!$uhome) || ($uhome eq 'no_host')) {
632: &logthis("User $uname at $udom is unknown in authenticate");
633: }
1.471 albertel 634: return 'no_host';
1.1 albertel 635: }
1.471 albertel 636: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
637: if ($answer eq 'authorized') {
638: &logthis("User $uname at $udom authorized by $uhome");
639: return $uhome;
640: }
641: if ($answer eq 'non_authorized') {
642: &logthis("User $uname at $udom rejected by $uhome");
643: return 'no_host';
1.9 www 644: }
1.471 albertel 645: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 646: return 'no_host';
647: }
648:
649: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 650:
1.599 albertel 651: my %homecache;
1.1 albertel 652: sub homeserver {
1.230 stredwic 653: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 654: my $index="$uname:$udom";
1.426 albertel 655:
1.599 albertel 656: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 657:
658: my %servers = &get_servers($udom,'library');
659: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 660: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 661: exists($badServerCache{$tryserver}));
1.841 albertel 662:
663: my $answer=reply("home:$udom:$uname",$tryserver);
664: if ($answer eq 'found') {
665: delete($badServerCache{$tryserver});
666: return $homecache{$index}=$tryserver;
667: } elsif ($answer eq 'no_host') {
668: $badServerCache{$tryserver}=1;
669: }
1.1 albertel 670: }
671: return 'no_host';
1.70 www 672: }
673:
1.860 raeburn 674: # ---------------------- Get domain configuration for a domain
675: sub get_domainconf {
676: my ($udom) = @_;
677: my $cachetime=1800;
678: my ($result,$cached)=&is_cached_new('domainconfig',$udom);
679: if (defined($cached)) { return %{$result}; }
680:
681: if ($udom eq '') {
682: $udom = &Apache::loncommon::determinedomain();
683: }
684: my %domconfig = &get_dom('configuration',['login','rolecolors'],$udom);
685: my %designhash;
686: if (keys(%domconfig) > 0) {
687: if (ref($domconfig{'login'}) eq 'HASH') {
688: foreach my $key (keys(%{$domconfig{'login'}})) {
689: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
690: }
691: }
692: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
693: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
694: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
695: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
696: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
697: }
698: }
699: }
700: }
701: } else {
702: my $designdir=$perlvar{'lonTabDir'}.'/lonDomColors';
703: my $designfile = $designdir.'/'.$udom.'.tab';
704: if (-e $designfile) {
705: if ( open (my $fh,"<$designfile") ) {
706: while (my $line = <$fh>) {
707: next if ($line =~ /^\#/);
708: chomp($line);
709: my ($key,$val)=(split(/\=/,$line));
710: if ($val) { $designhash{$udom.'.'.$key}=$val; }
711: }
712: close($fh);
713: }
714: }
715: if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
716: $designhash{$udom.'.login.domlogo'} =
717: &lonhttpdurl("/adm/lonDomLogos/$udom.gif");
718: }
719: }
720: &do_cache_new('domainconfig',$udom,\%designhash,$cachetime);
721: return %designhash;
722: }
723:
724: sub devalidate_domconfig_cache {
725: my ($udom)=@_;
726: &devalidate_cache_new('domainconfig',$udom);
727: }
728:
1.70 www 729: # ------------------------------------- Find the usernames behind a list of IDs
730:
731: sub idget {
732: my ($udom,@ids)=@_;
733: my %returnhash=();
734:
1.841 albertel 735: my %servers = &get_servers($udom,'library');
736: foreach my $tryserver (keys(%servers)) {
737: my $idlist=join('&',@ids);
738: $idlist=~tr/A-Z/a-z/;
739: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
740: my @answer=();
741: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
742: @answer=split(/\&/,$reply);
743: } ;
744: my $i;
745: for ($i=0;$i<=$#ids;$i++) {
746: if ($answer[$i]) {
747: $returnhash{$ids[$i]}=$answer[$i];
748: }
749: }
750: }
1.70 www 751: return %returnhash;
752: }
753:
754: # ------------------------------------- Find the IDs behind a list of usernames
755:
756: sub idrget {
757: my ($udom,@unames)=@_;
758: my %returnhash=();
1.800 albertel 759: foreach my $uname (@unames) {
760: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 761: }
1.70 www 762: return %returnhash;
763: }
764:
765: # ------------------------------- Store away a list of names and associated IDs
766:
767: sub idput {
768: my ($udom,%ids)=@_;
769: my %servers=();
1.800 albertel 770: foreach my $uname (keys(%ids)) {
771: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
772: my $uhom=&homeserver($uname,$udom);
1.70 www 773: if ($uhom ne 'no_host') {
1.800 albertel 774: my $id=&escape($ids{$uname});
1.70 www 775: $id=~tr/A-Z/a-z/;
1.800 albertel 776: my $esc_unam=&escape($uname);
1.70 www 777: if ($servers{$uhom}) {
1.800 albertel 778: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 779: } else {
1.800 albertel 780: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 781: }
782: }
1.191 harris41 783: }
1.800 albertel 784: foreach my $server (keys(%servers)) {
785: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 786: }
1.344 www 787: }
788:
1.806 raeburn 789: # ------------------------------------------- get items from domain db files
790:
791: sub get_dom {
1.860 raeburn 792: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 793: my $items='';
794: foreach my $item (@$storearr) {
795: $items.=&escape($item).'&';
796: }
797: $items=~s/\&$//;
1.860 raeburn 798: if (!$udom) {
799: $udom=$env{'user.domain'};
800: if (defined(&domain($udom,'primary'))) {
801: $uhome=&domain($udom,'primary');
802: } else {
803: $uhome eq '';
804: }
805: } else {
806: if (!$uhome) {
807: if (defined(&domain($udom,'primary'))) {
808: $uhome=&domain($udom,'primary');
809: }
810: }
811: }
812: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 813: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
814: my @pairs=split(/\&/,$rep);
815: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
816: return @pairs;
817: }
818: my %returnhash=();
819: my $i=0;
820: foreach my $item (@$storearr) {
821: $returnhash{$item}=&thaw_unescape($pairs[$i]);
822: $i++;
823: }
824: return %returnhash;
825: } else {
1.860 raeburn 826: &logthis("get_dom failed - no homeserver and/or domain");
1.806 raeburn 827: }
828: }
829:
830: # -------------------------------------------- put items in domain db files
831:
832: sub put_dom {
1.860 raeburn 833: my ($namespace,$storehash,$udom,$uhome)=@_;
834: if (!$udom) {
835: $udom=$env{'user.domain'};
836: if (defined(&domain($udom,'primary'))) {
837: $uhome=&domain($udom,'primary');
838: } else {
839: $uhome eq '';
840: }
841: } else {
842: if (!$uhome) {
843: if (defined(&domain($udom,'primary'))) {
844: $uhome=&domain($udom,'primary');
845: }
846: }
847: }
848: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 849: my $items='';
850: foreach my $item (keys(%$storehash)) {
851: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
852: }
853: $items=~s/\&$//;
854: return &reply("putdom:$udom:$namespace:$items",$uhome);
855: } else {
1.860 raeburn 856: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 857: }
858: }
859:
1.837 raeburn 860: sub retrieve_inst_usertypes {
861: my ($udom) = @_;
862: my (%returnhash,@order);
1.846 albertel 863: if (defined(&domain($udom,'primary'))) {
864: my $uhome=&domain($udom,'primary');
1.837 raeburn 865: my $rep=&reply("inst_usertypes:$udom",$uhome);
866: my ($hashitems,$orderitems) = split(/:/,$rep);
867: my @pairs=split(/\&/,$hashitems);
868: foreach my $item (@pairs) {
869: my ($key,$value)=split(/=/,$item,2);
870: $key = &unescape($key);
871: next if ($key =~ /^error: 2 /);
872: $returnhash{$key}=&thaw_unescape($value);
873: }
874: my @esc_order = split(/\&/,$orderitems);
875: foreach my $item (@esc_order) {
876: push(@order,&unescape($item));
877: }
878: } else {
879: &logthis("get_dom failed - no primary domain server for $udom");
880: }
881: return (\%returnhash,\@order);
882: }
883:
1.344 www 884: # --------------------------------------------------- Assign a key to a student
885:
886: sub assign_access_key {
1.364 www 887: #
888: # a valid key looks like uname:udom#comments
889: # comments are being appended
890: #
1.498 www 891: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
892: $kdom=
1.620 albertel 893: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 894: $knum=
1.620 albertel 895: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 896: $cdom=
1.620 albertel 897: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 898: $cnum=
1.620 albertel 899: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
900: $udom=$env{'user.name'} unless (defined($udom));
901: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 902: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 903: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 904: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 905: # assigned to this person
906: # - this should not happen,
1.345 www 907: # unless something went wrong
908: # the first time around
909: # ready to assign
1.364 www 910: $logentry=$1.'; '.$logentry;
1.496 www 911: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 912: $kdom,$knum) eq 'ok') {
1.345 www 913: # key now belongs to user
1.346 www 914: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 915: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
916: &appenv('environment.'.$envkey => $ckey);
917: return 'ok';
918: } else {
919: return
920: 'error: Count not permanently assign key, will need to be re-entered later.';
921: }
922: } else {
923: return 'error: Could not assign key, try again later.';
924: }
1.364 www 925: } elsif (!$existing{$ckey}) {
1.345 www 926: # the key does not exist
927: return 'error: The key does not exist';
928: } else {
929: # the key is somebody else's
930: return 'error: The key is already in use';
931: }
1.344 www 932: }
933:
1.364 www 934: # ------------------------------------------ put an additional comment on a key
935:
936: sub comment_access_key {
937: #
938: # a valid key looks like uname:udom#comments
939: # comments are being appended
940: #
941: my ($ckey,$cdom,$cnum,$logentry)=@_;
942: $cdom=
1.620 albertel 943: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 944: $cnum=
1.620 albertel 945: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 946: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
947: if ($existing{$ckey}) {
948: $existing{$ckey}.='; '.$logentry;
949: # ready to assign
1.367 www 950: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 951: $cdom,$cnum) eq 'ok') {
952: return 'ok';
953: } else {
954: return 'error: Count not store comment.';
955: }
956: } else {
957: # the key does not exist
958: return 'error: The key does not exist';
959: }
960: }
961:
1.344 www 962: # ------------------------------------------------------ Generate a set of keys
963:
964: sub generate_access_keys {
1.364 www 965: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 966: $cdom=
1.620 albertel 967: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 968: $cnum=
1.620 albertel 969: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 970: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 971: unless (($cdom) && ($cnum)) { return 0; }
972: if ($number>10000) { return 0; }
973: sleep(2); # make sure don't get same seed twice
974: srand(time()^($$+($$<<15))); # from "Programming Perl"
975: my $total=0;
976: for (my $i=1;$i<=$number;$i++) {
977: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
978: sprintf("%lx",int(100000*rand)).'-'.
979: sprintf("%lx",int(100000*rand));
980: $newkey=~s/1/g/g; # folks mix up 1 and l
981: $newkey=~s/0/h/g; # and also 0 and O
982: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
983: if ($existing{$newkey}) {
984: $i--;
985: } else {
1.364 www 986: if (&put('accesskeys',
987: { $newkey => '# generated '.localtime().
1.620 albertel 988: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 989: '; '.$logentry },
990: $cdom,$cnum) eq 'ok') {
1.344 www 991: $total++;
992: }
993: }
994: }
1.620 albertel 995: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 996: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
997: return $total;
998: }
999:
1000: # ------------------------------------------------------- Validate an accesskey
1001:
1002: sub validate_access_key {
1003: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1004: $cdom=
1.620 albertel 1005: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1006: $cnum=
1.620 albertel 1007: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1008: $udom=$env{'user.domain'} unless (defined($udom));
1009: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1010: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1011: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1012: }
1013:
1014: # ------------------------------------- Find the section of student in a course
1.652 albertel 1015: sub devalidate_getsection_cache {
1016: my ($udom,$unam,$courseid)=@_;
1017: my $hashid="$udom:$unam:$courseid";
1018: &devalidate_cache_new('getsection',$hashid);
1019: }
1.298 matthew 1020:
1.815 albertel 1021: sub courseid_to_courseurl {
1022: my ($courseid) = @_;
1023: #already url style courseid
1024: return $courseid if ($courseid =~ m{^/});
1025:
1026: if (exists($env{'course.'.$courseid.'.num'})) {
1027: my $cnum = $env{'course.'.$courseid.'.num'};
1028: my $cdom = $env{'course.'.$courseid.'.domain'};
1029: return "/$cdom/$cnum";
1030: }
1031:
1032: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1033: if (exists($courseinfo{'num'})) {
1034: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1035: }
1036:
1037: return undef;
1038: }
1039:
1.298 matthew 1040: sub getsection {
1041: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1042: my $cachetime=1800;
1.551 albertel 1043:
1044: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1045: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1046: if (defined($cached)) { return $result; }
1047:
1.298 matthew 1048: my %Pending;
1049: my %Expired;
1050: #
1051: # Each role can either have not started yet (pending), be active,
1052: # or have expired.
1053: #
1054: # If there is an active role, we are done.
1055: #
1056: # If there is more than one role which has not started yet,
1057: # choose the one which will start sooner
1058: # If there is one role which has not started yet, return it.
1059: #
1060: # If there is more than one expired role, choose the one which ended last.
1061: # If there is a role which has expired, return it.
1062: #
1.815 albertel 1063: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1064: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1065: foreach my $key (keys(%roleshash)) {
1.479 albertel 1066: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1067: my $section=$1;
1068: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1069: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1070: my $now=time;
1.548 albertel 1071: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1072: $Expired{$end}=$section;
1073: next;
1074: }
1.548 albertel 1075: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1076: $Pending{$start}=$section;
1077: next;
1078: }
1.599 albertel 1079: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1080: }
1081: #
1082: # Presumedly there will be few matching roles from the above
1083: # loop and the sorting time will be negligible.
1084: if (scalar(keys(%Pending))) {
1085: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1086: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1087: }
1088: if (scalar(keys(%Expired))) {
1089: my @sorted = sort {$a <=> $b} keys(%Expired);
1090: my $time = pop(@sorted);
1.599 albertel 1091: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1092: }
1.599 albertel 1093: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1094: }
1.70 www 1095:
1.599 albertel 1096: sub save_cache {
1097: &purge_remembered();
1.722 albertel 1098: #&Apache::loncommon::validate_page();
1.620 albertel 1099: undef(%env);
1.780 albertel 1100: undef($env_loaded);
1.599 albertel 1101: }
1.452 albertel 1102:
1.599 albertel 1103: my $to_remember=-1;
1104: my %remembered;
1105: my %accessed;
1106: my $kicks=0;
1107: my $hits=0;
1.849 albertel 1108: sub make_key {
1109: my ($name,$id) = @_;
1110: if (length($id) > 200) { $id=length($id).':'.&Digest::MD5::md5_hex($id); }
1111: return &escape($name.':'.$id);
1112: }
1113:
1.599 albertel 1114: sub devalidate_cache_new {
1115: my ($name,$id,$debug) = @_;
1116: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1117: $id=&make_key($name,$id);
1.599 albertel 1118: $memcache->delete($id);
1119: delete($remembered{$id});
1120: delete($accessed{$id});
1121: }
1122:
1123: sub is_cached_new {
1124: my ($name,$id,$debug) = @_;
1.849 albertel 1125: $id=&make_key($name,$id);
1.599 albertel 1126: if (exists($remembered{$id})) {
1127: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1128: $accessed{$id}=[&gettimeofday()];
1129: $hits++;
1130: return ($remembered{$id},1);
1131: }
1132: my $value = $memcache->get($id);
1133: if (!(defined($value))) {
1134: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1135: return (undef,undef);
1.416 albertel 1136: }
1.599 albertel 1137: if ($value eq '__undef__') {
1138: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1139: $value=undef;
1140: }
1141: &make_room($id,$value,$debug);
1142: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1143: return ($value,1);
1144: }
1145:
1146: sub do_cache_new {
1147: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1148: $id=&make_key($name,$id);
1.599 albertel 1149: my $setvalue=$value;
1150: if (!defined($setvalue)) {
1151: $setvalue='__undef__';
1152: }
1.623 albertel 1153: if (!defined($time) ) {
1154: $time=600;
1155: }
1.599 albertel 1156: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600 albertel 1157: $memcache->set($id,$setvalue,$time);
1158: # need to make a copy of $value
1159: #&make_room($id,$value,$debug);
1.599 albertel 1160: return $value;
1161: }
1162:
1163: sub make_room {
1164: my ($id,$value,$debug)=@_;
1165: $remembered{$id}=$value;
1166: if ($to_remember<0) { return; }
1167: $accessed{$id}=[&gettimeofday()];
1168: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1169: my $to_kick;
1170: my $max_time=0;
1171: foreach my $other (keys(%accessed)) {
1172: if (&tv_interval($accessed{$other}) > $max_time) {
1173: $to_kick=$other;
1174: $max_time=&tv_interval($accessed{$other});
1175: }
1176: }
1177: delete($remembered{$to_kick});
1178: delete($accessed{$to_kick});
1179: $kicks++;
1180: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1181: return;
1182: }
1183:
1.599 albertel 1184: sub purge_remembered {
1.604 albertel 1185: #&logthis("Tossing ".scalar(keys(%remembered)));
1186: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1187: undef(%remembered);
1188: undef(%accessed);
1.428 albertel 1189: }
1.70 www 1190: # ------------------------------------- Read an entry from a user's environment
1191:
1192: sub userenvironment {
1193: my ($udom,$unam,@what)=@_;
1194: my %returnhash=();
1195: my @answer=split(/\&/,
1196: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
1197: &homeserver($unam,$udom)));
1198: my $i;
1199: for ($i=0;$i<=$#what;$i++) {
1200: $returnhash{$what[$i]}=&unescape($answer[$i]);
1201: }
1202: return %returnhash;
1.1 albertel 1203: }
1204:
1.617 albertel 1205: # ---------------------------------------------------------- Get a studentphoto
1206: sub studentphoto {
1207: my ($udom,$unam,$ext) = @_;
1208: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1209: if (defined($env{'request.course.id'})) {
1.708 raeburn 1210: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1211: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1212: return(&retrievestudentphoto($udom,$unam,$ext));
1213: } else {
1214: my ($result,$perm_reqd)=
1.707 albertel 1215: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1216: if ($result eq 'ok') {
1217: if (!($perm_reqd eq 'yes')) {
1218: return(&retrievestudentphoto($udom,$unam,$ext));
1219: }
1220: }
1221: }
1222: }
1223: } else {
1224: my ($result,$perm_reqd) =
1.707 albertel 1225: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1226: if ($result eq 'ok') {
1227: if (!($perm_reqd eq 'yes')) {
1228: return(&retrievestudentphoto($udom,$unam,$ext));
1229: }
1230: }
1231: }
1232: return '/adm/lonKaputt/lonlogo_broken.gif';
1233: }
1234:
1235: sub retrievestudentphoto {
1236: my ($udom,$unam,$ext,$type) = @_;
1237: my $home=&Apache::lonnet::homeserver($unam,$udom);
1238: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1239: if ($ret eq 'ok') {
1240: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1241: if ($type eq 'thumbnail') {
1242: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1243: }
1244: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1245: return $tokenurl;
1246: } else {
1247: if ($type eq 'thumbnail') {
1248: return '/adm/lonKaputt/genericstudent_tn.gif';
1249: } else {
1250: return '/adm/lonKaputt/lonlogo_broken.gif';
1251: }
1.617 albertel 1252: }
1253: }
1254:
1.263 www 1255: # -------------------------------------------------------------------- New chat
1256:
1257: sub chatsend {
1.724 raeburn 1258: my ($newentry,$anon,$group)=@_;
1.620 albertel 1259: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1260: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1261: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1262: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1263: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1264: &escape($newentry)).':'.$group,$chome);
1.292 www 1265: }
1266:
1267: # ------------------------------------------ Find current version of a resource
1268:
1269: sub getversion {
1270: my $fname=&clutter(shift);
1271: unless ($fname=~/^\/res\//) { return -1; }
1272: return ¤tversion(&filelocation('',$fname));
1273: }
1274:
1275: sub currentversion {
1276: my $fname=shift;
1.599 albertel 1277: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1278: if (defined($cached)) { return $result; }
1.292 www 1279: my $author=$fname;
1280: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1281: my ($udom,$uname)=split(/\//,$author);
1282: my $home=homeserver($uname,$udom);
1283: if ($home eq 'no_host') {
1284: return -1;
1285: }
1286: my $answer=reply("currentversion:$fname",$home);
1287: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1288: return -1;
1289: }
1.599 albertel 1290: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1291: }
1292:
1.1 albertel 1293: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1294:
1.1 albertel 1295: sub subscribe {
1296: my $fname=shift;
1.761 raeburn 1297: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1298: $fname=~s/[\n\r]//g;
1.1 albertel 1299: my $author=$fname;
1300: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1301: my ($udom,$uname)=split(/\//,$author);
1302: my $home=homeserver($uname,$udom);
1.335 albertel 1303: if ($home eq 'no_host') {
1304: return 'not_found';
1.1 albertel 1305: }
1306: my $answer=reply("sub:$fname",$home);
1.64 www 1307: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1308: $answer.=' by '.$home;
1309: }
1.1 albertel 1310: return $answer;
1311: }
1312:
1.8 www 1313: # -------------------------------------------------------------- Replicate file
1314:
1315: sub repcopy {
1316: my $filename=shift;
1.23 www 1317: $filename=~s/\/+/\//g;
1.607 raeburn 1318: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1319: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1320: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1321: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1322: return &repcopy_userfile($filename);
1323: }
1.532 albertel 1324: $filename=~s/[\n\r]//g;
1.8 www 1325: my $transname="$filename.in.transfer";
1.828 www 1326: # FIXME: this should flock
1.607 raeburn 1327: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1328: my $remoteurl=subscribe($filename);
1.64 www 1329: if ($remoteurl =~ /^con_lost by/) {
1330: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1331: return 'unavailable';
1.8 www 1332: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1333: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1334: return 'not_found';
1.64 www 1335: } elsif ($remoteurl =~ /^rejected by/) {
1336: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1337: return 'forbidden';
1.20 www 1338: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1339: return 'ok';
1.8 www 1340: } else {
1.290 www 1341: my $author=$filename;
1342: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1343: my ($udom,$uname)=split(/\//,$author);
1344: my $home=homeserver($uname,$udom);
1345: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1346: my @parts=split(/\//,$filename);
1347: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1348: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1349: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1350: return 'bad_request';
1.8 www 1351: }
1352: my $count;
1353: for ($count=5;$count<$#parts;$count++) {
1354: $path.="/$parts[$count]";
1355: if ((-e $path)!=1) {
1356: mkdir($path,0777);
1357: }
1358: }
1359: my $ua=new LWP::UserAgent;
1360: my $request=new HTTP::Request('GET',"$remoteurl");
1361: my $response=$ua->request($request,$transname);
1362: if ($response->is_error()) {
1363: unlink($transname);
1364: my $message=$response->status_line;
1.672 albertel 1365: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1366: ." LWP get: $message: $filename</font>");
1.607 raeburn 1367: return 'unavailable';
1.8 www 1368: } else {
1.16 www 1369: if ($remoteurl!~/\.meta$/) {
1370: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1371: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1372: if ($mresponse->is_error()) {
1373: unlink($filename.'.meta');
1374: &logthis(
1.672 albertel 1375: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1376: }
1377: }
1.8 www 1378: rename($transname,$filename);
1.607 raeburn 1379: return 'ok';
1.8 www 1380: }
1.290 www 1381: }
1.8 www 1382: }
1.330 www 1383: }
1384:
1385: # ------------------------------------------------ Get server side include body
1386: sub ssi_body {
1.381 albertel 1387: my ($filelink,%form)=@_;
1.606 matthew 1388: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1389: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1390: }
1.330 www 1391: my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381 albertel 1392: &ssi($filelink,%form));
1.778 albertel 1393: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1394: $output=~s/^.*?\<body[^\>]*\>//si;
1395: $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330 www 1396: return $output;
1.8 www 1397: }
1398:
1.15 www 1399: # --------------------------------------------------------- Server Side Include
1400:
1.782 albertel 1401: sub absolute_url {
1402: my ($host_name) = @_;
1403: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1404: if ($host_name eq '') {
1405: $host_name = $ENV{'SERVER_NAME'};
1406: }
1407: return $protocol.$host_name;
1408: }
1409:
1.15 www 1410: sub ssi {
1411:
1.23 www 1412: my ($fn,%form)=@_;
1.15 www 1413:
1414: my $ua=new LWP::UserAgent;
1.23 www 1415:
1416: my $request;
1.711 albertel 1417:
1418: $form{'no_update_last_known'}=1;
1419:
1.23 www 1420: if (%form) {
1.782 albertel 1421: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201 albertel 1422: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23 www 1423: } else {
1.782 albertel 1424: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1425: }
1426:
1.15 www 1427: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1428: my $response=$ua->request($request);
1429:
1.324 www 1430: return $response->content;
1431: }
1432:
1433: sub externalssi {
1434: my ($url)=@_;
1435: my $ua=new LWP::UserAgent;
1436: my $request=new HTTP::Request('GET',$url);
1437: my $response=$ua->request($request);
1.15 www 1438: return $response->content;
1439: }
1.254 www 1440:
1.492 albertel 1441: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1442:
1443: sub allowuploaded {
1444: my ($srcurl,$url)=@_;
1445: $url=&clutter(&declutter($url));
1446: my $dir=$url;
1447: $dir=~s/\/[^\/]+$//;
1448: my %httpref=();
1449: my $httpurl=&hreflocation('',$url);
1450: $httpref{'httpref.'.$httpurl}=$srcurl;
1451: &Apache::lonnet::appenv(%httpref);
1.254 www 1452: }
1.477 raeburn 1453:
1.478 albertel 1454: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1455: # input: action, courseID, current domain, intended
1.637 raeburn 1456: # path to file, source of file, instruction to parse file for objects,
1457: # ref to hash for embedded objects,
1458: # ref to hash for codebase of java objects.
1459: #
1.485 raeburn 1460: # output: url to file (if action was uploaddoc),
1461: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 1462: #
1.478 albertel 1463: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1464: # course.
1.477 raeburn 1465: #
1.478 albertel 1466: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1467: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1468: # course's home server.
1.477 raeburn 1469: #
1.478 albertel 1470: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1471: # be copied from $source (current location) to
1472: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1473: # and will then be copied to
1474: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1475: # course's home server.
1.485 raeburn 1476: #
1.481 raeburn 1477: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 1478: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 1479: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1480: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1481: # in course's home server.
1.637 raeburn 1482: #
1.477 raeburn 1483:
1484: sub process_coursefile {
1.638 albertel 1485: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 1486: my $fetchresult;
1.638 albertel 1487: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 1488: if ($action eq 'propagate') {
1.638 albertel 1489: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1490: $home);
1.481 raeburn 1491: } else {
1.477 raeburn 1492: my $fpath = '';
1493: my $fname = $file;
1.478 albertel 1494: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 1495: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 1496: my $filepath = &build_filepath($fpath);
1.481 raeburn 1497: if ($action eq 'copy') {
1498: if ($source eq '') {
1499: $fetchresult = 'no source file';
1500: return $fetchresult;
1501: } else {
1502: my $destination = $filepath.'/'.$fname;
1503: rename($source,$destination);
1504: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1505: $home);
1.481 raeburn 1506: }
1507: } elsif ($action eq 'uploaddoc') {
1508: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 1509: print $fh $env{'form.'.$source};
1.481 raeburn 1510: close($fh);
1.637 raeburn 1511: if ($parser eq 'parse') {
1512: my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
1513: unless ($parse_result eq 'ok') {
1514: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1515: }
1516: }
1.477 raeburn 1517: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1518: $home);
1.481 raeburn 1519: if ($fetchresult eq 'ok') {
1520: return '/uploaded/'.$fpath.'/'.$fname;
1521: } else {
1522: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1523: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 1524: return '/adm/notfound.html';
1525: }
1.477 raeburn 1526: }
1527: }
1.485 raeburn 1528: unless ( $fetchresult eq 'ok') {
1.477 raeburn 1529: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1530: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 1531: }
1532: return $fetchresult;
1533: }
1534:
1.637 raeburn 1535: sub build_filepath {
1536: my ($fpath) = @_;
1537: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1538: unless ($fpath eq '') {
1539: my @parts=split('/',$fpath);
1540: foreach my $part (@parts) {
1541: $filepath.= '/'.$part;
1542: if ((-e $filepath)!=1) {
1543: mkdir($filepath,0777);
1544: }
1545: }
1546: }
1547: return $filepath;
1548: }
1549:
1550: sub store_edited_file {
1.638 albertel 1551: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 1552: my $file = $primary_url;
1553: $file =~ s#^/uploaded/$docudom/$docuname/##;
1554: my $fpath = '';
1555: my $fname = $file;
1556: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1557: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1558: my $filepath = &build_filepath($fpath);
1559: open(my $fh,'>'.$filepath.'/'.$fname);
1560: print $fh $content;
1561: close($fh);
1.638 albertel 1562: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 1563: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1564: $home);
1.637 raeburn 1565: if ($$fetchresult eq 'ok') {
1566: return '/uploaded/'.$fpath.'/'.$fname;
1567: } else {
1.638 albertel 1568: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1569: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 1570: return '/adm/notfound.html';
1571: }
1572: }
1573:
1.531 albertel 1574: sub clean_filename {
1.831 albertel 1575: my ($fname,$args)=@_;
1.315 www 1576: # Replace Windows backslashes by forward slashes
1.257 www 1577: $fname=~s/\\/\//g;
1.831 albertel 1578: if (!$args->{'keep_path'}) {
1579: # Get rid of everything but the actual filename
1580: $fname=~s/^.*\/([^\/]+)$/$1/;
1581: }
1.315 www 1582: # Replace spaces by underscores
1583: $fname=~s/\s+/\_/g;
1584: # Replace all other weird characters by nothing
1.831 albertel 1585: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 1586: # Replace all .\d. sequences with _\d. so they no longer look like version
1587: # numbers
1588: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 1589: return $fname;
1590: }
1591:
1.608 albertel 1592: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 1593: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 1594: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 1595: # $coursedoc - if true up to the current course
1596: # if false
1597: # $subdir - directory in userfile to store the file into
1.858 raeburn 1598: # $parser - instruction to parse file for objects ($parser = parse)
1599: # $allfiles - reference to hash for embedded objects
1600: # $codebase - reference to hash for codebase of java objects
1601: # $desuname - username for permanent storage of uploaded file
1602: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 1603: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
1604: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858 raeburn 1605: #
1.686 albertel 1606: # output: url of file in userspace, or error: <message>
1607: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 1608:
1609:
1.531 albertel 1610: sub userfileupload {
1.860 raeburn 1611: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1612: $destudom,$thumbwidth,$thumbheight)=@_;
1.531 albertel 1613: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 1614: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 1615: $fname=&clean_filename($fname);
1.315 www 1616: # See if there is anything left
1.257 www 1617: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 1618: chop($env{'form.'.$formname});
1.523 raeburn 1619: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
1620: my $now = time;
1621: my $filepath = 'tmp/helprequests/'.$now;
1622: my @parts=split(/\//,$filepath);
1623: my $fullpath = $perlvar{'lonDaemons'};
1624: for (my $i=0;$i<@parts;$i++) {
1625: $fullpath .= '/'.$parts[$i];
1626: if ((-e $fullpath)!=1) {
1627: mkdir($fullpath,0777);
1628: }
1629: }
1630: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 1631: print $fh $env{'form.'.$formname};
1.523 raeburn 1632: close($fh);
1.741 raeburn 1633: return $fullpath.'/'.$fname;
1634: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
1635: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
1636: '_'.$env{'user.domain'}.'/pending';
1637: my @parts=split(/\//,$filepath);
1638: my $fullpath = $perlvar{'lonDaemons'};
1639: for (my $i=0;$i<@parts;$i++) {
1640: $fullpath .= '/'.$parts[$i];
1641: if ((-e $fullpath)!=1) {
1642: mkdir($fullpath,0777);
1643: }
1644: }
1645: open(my $fh,'>'.$fullpath.'/'.$fname);
1646: print $fh $env{'form.'.$formname};
1647: close($fh);
1648: return $fullpath.'/'.$fname;
1.523 raeburn 1649: }
1.719 banghart 1650:
1.258 www 1651: # Create the directory if not present
1.493 albertel 1652: $fname="$subdir/$fname";
1.259 www 1653: if ($coursedoc) {
1.638 albertel 1654: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1655: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 1656: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 1657: return &finishuserfileupload($docuname,$docudom,
1658: $formname,$fname,$parser,$allfiles,
1.860 raeburn 1659: $codebase,$thumbwidth,$thumbheight);
1.481 raeburn 1660: } else {
1.620 albertel 1661: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 1662: return &process_coursefile('uploaddoc',$docuname,$docudom,
1663: $fname,$formname,$parser,
1664: $allfiles,$codebase);
1.481 raeburn 1665: }
1.719 banghart 1666: } elsif (defined($destuname)) {
1667: my $docuname=$destuname;
1668: my $docudom=$destudom;
1.860 raeburn 1669: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
1670: $parser,$allfiles,$codebase,
1671: $thumbwidth,$thumbheight);
1.719 banghart 1672:
1.259 www 1673: } else {
1.638 albertel 1674: my $docuname=$env{'user.name'};
1675: my $docudom=$env{'user.domain'};
1.714 raeburn 1676: if (exists($env{'form.group'})) {
1677: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1678: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1679: }
1.860 raeburn 1680: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
1681: $parser,$allfiles,$codebase,
1682: $thumbwidth,$thumbheight);
1.259 www 1683: }
1.271 www 1684: }
1685:
1686: sub finishuserfileupload {
1.860 raeburn 1687: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1688: $thumbwidth,$thumbheight) = @_;
1.477 raeburn 1689: my $path=$docudom.'/'.$docuname.'/';
1.258 www 1690: my $filepath=$perlvar{'lonDocRoot'};
1.860 raeburn 1691: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 1692: $file=$fname;
1693: if ($fname=~m|/|) {
1694: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
1695: $path.=$fnamepath.'/';
1696: }
1.259 www 1697: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 1698: my $count;
1699: for ($count=4;$count<=$#parts;$count++) {
1700: $filepath.="/$parts[$count]";
1701: if ((-e $filepath)!=1) {
1702: mkdir($filepath,0777);
1703: }
1704: }
1705: # Save the file
1706: {
1.701 albertel 1707: if (!open(FH,'>'.$filepath.'/'.$file)) {
1708: &logthis('Failed to create '.$filepath.'/'.$file);
1709: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
1710: return '/adm/notfound.html';
1711: }
1712: if (!print FH ($env{'form.'.$formname})) {
1713: &logthis('Failed to write to '.$filepath.'/'.$file);
1714: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
1715: return '/adm/notfound.html';
1716: }
1.570 albertel 1717: close(FH);
1.258 www 1718: }
1.637 raeburn 1719: if ($parser eq 'parse') {
1.638 albertel 1720: my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
1721: $codebase);
1.637 raeburn 1722: unless ($parse_result eq 'ok') {
1.638 albertel 1723: &logthis('Failed to parse '.$filepath.$file.
1724: ' for embedded media: '.$parse_result);
1.637 raeburn 1725: }
1726: }
1.860 raeburn 1727: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
1728: my $input = $filepath.'/'.$file;
1729: my $output = $filepath.'/'.'tn-'.$file;
1730: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1731: system("convert -sample $thumbsize $input $output");
1732: if (-e $filepath.'/'.'tn-'.$file) {
1733: $fetchthumb = 1;
1734: }
1735: }
1.858 raeburn 1736:
1.259 www 1737: # Notify homeserver to grep it
1738: #
1.638 albertel 1739: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 1740: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 1741: if ($fetchresult eq 'ok') {
1.860 raeburn 1742: if ($fetchthumb) {
1743: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
1744: if ($thumbresult ne 'ok') {
1745: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
1746: $docuhome.': '.$thumbresult);
1747: }
1748: }
1.259 www 1749: #
1.258 www 1750: # Return the URL to it
1.494 albertel 1751: return '/uploaded/'.$path.$file;
1.263 www 1752: } else {
1.494 albertel 1753: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
1754: ': '.$fetchresult);
1.263 www 1755: return '/adm/notfound.html';
1.858 raeburn 1756: }
1.493 albertel 1757: }
1758:
1.637 raeburn 1759: sub extract_embedded_items {
1.648 raeburn 1760: my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637 raeburn 1761: my @state = ();
1762: my %javafiles = (
1763: codebase => '',
1764: code => '',
1765: archive => ''
1766: );
1767: my %mediafiles = (
1768: src => '',
1769: movie => '',
1770: );
1.648 raeburn 1771: my $p;
1772: if ($content) {
1773: $p = HTML::LCParser->new($content);
1774: } else {
1775: $p = HTML::LCParser->new($filepath.'/'.$file);
1776: }
1.641 albertel 1777: while (my $t=$p->get_token()) {
1.640 albertel 1778: if ($t->[0] eq 'S') {
1779: my ($tagname, $attr) = ($t->[1],$t->[2]);
1780: push (@state, $tagname);
1.648 raeburn 1781: if (lc($tagname) eq 'allow') {
1782: &add_filetype($allfiles,$attr->{'src'},'src');
1783: }
1.640 albertel 1784: if (lc($tagname) eq 'img') {
1785: &add_filetype($allfiles,$attr->{'src'},'src');
1786: }
1.645 raeburn 1787: if (lc($tagname) eq 'script') {
1788: if ($attr->{'archive'} =~ /\.jar$/i) {
1789: &add_filetype($allfiles,$attr->{'archive'},'archive');
1790: } else {
1791: &add_filetype($allfiles,$attr->{'src'},'src');
1792: }
1793: }
1794: if (lc($tagname) eq 'link') {
1795: if (lc($attr->{'rel'}) eq 'stylesheet') {
1796: &add_filetype($allfiles,$attr->{'href'},'href');
1797: }
1798: }
1.640 albertel 1799: if (lc($tagname) eq 'object' ||
1800: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
1801: foreach my $item (keys(%javafiles)) {
1802: $javafiles{$item} = '';
1803: }
1804: }
1805: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
1806: my $name = lc($attr->{'name'});
1807: foreach my $item (keys(%javafiles)) {
1808: if ($name eq $item) {
1809: $javafiles{$item} = $attr->{'value'};
1810: last;
1811: }
1812: }
1813: foreach my $item (keys(%mediafiles)) {
1814: if ($name eq $item) {
1815: &add_filetype($allfiles, $attr->{'value'}, 'value');
1816: last;
1817: }
1818: }
1819: }
1820: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
1821: foreach my $item (keys(%javafiles)) {
1822: if ($attr->{$item}) {
1823: $javafiles{$item} = $attr->{$item};
1824: last;
1825: }
1826: }
1827: foreach my $item (keys(%mediafiles)) {
1828: if ($attr->{$item}) {
1829: &add_filetype($allfiles,$attr->{$item},$item);
1830: last;
1831: }
1832: }
1833: }
1834: } elsif ($t->[0] eq 'E') {
1835: my ($tagname) = ($t->[1]);
1836: if ($javafiles{'codebase'} ne '') {
1837: $javafiles{'codebase'} .= '/';
1838: }
1839: if (lc($tagname) eq 'applet' ||
1840: lc($tagname) eq 'object' ||
1841: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
1842: ) {
1843: foreach my $item (keys(%javafiles)) {
1844: if ($item ne 'codebase' && $javafiles{$item} ne '') {
1845: my $file=$javafiles{'codebase'}.$javafiles{$item};
1846: &add_filetype($allfiles,$file,$item);
1847: }
1848: }
1849: }
1850: pop @state;
1851: }
1852: }
1.637 raeburn 1853: return 'ok';
1854: }
1855:
1.639 albertel 1856: sub add_filetype {
1857: my ($allfiles,$file,$type)=@_;
1858: if (exists($allfiles->{$file})) {
1859: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
1860: push(@{$allfiles->{$file}}, &escape($type));
1861: }
1862: } else {
1863: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 1864: }
1865: }
1866:
1.493 albertel 1867: sub removeuploadedurl {
1868: my ($url)=@_;
1869: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 1870: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 1871: }
1872:
1873: sub removeuserfile {
1874: my ($docuname,$docudom,$fname)=@_;
1875: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 1876: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1877: if ($result eq 'ok') {
1878: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
1879: my $metafile = $fname.'.meta';
1880: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 1881: my $url = "/uploaded/$docudom/$docuname/$fname";
1882: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 1883: my $sqlresult =
1.823 albertel 1884: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 1885: 'portfolio_metadata',$group,
1886: 'delete');
1.798 raeburn 1887: }
1888: }
1889: return $result;
1.257 www 1890: }
1.15 www 1891:
1.530 albertel 1892: sub mkdiruserfile {
1893: my ($docuname,$docudom,$dir)=@_;
1894: my $home=&homeserver($docuname,$docudom);
1895: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
1896: }
1897:
1.531 albertel 1898: sub renameuserfile {
1899: my ($docuname,$docudom,$old,$new)=@_;
1900: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 1901: my $result = &reply("renameuserfile:$docudom:$docuname:".
1902: &escape("$old").':'.&escape("$new"),$home);
1903: if ($result eq 'ok') {
1904: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
1905: my $oldmeta = $old.'.meta';
1906: my $newmeta = $new.'.meta';
1907: my $metaresult =
1908: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 1909: my $url = "/uploaded/$docudom/$docuname/$old";
1910: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 1911: my $sqlresult =
1.823 albertel 1912: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 1913: 'portfolio_metadata',$group,
1914: 'delete');
1.798 raeburn 1915: }
1916: }
1917: return $result;
1.531 albertel 1918: }
1919:
1.14 www 1920: # ------------------------------------------------------------------------- Log
1921:
1922: sub log {
1923: my ($dom,$nam,$hom,$what)=@_;
1.47 www 1924: return critical("log:$dom:$nam:$what",$hom);
1.157 www 1925: }
1926:
1927: # ------------------------------------------------------------------ Course Log
1.352 www 1928: #
1929: # This routine flushes several buffers of non-mission-critical nature
1930: #
1.157 www 1931:
1932: sub flushcourselogs {
1.352 www 1933: &logthis('Flushing log buffers');
1934: #
1935: # course logs
1936: # This is a log of all transactions in a course, which can be used
1937: # for data mining purposes
1938: #
1939: # It also collects the courseid database, which lists last transaction
1940: # times and course titles for all courseids
1941: #
1942: my %courseidbuffer=();
1.800 albertel 1943: foreach my $crsid (keys %courselogs) {
1.352 www 1944: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 1945: &escape($courselogs{$crsid}),
1946: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 1947: delete $courselogs{$crsid};
1948: } else {
1949: &logthis('Failed to flush log buffer for '.$crsid);
1950: if (length($courselogs{$crsid})>40000) {
1.672 albertel 1951: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 1952: " exceeded maximum size, deleting.</font>");
1953: delete $courselogs{$crsid};
1954: }
1.352 www 1955: }
1956: if ($courseidbuffer{$coursehombuf{$crsid}}) {
1957: $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516 raeburn 1958: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741 raeburn 1959: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352 www 1960: } else {
1961: $courseidbuffer{$coursehombuf{$crsid}}=
1.516 raeburn 1962: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741 raeburn 1963: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571 raeburn 1964: }
1.191 harris41 1965: }
1.352 www 1966: #
1967: # Write course id database (reverse lookup) to homeserver of courses
1968: # Is used in pickcourse
1969: #
1.840 albertel 1970: foreach my $crs_home (keys(%courseidbuffer)) {
1.844 albertel 1971: &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840 albertel 1972: $crs_home);
1.352 www 1973: }
1974: #
1975: # File accesses
1976: # Writes to the dynamic metadata of resources to get hit counts, etc.
1977: #
1.449 matthew 1978: foreach my $entry (keys(%accesshash)) {
1.458 matthew 1979: if ($entry =~ /___count$/) {
1980: my ($dom,$name);
1.807 albertel 1981: ($dom,$name,undef)=
1.811 albertel 1982: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 1983: if (! defined($dom) || $dom eq '' ||
1984: ! defined($name) || $name eq '') {
1.620 albertel 1985: my $cid = $env{'request.course.id'};
1986: $dom = $env{'request.'.$cid.'.domain'};
1987: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 1988: }
1.450 matthew 1989: my $value = $accesshash{$entry};
1990: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
1991: my %temphash=($url => $value);
1.449 matthew 1992: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
1993: if ($result eq 'ok') {
1994: delete $accesshash{$entry};
1995: } elsif ($result eq 'unknown_cmd') {
1996: # Target server has old code running on it.
1.450 matthew 1997: my %temphash=($entry => $value);
1.449 matthew 1998: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1999: delete $accesshash{$entry};
2000: }
2001: }
2002: } else {
1.811 albertel 2003: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2004: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2005: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2006: delete $accesshash{$entry};
2007: }
1.185 www 2008: }
1.191 harris41 2009: }
1.352 www 2010: #
2011: # Roles
2012: # Reverse lookup of user roles for course faculty/staff and co-authorship
2013: #
1.800 albertel 2014: foreach my $entry (keys(%userrolehash)) {
1.351 www 2015: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2016: split(/\:/,$entry);
2017: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2018: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2019: $rudom,$runame) eq 'ok') {
2020: delete $userrolehash{$entry};
2021: }
2022: }
1.662 raeburn 2023: #
2024: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2025: #
2026: my %domrolebuffer = ();
2027: foreach my $entry (keys %domainrolehash) {
2028: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
2029: if ($domrolebuffer{$rudom}) {
2030: $domrolebuffer{$rudom}.='&'.&escape($entry).
2031: '='.&escape($domainrolehash{$entry});
2032: } else {
2033: $domrolebuffer{$rudom}.=&escape($entry).
2034: '='.&escape($domainrolehash{$entry});
2035: }
2036: delete $domainrolehash{$entry};
2037: }
2038: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2039: my %servers = &get_servers($dom,'library');
2040: foreach my $tryserver (keys(%servers)) {
2041: unless (&reply('domroleput:'.$dom.':'.
2042: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2043: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2044: }
1.662 raeburn 2045: }
2046: }
1.186 www 2047: $dumpcount++;
1.157 www 2048: }
2049:
2050: sub courselog {
2051: my $what=shift;
1.158 www 2052: $what=time.':'.$what;
1.620 albertel 2053: unless ($env{'request.course.id'}) { return ''; }
2054: $coursedombuf{$env{'request.course.id'}}=
2055: $env{'course.'.$env{'request.course.id'}.'.domain'};
2056: $coursenumbuf{$env{'request.course.id'}}=
2057: $env{'course.'.$env{'request.course.id'}.'.num'};
2058: $coursehombuf{$env{'request.course.id'}}=
2059: $env{'course.'.$env{'request.course.id'}.'.home'};
2060: $coursedescrbuf{$env{'request.course.id'}}=
2061: $env{'course.'.$env{'request.course.id'}.'.description'};
2062: $courseinstcodebuf{$env{'request.course.id'}}=
2063: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2064: $courseownerbuf{$env{'request.course.id'}}=
2065: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2066: $coursetypebuf{$env{'request.course.id'}}=
2067: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2068: if (defined $courselogs{$env{'request.course.id'}}) {
2069: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2070: } else {
1.620 albertel 2071: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2072: }
1.620 albertel 2073: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2074: &flushcourselogs();
2075: }
1.158 www 2076: }
2077:
2078: sub courseacclog {
2079: my $fnsymb=shift;
1.620 albertel 2080: unless ($env{'request.course.id'}) { return ''; }
2081: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2082: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2083: $what.=':POST';
1.583 matthew 2084: # FIXME: Probably ought to escape things....
1.800 albertel 2085: foreach my $key (keys(%env)) {
2086: if ($key=~/^form\.(.*)/) {
2087: $what.=':'.$1.'='.$env{$key};
1.158 www 2088: }
1.191 harris41 2089: }
1.583 matthew 2090: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2091: # FIXME: We should not be depending on a form parameter that someone
2092: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2093: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2094: $what.= ':POST';
2095: # FIXME: Probably ought to escape things....
2096: foreach my $element ('courseexp','crsfulltext','crsrelated',
2097: 'crsdiscuss') {
1.620 albertel 2098: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2099: }
2100: }
1.158 www 2101: }
2102: &courselog($what);
1.149 www 2103: }
2104:
1.185 www 2105: sub countacc {
2106: my $url=&declutter(shift);
1.458 matthew 2107: return if (! defined($url) || $url eq '');
1.620 albertel 2108: unless ($env{'request.course.id'}) { return ''; }
2109: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2110: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2111: $accesshash{$key}++;
1.185 www 2112: }
1.349 www 2113:
1.361 www 2114: sub linklog {
2115: my ($from,$to)=@_;
2116: $from=&declutter($from);
2117: $to=&declutter($to);
2118: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2119: $accesshash{$to.'___'.$from.'___goto'}=1;
2120: }
2121:
1.349 www 2122: sub userrolelog {
2123: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2124: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2125: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2126: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2127: ($trole=~/^ta/)) {
1.350 www 2128: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2129: $userrolehash
2130: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2131: =$tend.':'.$tstart;
1.662 raeburn 2132: }
2133: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2134: ($trole=~/^li/) || ($trole=~/^li/) ||
2135: ($trole=~/^au/) || ($trole=~/^dg/) ||
2136: ($trole=~/^sc/)) {
2137: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2138: $domainrolehash
2139: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2140: = $tend.':'.$tstart;
2141: }
1.351 www 2142: }
2143:
2144: sub get_course_adv_roles {
2145: my $cid=shift;
1.620 albertel 2146: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2147: my %coursehash=&coursedescription($cid);
1.470 www 2148: my %nothide=();
1.800 albertel 2149: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2150: $nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470 www 2151: }
1.351 www 2152: my %returnhash=();
2153: my %dumphash=
2154: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2155: my $now=time;
1.800 albertel 2156: foreach my $entry (keys %dumphash) {
2157: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2158: if (($tstart) && ($tstart<0)) { next; }
2159: if (($tend) && ($tend<$now)) { next; }
2160: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2161: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2162: if ($username eq '' || $domain eq '') { next; }
1.470 www 2163: if ((&privileged($username,$domain)) &&
2164: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2165: if ($role eq 'cr') { next; }
1.351 www 2166: my $key=&plaintext($role);
2167: if ($section) { $key.=' (Sec/Grp '.$section.')'; }
2168: if ($returnhash{$key}) {
2169: $returnhash{$key}.=','.$username.':'.$domain;
2170: } else {
2171: $returnhash{$key}=$username.':'.$domain;
2172: }
1.400 www 2173: }
2174: return %returnhash;
2175: }
2176:
2177: sub get_my_roles {
1.858 raeburn 2178: my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620 albertel 2179: unless (defined($uname)) { $uname=$env{'user.name'}; }
2180: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858 raeburn 2181: my %dumphash;
2182: if ($context eq 'userroles') {
2183: %dumphash = &dump('roles',$udom,$uname);
2184: } else {
2185: %dumphash=
1.400 www 2186: &dump('nohist_userroles',$udom,$uname);
1.858 raeburn 2187: }
1.400 www 2188: my %returnhash=();
2189: my $now=time;
1.800 albertel 2190: foreach my $entry (keys(%dumphash)) {
2191: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400 www 2192: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2193: my $status = 'active';
2194: if (($tend) && ($tend<$now)) {
2195: $status = 'previous';
2196: }
2197: if (($tstart) && ($now<$tstart)) {
2198: $status = 'future';
2199: }
2200: if (ref($types) eq 'ARRAY') {
2201: if (!grep(/^\Q$status\E$/,@{$types})) {
2202: next;
2203: }
2204: } else {
2205: if ($status ne 'active') {
2206: next;
2207: }
2208: }
1.800 albertel 2209: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.832 raeburn 2210: if (ref($roledoms) eq 'ARRAY') {
2211: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2212: next;
2213: }
2214: }
2215: if (ref($roles) eq 'ARRAY') {
2216: if (!grep(/^\Q$role\E$/,@{$roles})) {
2217: next;
2218: }
2219: }
1.400 www 2220: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832 raeburn 2221: }
1.373 www 2222: return %returnhash;
1.399 www 2223: }
2224:
2225: # ----------------------------------------------------- Frontpage Announcements
2226: #
2227: #
2228:
2229: sub postannounce {
2230: my ($server,$text)=@_;
1.844 albertel 2231: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2232: unless ($text=~/\w/) { $text=''; }
2233: return &reply('setannounce:'.&escape($text),$server);
2234: }
2235:
2236: sub getannounce {
1.448 albertel 2237:
2238: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 2239: my $announcement='';
1.800 albertel 2240: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 2241: close($fh);
1.399 www 2242: if ($announcement=~/\w/) {
2243: return
2244: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 2245: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 2246: } else {
2247: return '';
2248: }
2249: } else {
2250: return '';
2251: }
1.351 www 2252: }
1.353 www 2253:
2254: # ---------------------------------------------------------- Course ID routines
2255: # Deal with domain's nohist_courseid.db files
2256: #
2257:
2258: sub courseidput {
2259: my ($domain,$what,$coursehome)=@_;
2260: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2261: }
2262:
2263: sub courseiddump {
1.791 raeburn 2264: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353 www 2265: my %returnhash=();
1.355 www 2266: unless ($domfilter) { $domfilter=''; }
1.845 albertel 2267: my %libserv = &all_library();
2268: foreach my $tryserver (keys(%libserv)) {
2269: if ( ( $hostidflag == 1
2270: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
2271: || (!defined($hostidflag)) ) {
2272:
2273: if ($domfilter eq ''
2274: || (&host_domain($tryserver) eq $domfilter)) {
1.800 albertel 2275: foreach my $line (
1.844 albertel 2276: split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571 raeburn 2277: $sincefilter.':'.&escape($descfilter).':'.
1.791 raeburn 2278: &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354 www 2279: $tryserver))) {
1.800 albertel 2280: my ($key,$value)=split(/\=/,$line,2);
1.506 raeburn 2281: if (($key) && ($value)) {
1.516 raeburn 2282: $returnhash{&unescape($key)}=$value;
1.506 raeburn 2283: }
1.353 www 2284: }
2285: }
2286: }
2287: }
2288: return %returnhash;
2289: }
2290:
1.658 raeburn 2291: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 2292:
2293: sub dcmailput {
1.685 raeburn 2294: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 2295: my $status = &Apache::lonnet::critical(
1.740 www 2296: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2297: &escape($message),$server);
1.662 raeburn 2298: return $status;
2299: }
2300:
1.658 raeburn 2301: sub dcmaildump {
2302: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 2303: my %returnhash=();
1.846 albertel 2304:
2305: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 2306: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2307: &escape($enddate).':';
2308: my @esc_senders=map { &escape($_)} @$senders;
2309: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 2310: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 2311: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 2312: if (($key) && ($value)) {
2313: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 2314: }
2315: }
2316: }
2317: return %returnhash;
2318: }
1.662 raeburn 2319: # ---------------------------------------------------------- Domain roles
2320:
2321: sub get_domain_roles {
2322: my ($dom,$roles,$startdate,$enddate)=@_;
2323: if (undef($startdate) || $startdate eq '') {
2324: $startdate = '.';
2325: }
2326: if (undef($enddate) || $enddate eq '') {
2327: $enddate = '.';
2328: }
2329: my $rolelist = join(':',@{$roles});
2330: my %personnel = ();
1.841 albertel 2331:
2332: my %servers = &get_servers($dom,'library');
2333: foreach my $tryserver (keys(%servers)) {
2334: %{$personnel{$tryserver}}=();
2335: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
2336: &escape($startdate).':'.
2337: &escape($enddate).':'.
2338: &escape($rolelist), $tryserver))) {
2339: my ($key,$value) = split(/\=/,$line,2);
2340: if (($key) && ($value)) {
2341: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2342: }
2343: }
1.662 raeburn 2344: }
2345: return %personnel;
2346: }
1.658 raeburn 2347:
1.149 www 2348: # ----------------------------------------------------------- Check out an item
2349:
1.504 albertel 2350: sub get_first_access {
2351: my ($type,$argsymb)=@_;
1.790 albertel 2352: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2353: if ($argsymb) { $symb=$argsymb; }
2354: my ($map,$id,$res)=&decode_symb($symb);
1.588 albertel 2355: if ($type eq 'map') {
2356: $res=&symbread($map);
2357: } else {
2358: $res=$symb;
2359: }
2360: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2361: return $times{"$courseid\0$res"};
1.504 albertel 2362: }
2363:
2364: sub set_first_access {
2365: my ($type)=@_;
1.790 albertel 2366: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2367: my ($map,$id,$res)=&decode_symb($symb);
1.588 albertel 2368: if ($type eq 'map') {
2369: $res=&symbread($map);
2370: } else {
2371: $res=$symb;
2372: }
2373: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 2374: if (!$firstaccess) {
1.588 albertel 2375: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 2376: }
2377: return 'already_set';
1.504 albertel 2378: }
2379:
1.149 www 2380: sub checkout {
2381: my ($symb,$tuname,$tudom,$tcrsid)=@_;
2382: my $now=time;
2383: my $lonhost=$perlvar{'lonHostID'};
2384: my $infostr=&escape(
1.234 www 2385: 'CHECKOUTTOKEN&'.
1.149 www 2386: $tuname.'&'.
2387: $tudom.'&'.
2388: $tcrsid.'&'.
2389: $symb.'&'.
2390: $now.'&'.$ENV{'REMOTE_ADDR'});
2391: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 2392: if ($token=~/^error\:/) {
1.672 albertel 2393: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2394: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
2395: "</font>");
2396: return '';
2397: }
2398:
1.149 www 2399: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
2400: $token=~tr/a-z/A-Z/;
2401:
1.153 www 2402: my %infohash=('resource.0.outtoken' => $token,
2403: 'resource.0.checkouttime' => $now,
2404: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 2405:
2406: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2407: return '';
1.151 www 2408: } else {
1.672 albertel 2409: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2410: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
2411: "</font>");
1.149 www 2412: }
2413:
2414: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2415: &escape('Checkout '.$infostr.' - '.
2416: $token)) ne 'ok') {
2417: return '';
1.151 www 2418: } else {
1.672 albertel 2419: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2420: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
2421: "</font>");
1.149 www 2422: }
1.151 www 2423: return $token;
1.149 www 2424: }
2425:
2426: # ------------------------------------------------------------ Check in an item
2427:
2428: sub checkin {
2429: my $token=shift;
1.150 www 2430: my $now=time;
2431: my ($ta,$tb,$lonhost)=split(/\*/,$token);
2432: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 2433: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 2434: $dtoken=~s/\W/\_/g;
1.234 www 2435: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 2436: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
2437:
1.154 www 2438: unless (($tuname) && ($tudom)) {
2439: &logthis('Check in '.$token.' ('.$dtoken.') failed');
2440: return '';
2441: }
2442:
2443: unless (&allowed('mgr',$tcrsid)) {
2444: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 2445: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 2446: return '';
2447: }
2448:
1.153 www 2449: my %infohash=('resource.0.intoken' => $token,
2450: 'resource.0.checkintime' => $now,
2451: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 2452:
2453: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2454: return '';
2455: }
2456:
2457: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2458: &escape('Checkin - '.$token)) ne 'ok') {
2459: return '';
2460: }
2461:
2462: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 2463: }
2464:
2465: # --------------------------------------------- Set Expire Date for Spreadsheet
2466:
2467: sub expirespread {
2468: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 2469: my $cid=$env{'request.course.id'};
1.110 www 2470: if ($cid) {
2471: my $now=time;
2472: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 2473: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
2474: $env{'course.'.$cid.'.num'}.
1.110 www 2475: ':nohist_expirationdates:'.
2476: &escape($key).'='.$now,
1.620 albertel 2477: $env{'course.'.$cid.'.home'})
1.110 www 2478: }
2479: return 'ok';
1.14 www 2480: }
2481:
1.109 www 2482: # ----------------------------------------------------- Devalidate Spreadsheets
2483:
2484: sub devalidate {
1.325 www 2485: my ($symb,$uname,$udom)=@_;
1.620 albertel 2486: my $cid=$env{'request.course.id'};
1.109 www 2487: if ($cid) {
1.391 matthew 2488: # delete the stored spreadsheets for
2489: # - the student level sheet of this user in course's homespace
2490: # - the assessment level sheet for this resource
2491: # for this user in user's homespace
1.553 albertel 2492: # - current conditional state info
1.325 www 2493: my $key=$uname.':'.$udom.':';
1.109 www 2494: my $status=
1.299 matthew 2495: &del('nohist_calculatedsheets',
1.391 matthew 2496: [$key.'studentcalc:'],
1.620 albertel 2497: $env{'course.'.$cid.'.domain'},
2498: $env{'course.'.$cid.'.num'})
1.133 albertel 2499: .' '.
2500: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 2501: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 2502: unless ($status eq 'ok ok') {
2503: &logthis('Could not devalidate spreadsheet '.
1.325 www 2504: $uname.' at '.$udom.' for '.
1.109 www 2505: $symb.': '.$status);
1.133 albertel 2506: }
1.553 albertel 2507: &delenv('user.state.'.$cid);
1.109 www 2508: }
2509: }
2510:
1.265 albertel 2511: sub get_scalar {
2512: my ($string,$end) = @_;
2513: my $value;
2514: if ($$string =~ s/^([^&]*?)($end)/$2/) {
2515: $value = $1;
2516: } elsif ($$string =~ s/^([^&]*?)&//) {
2517: $value = $1;
2518: }
2519: return &unescape($value);
2520: }
2521:
2522: sub array2str {
2523: my (@array) = @_;
2524: my $result=&arrayref2str(\@array);
2525: $result=~s/^__ARRAY_REF__//;
2526: $result=~s/__END_ARRAY_REF__$//;
2527: return $result;
2528: }
2529:
1.204 albertel 2530: sub arrayref2str {
2531: my ($arrayref) = @_;
1.265 albertel 2532: my $result='__ARRAY_REF__';
1.204 albertel 2533: foreach my $elem (@$arrayref) {
1.265 albertel 2534: if(ref($elem) eq 'ARRAY') {
2535: $result.=&arrayref2str($elem).'&';
2536: } elsif(ref($elem) eq 'HASH') {
2537: $result.=&hashref2str($elem).'&';
2538: } elsif(ref($elem)) {
2539: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 2540: } else {
2541: $result.=&escape($elem).'&';
2542: }
2543: }
2544: $result=~s/\&$//;
1.265 albertel 2545: $result .= '__END_ARRAY_REF__';
1.204 albertel 2546: return $result;
2547: }
2548:
1.168 albertel 2549: sub hash2str {
1.204 albertel 2550: my (%hash) = @_;
2551: my $result=&hashref2str(\%hash);
1.265 albertel 2552: $result=~s/^__HASH_REF__//;
2553: $result=~s/__END_HASH_REF__$//;
1.204 albertel 2554: return $result;
2555: }
2556:
2557: sub hashref2str {
2558: my ($hashref)=@_;
1.265 albertel 2559: my $result='__HASH_REF__';
1.800 albertel 2560: foreach my $key (sort(keys(%$hashref))) {
2561: if (ref($key) eq 'ARRAY') {
2562: $result.=&arrayref2str($key).'=';
2563: } elsif (ref($key) eq 'HASH') {
2564: $result.=&hashref2str($key).'=';
2565: } elsif (ref($key)) {
1.265 albertel 2566: $result.='=';
1.800 albertel 2567: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 2568: } else {
1.800 albertel 2569: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 2570: }
2571:
1.800 albertel 2572: if(ref($hashref->{$key}) eq 'ARRAY') {
2573: $result.=&arrayref2str($hashref->{$key}).'&';
2574: } elsif(ref($hashref->{$key}) eq 'HASH') {
2575: $result.=&hashref2str($hashref->{$key}).'&';
2576: } elsif(ref($hashref->{$key})) {
1.265 albertel 2577: $result.='&';
1.800 albertel 2578: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 2579: } else {
1.800 albertel 2580: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 2581: }
2582: }
1.168 albertel 2583: $result=~s/\&$//;
1.265 albertel 2584: $result .= '__END_HASH_REF__';
1.168 albertel 2585: return $result;
2586: }
2587:
2588: sub str2hash {
1.265 albertel 2589: my ($string)=@_;
2590: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
2591: return %$hash;
2592: }
2593:
2594: sub str2hashref {
1.168 albertel 2595: my ($string) = @_;
1.265 albertel 2596:
2597: my %hash;
2598:
2599: if($string !~ /^__HASH_REF__/) {
2600: if (! ($string eq '' || !defined($string))) {
2601: $hash{'error'}='Not hash reference';
2602: }
2603: return (\%hash, $string);
2604: }
2605:
2606: $string =~ s/^__HASH_REF__//;
2607:
2608: while($string !~ /^__END_HASH_REF__/) {
2609: #key
2610: my $key='';
2611: if($string =~ /^__HASH_REF__/) {
2612: ($key, $string)=&str2hashref($string);
2613: if(defined($key->{'error'})) {
2614: $hash{'error'}='Bad data';
2615: return (\%hash, $string);
2616: }
2617: } elsif($string =~ /^__ARRAY_REF__/) {
2618: ($key, $string)=&str2arrayref($string);
2619: if($key->[0] eq 'Array reference error') {
2620: $hash{'error'}='Bad data';
2621: return (\%hash, $string);
2622: }
2623: } else {
2624: $string =~ s/^(.*?)=//;
1.267 albertel 2625: $key=&unescape($1);
1.265 albertel 2626: }
2627: $string =~ s/^=//;
2628:
2629: #value
2630: my $value='';
2631: if($string =~ /^__HASH_REF__/) {
2632: ($value, $string)=&str2hashref($string);
2633: if(defined($value->{'error'})) {
2634: $hash{'error'}='Bad data';
2635: return (\%hash, $string);
2636: }
2637: } elsif($string =~ /^__ARRAY_REF__/) {
2638: ($value, $string)=&str2arrayref($string);
2639: if($value->[0] eq 'Array reference error') {
2640: $hash{'error'}='Bad data';
2641: return (\%hash, $string);
2642: }
2643: } else {
2644: $value=&get_scalar(\$string,'__END_HASH_REF__');
2645: }
2646: $string =~ s/^&//;
2647:
2648: $hash{$key}=$value;
1.204 albertel 2649: }
1.265 albertel 2650:
2651: $string =~ s/^__END_HASH_REF__//;
2652:
2653: return (\%hash, $string);
1.204 albertel 2654: }
2655:
2656: sub str2array {
1.265 albertel 2657: my ($string)=@_;
2658: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
2659: return @$array;
2660: }
2661:
2662: sub str2arrayref {
1.204 albertel 2663: my ($string) = @_;
1.265 albertel 2664: my @array;
2665:
2666: if($string !~ /^__ARRAY_REF__/) {
2667: if (! ($string eq '' || !defined($string))) {
2668: $array[0]='Array reference error';
2669: }
2670: return (\@array, $string);
2671: }
2672:
2673: $string =~ s/^__ARRAY_REF__//;
2674:
2675: while($string !~ /^__END_ARRAY_REF__/) {
2676: my $value='';
2677: if($string =~ /^__HASH_REF__/) {
2678: ($value, $string)=&str2hashref($string);
2679: if(defined($value->{'error'})) {
2680: $array[0] ='Array reference error';
2681: return (\@array, $string);
2682: }
2683: } elsif($string =~ /^__ARRAY_REF__/) {
2684: ($value, $string)=&str2arrayref($string);
2685: if($value->[0] eq 'Array reference error') {
2686: $array[0] ='Array reference error';
2687: return (\@array, $string);
2688: }
2689: } else {
2690: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
2691: }
2692: $string =~ s/^&//;
2693:
2694: push(@array, $value);
1.191 harris41 2695: }
1.265 albertel 2696:
2697: $string =~ s/^__END_ARRAY_REF__//;
2698:
2699: return (\@array, $string);
1.168 albertel 2700: }
2701:
1.167 albertel 2702: # -------------------------------------------------------------------Temp Store
2703:
1.168 albertel 2704: sub tmpreset {
2705: my ($symb,$namespace,$domain,$stuname) = @_;
2706: if (!$symb) {
2707: $symb=&symbread();
1.620 albertel 2708: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2709: }
2710: $symb=escape($symb);
2711:
1.620 albertel 2712: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 2713: $namespace=~s/\//\_/g;
2714: $namespace=~s/\W//g;
2715:
1.620 albertel 2716: if (!$domain) { $domain=$env{'user.domain'}; }
2717: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2718: if ($domain eq 'public' && $stuname eq 'public') {
2719: $stuname=$ENV{'REMOTE_ADDR'};
2720: }
1.168 albertel 2721: my $path=$perlvar{'lonDaemons'}.'/tmp';
2722: my %hash;
2723: if (tie(%hash,'GDBM_File',
2724: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2725: &GDBM_WRCREAT(),0640)) {
1.168 albertel 2726: foreach my $key (keys %hash) {
1.180 albertel 2727: if ($key=~ /:$symb/) {
1.168 albertel 2728: delete($hash{$key});
2729: }
2730: }
2731: }
2732: }
2733:
1.167 albertel 2734: sub tmpstore {
1.168 albertel 2735: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2736:
2737: if (!$symb) {
2738: $symb=&symbread();
1.620 albertel 2739: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2740: }
2741: $symb=escape($symb);
2742:
2743: if (!$namespace) {
2744: # I don't think we would ever want to store this for a course.
2745: # it seems this will only be used if we don't have a course.
1.620 albertel 2746: #$namespace=$env{'request.course.id'};
1.168 albertel 2747: #if (!$namespace) {
1.620 albertel 2748: $namespace=$env{'request.state'};
1.168 albertel 2749: #}
2750: }
2751: $namespace=~s/\//\_/g;
2752: $namespace=~s/\W//g;
1.620 albertel 2753: if (!$domain) { $domain=$env{'user.domain'}; }
2754: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2755: if ($domain eq 'public' && $stuname eq 'public') {
2756: $stuname=$ENV{'REMOTE_ADDR'};
2757: }
1.168 albertel 2758: my $now=time;
2759: my %hash;
2760: my $path=$perlvar{'lonDaemons'}.'/tmp';
2761: if (tie(%hash,'GDBM_File',
2762: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2763: &GDBM_WRCREAT(),0640)) {
1.168 albertel 2764: $hash{"version:$symb"}++;
2765: my $version=$hash{"version:$symb"};
2766: my $allkeys='';
2767: foreach my $key (keys(%$storehash)) {
2768: $allkeys.=$key.':';
1.591 albertel 2769: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 2770: }
2771: $hash{"$version:$symb:timestamp"}=$now;
2772: $allkeys.='timestamp';
2773: $hash{"$version:keys:$symb"}=$allkeys;
2774: if (untie(%hash)) {
2775: return 'ok';
2776: } else {
2777: return "error:$!";
2778: }
2779: } else {
2780: return "error:$!";
2781: }
2782: }
1.167 albertel 2783:
1.168 albertel 2784: # -----------------------------------------------------------------Temp Restore
1.167 albertel 2785:
1.168 albertel 2786: sub tmprestore {
2787: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 2788:
1.168 albertel 2789: if (!$symb) {
2790: $symb=&symbread();
1.620 albertel 2791: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2792: }
2793: $symb=escape($symb);
2794:
1.620 albertel 2795: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 2796:
1.620 albertel 2797: if (!$domain) { $domain=$env{'user.domain'}; }
2798: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2799: if ($domain eq 'public' && $stuname eq 'public') {
2800: $stuname=$ENV{'REMOTE_ADDR'};
2801: }
1.168 albertel 2802: my %returnhash;
2803: $namespace=~s/\//\_/g;
2804: $namespace=~s/\W//g;
2805: my %hash;
2806: my $path=$perlvar{'lonDaemons'}.'/tmp';
2807: if (tie(%hash,'GDBM_File',
2808: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2809: &GDBM_READER(),0640)) {
1.168 albertel 2810: my $version=$hash{"version:$symb"};
2811: $returnhash{'version'}=$version;
2812: my $scope;
2813: for ($scope=1;$scope<=$version;$scope++) {
2814: my $vkeys=$hash{"$scope:keys:$symb"};
2815: my @keys=split(/:/,$vkeys);
2816: my $key;
2817: $returnhash{"$scope:keys"}=$vkeys;
2818: foreach $key (@keys) {
1.591 albertel 2819: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
2820: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 2821: }
2822: }
1.168 albertel 2823: if (!(untie(%hash))) {
2824: return "error:$!";
2825: }
2826: } else {
2827: return "error:$!";
2828: }
2829: return %returnhash;
1.167 albertel 2830: }
2831:
1.9 www 2832: # ----------------------------------------------------------------------- Store
2833:
2834: sub store {
1.124 www 2835: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2836: my $home='';
2837:
1.168 albertel 2838: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2839:
1.213 www 2840: $symb=&symbclean($symb);
1.122 albertel 2841: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 2842:
1.620 albertel 2843: if (!$domain) { $domain=$env{'user.domain'}; }
2844: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 2845:
2846: &devalidate($symb,$stuname,$domain);
1.109 www 2847:
2848: $symb=escape($symb);
1.187 www 2849: if (!$namespace) {
1.620 albertel 2850: unless ($namespace=$env{'request.course.id'}) {
1.187 www 2851: return '';
2852: }
2853: }
1.620 albertel 2854: if (!$home) { $home=$env{'user.home'}; }
1.447 www 2855:
2856: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2857: $$storehash{'host'}=$perlvar{'lonHostID'};
2858:
1.12 www 2859: my $namevalue='';
1.800 albertel 2860: foreach my $key (keys(%$storehash)) {
2861: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 2862: }
1.12 www 2863: $namevalue=~s/\&$//;
1.187 www 2864: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 2865: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 2866: }
2867:
1.47 www 2868: # -------------------------------------------------------------- Critical Store
2869:
2870: sub cstore {
1.124 www 2871: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2872: my $home='';
2873:
1.168 albertel 2874: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2875:
1.213 www 2876: $symb=&symbclean($symb);
1.122 albertel 2877: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 2878:
1.620 albertel 2879: if (!$domain) { $domain=$env{'user.domain'}; }
2880: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 2881:
2882: &devalidate($symb,$stuname,$domain);
1.109 www 2883:
2884: $symb=escape($symb);
1.187 www 2885: if (!$namespace) {
1.620 albertel 2886: unless ($namespace=$env{'request.course.id'}) {
1.187 www 2887: return '';
2888: }
2889: }
1.620 albertel 2890: if (!$home) { $home=$env{'user.home'}; }
1.447 www 2891:
2892: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2893: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 2894:
1.47 www 2895: my $namevalue='';
1.800 albertel 2896: foreach my $key (keys(%$storehash)) {
2897: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 2898: }
1.47 www 2899: $namevalue=~s/\&$//;
1.187 www 2900: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 2901: return critical
2902: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 2903: }
2904:
1.9 www 2905: # --------------------------------------------------------------------- Restore
2906:
2907: sub restore {
1.124 www 2908: my ($symb,$namespace,$domain,$stuname) = @_;
2909: my $home='';
2910:
1.168 albertel 2911: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2912:
1.122 albertel 2913: if (!$symb) {
2914: unless ($symb=escape(&symbread())) { return ''; }
2915: } else {
1.213 www 2916: $symb=&escape(&symbclean($symb));
1.122 albertel 2917: }
1.188 www 2918: if (!$namespace) {
1.620 albertel 2919: unless ($namespace=$env{'request.course.id'}) {
1.188 www 2920: return '';
2921: }
2922: }
1.620 albertel 2923: if (!$domain) { $domain=$env{'user.domain'}; }
2924: if (!$stuname) { $stuname=$env{'user.name'}; }
2925: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 2926: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
2927:
1.12 www 2928: my %returnhash=();
1.800 albertel 2929: foreach my $line (split(/\&/,$answer)) {
2930: my ($name,$value)=split(/\=/,$line);
1.591 albertel 2931: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 2932: }
1.75 www 2933: my $version;
2934: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 2935: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
2936: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 2937: }
1.75 www 2938: }
1.13 www 2939: return %returnhash;
1.34 www 2940: }
2941:
2942: # ---------------------------------------------------------- Course Description
2943:
2944: sub coursedescription {
1.731 albertel 2945: my ($courseid,$args)=@_;
1.34 www 2946: $courseid=~s/^\///;
1.49 www 2947: $courseid=~s/\_/\//g;
1.34 www 2948: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 2949: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 2950: my $normalid=$cdomain.'_'.$cnum;
2951: # need to always cache even if we get errors otherwise we keep
2952: # trying and trying and trying to get the course description.
2953: my %envhash=();
2954: my %returnhash=();
1.731 albertel 2955:
2956: my $expiretime=600;
2957: if ($env{'request.course.id'} eq $normalid) {
2958: $expiretime=120;
2959: }
2960:
2961: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
2962: if (!$args->{'freshen_cache'}
2963: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
2964: foreach my $key (keys(%env)) {
2965: next if ($key !~ /^\Q$prefix\E(.*)/);
2966: my ($setting) = $1;
2967: $returnhash{$setting} = $env{$key};
2968: }
2969: return %returnhash;
2970: }
2971:
2972: # get the data agin
2973: if (!$args->{'one_time'}) {
2974: $envhash{'course.'.$normalid.'.last_cache'}=time;
2975: }
1.811 albertel 2976:
1.34 www 2977: if ($chome ne 'no_host') {
1.302 albertel 2978: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 2979: if (!exists($returnhash{'con_lost'})) {
2980: $returnhash{'home'}= $chome;
2981: $returnhash{'domain'} = $cdomain;
2982: $returnhash{'num'} = $cnum;
1.741 raeburn 2983: if (!defined($returnhash{'type'})) {
2984: $returnhash{'type'} = 'Course';
2985: }
1.130 albertel 2986: while (my ($name,$value) = each %returnhash) {
1.53 www 2987: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 2988: }
1.270 www 2989: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 2990: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 2991: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 2992: $envhash{'course.'.$normalid.'.home'}=$chome;
2993: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
2994: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 2995: }
2996: }
1.731 albertel 2997: if (!$args->{'one_time'}) {
2998: &appenv(%envhash);
2999: }
1.302 albertel 3000: return %returnhash;
1.461 www 3001: }
3002:
3003: # -------------------------------------------------See if a user is privileged
3004:
3005: sub privileged {
3006: my ($username,$domain)=@_;
3007: my $rolesdump=&reply("dump:$domain:$username:roles",
3008: &homeserver($username,$domain));
3009: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
3010: my $now=time;
3011: if ($rolesdump ne '') {
1.800 albertel 3012: foreach my $entry (split(/&/,$rolesdump)) {
3013: if ($entry!~/^rolesdef_/) {
3014: my ($area,$role)=split(/=/,$entry);
1.461 www 3015: $area=~s/\_\w\w$//;
3016: my ($trole,$tend,$tstart)=split(/_/,$role);
3017: if (($trole eq 'dc') || ($trole eq 'su')) {
3018: my $active=1;
3019: if ($tend) {
3020: if ($tend<$now) { $active=0; }
3021: }
3022: if ($tstart) {
3023: if ($tstart>$now) { $active=0; }
3024: }
3025: if ($active) { return 1; }
3026: }
3027: }
3028: }
3029: }
3030: return 0;
1.9 www 3031: }
1.1 albertel 3032:
1.103 harris41 3033: # -------------------------------------------------------- Get user privileges
1.11 www 3034:
3035: sub rolesinit {
3036: my ($domain,$username,$authhost)=@_;
3037: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12 www 3038: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11 www 3039: my %allroles=();
1.678 raeburn 3040: my %allgroups=();
1.11 www 3041: my $now=time;
1.743 albertel 3042: my %userroles = ('user.login.time' => $now);
1.678 raeburn 3043: my $group_privs;
1.11 www 3044:
3045: if ($rolesdump ne '') {
1.800 albertel 3046: foreach my $entry (split(/&/,$rolesdump)) {
3047: if ($entry!~/^rolesdef_/) {
3048: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3049: $area=~s/\_\w\w$//;
1.678 raeburn 3050: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3051: if ($role=~/^cr/) {
1.807 albertel 3052: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3053: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3054: ($tend,$tstart)=split('_',$trest);
3055: } else {
3056: $trole=$role;
3057: }
1.678 raeburn 3058: } elsif ($role =~ m|^gr/|) {
3059: ($trole,$tend,$tstart) = split(/_/,$role);
3060: ($trole,$group_privs) = split(/\//,$trole);
3061: $group_privs = &unescape($group_privs);
1.587 albertel 3062: } else {
3063: ($trole,$tend,$tstart)=split(/_/,$role);
3064: }
1.743 albertel 3065: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3066: $username);
3067: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3068: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3069: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3070: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3071: my $spec=$trole.'.'.$area;
3072: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3073: if ($trole =~ /^cr\//) {
1.567 raeburn 3074: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3075: } elsif ($trole eq 'gr') {
3076: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3077: } else {
1.567 raeburn 3078: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3079: }
1.12 www 3080: }
1.662 raeburn 3081: }
1.191 harris41 3082: }
1.743 albertel 3083: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3084: $userroles{'user.adv'} = $adv;
3085: $userroles{'user.author'} = $author;
1.620 albertel 3086: $env{'user.adv'}=$adv;
1.11 www 3087: }
1.743 albertel 3088: return \%userroles;
1.11 www 3089: }
3090:
1.567 raeburn 3091: sub set_arearole {
3092: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3093: # log the associated role with the area
3094: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3095: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3096: }
3097:
3098: sub custom_roleprivs {
3099: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3100: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3101: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3102: if (&hostname($homsvr) ne '') {
1.567 raeburn 3103: my ($rdummy,$roledef)=
3104: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3105: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3106: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3107: if (defined($syspriv)) {
3108: $$allroles{'cm./'}.=':'.$syspriv;
3109: $$allroles{$spec.'./'}.=':'.$syspriv;
3110: }
3111: if ($tdomain ne '') {
3112: if (defined($dompriv)) {
3113: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3114: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3115: }
3116: if (($trest ne '') && (defined($coursepriv))) {
3117: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3118: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3119: }
3120: }
3121: }
3122: }
3123: }
3124:
1.678 raeburn 3125: sub group_roleprivs {
3126: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3127: my $access = 1;
3128: my $now = time;
3129: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3130: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3131: if ($access) {
1.811 albertel 3132: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3133: $$allgroups{$course}{$group} .=':'.$group_privs;
3134: }
3135: }
1.567 raeburn 3136:
3137: sub standard_roleprivs {
3138: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3139: if (defined($pr{$trole.':s'})) {
3140: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3141: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3142: }
3143: if ($tdomain ne '') {
3144: if (defined($pr{$trole.':d'})) {
3145: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3146: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3147: }
3148: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3149: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3150: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3151: }
3152: }
3153: }
3154:
3155: sub set_userprivs {
1.678 raeburn 3156: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 3157: my $author=0;
3158: my $adv=0;
1.678 raeburn 3159: my %grouproles = ();
3160: if (keys(%{$allgroups}) > 0) {
3161: foreach my $role (keys %{$allroles}) {
1.681 raeburn 3162: my ($trole,$area,$sec,$extendedarea);
1.811 albertel 3163: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678 raeburn 3164: $trole = $1;
3165: $area = $2;
1.681 raeburn 3166: $sec = $3;
3167: $extendedarea = $area.$sec;
3168: if (exists($$allgroups{$area})) {
3169: foreach my $group (keys(%{$$allgroups{$area}})) {
3170: my $spec = $trole.'.'.$extendedarea;
3171: $grouproles{$spec.'.'.$area.'/'.$group} =
3172: $$allgroups{$area}{$group};
1.678 raeburn 3173: }
3174: }
3175: }
3176: }
3177: }
1.800 albertel 3178: foreach my $group (keys(%grouproles)) {
3179: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3180: }
1.800 albertel 3181: foreach my $role (keys(%{$allroles})) {
3182: my %thesepriv;
3183: if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
3184: foreach my $item (split(/:/,$$allroles{$role})) {
3185: if ($item ne '') {
3186: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3187: if ($restrictions eq '') {
3188: $thesepriv{$privilege}='F';
3189: } elsif ($thesepriv{$privilege} ne 'F') {
3190: $thesepriv{$privilege}.=$restrictions;
3191: }
3192: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3193: }
3194: }
3195: my $thesestr='';
1.800 albertel 3196: foreach my $priv (keys(%thesepriv)) {
3197: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3198: }
3199: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3200: }
3201: return ($author,$adv);
3202: }
3203:
1.12 www 3204: # --------------------------------------------------------------- get interface
3205:
3206: sub get {
1.131 albertel 3207: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3208: my $items='';
1.800 albertel 3209: foreach my $item (@$storearr) {
3210: $items.=&escape($item).'&';
1.191 harris41 3211: }
1.12 www 3212: $items=~s/\&$//;
1.620 albertel 3213: if (!$udomain) { $udomain=$env{'user.domain'}; }
3214: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 3215: my $uhome=&homeserver($uname,$udomain);
3216:
1.133 albertel 3217: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3218: my @pairs=split(/\&/,$rep);
1.273 albertel 3219: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
3220: return @pairs;
3221: }
1.15 www 3222: my %returnhash=();
1.42 www 3223: my $i=0;
1.800 albertel 3224: foreach my $item (@$storearr) {
3225: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3226: $i++;
1.191 harris41 3227: }
1.15 www 3228: return %returnhash;
1.27 www 3229: }
3230:
3231: # --------------------------------------------------------------- del interface
3232:
3233: sub del {
1.133 albertel 3234: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 3235: my $items='';
1.800 albertel 3236: foreach my $item (@$storearr) {
3237: $items.=&escape($item).'&';
1.191 harris41 3238: }
1.27 www 3239: $items=~s/\&$//;
1.620 albertel 3240: if (!$udomain) { $udomain=$env{'user.domain'}; }
3241: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3242: my $uhome=&homeserver($uname,$udomain);
3243:
3244: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3245: }
3246:
3247: # -------------------------------------------------------------- dump interface
3248:
3249: sub dump {
1.755 albertel 3250: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3251: if (!$udomain) { $udomain=$env{'user.domain'}; }
3252: if (!$uname) { $uname=$env{'user.name'}; }
3253: my $uhome=&homeserver($uname,$udomain);
3254: if ($regexp) {
3255: $regexp=&escape($regexp);
3256: } else {
3257: $regexp='.';
3258: }
3259: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3260: my @pairs=split(/\&/,$rep);
3261: my %returnhash=();
3262: foreach my $item (@pairs) {
3263: my ($key,$value)=split(/=/,$item,2);
3264: $key = &unescape($key);
3265: next if ($key =~ /^error: 2 /);
3266: $returnhash{$key}=&thaw_unescape($value);
3267: }
3268: return %returnhash;
1.407 www 3269: }
3270:
1.717 albertel 3271: # --------------------------------------------------------- dumpstore interface
3272:
3273: sub dumpstore {
3274: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 3275: if (!$udomain) { $udomain=$env{'user.domain'}; }
3276: if (!$uname) { $uname=$env{'user.name'}; }
3277: my $uhome=&homeserver($uname,$udomain);
3278: if ($regexp) {
3279: $regexp=&escape($regexp);
3280: } else {
3281: $regexp='.';
3282: }
3283: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3284: my @pairs=split(/\&/,$rep);
3285: my %returnhash=();
3286: foreach my $item (@pairs) {
3287: my ($key,$value)=split(/=/,$item,2);
3288: next if ($key =~ /^error: 2 /);
3289: $returnhash{$key}=&thaw_unescape($value);
3290: }
3291: return %returnhash;
1.717 albertel 3292: }
3293:
1.407 www 3294: # -------------------------------------------------------------- keys interface
3295:
3296: sub getkeys {
3297: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 3298: if (!$udomain) { $udomain=$env{'user.domain'}; }
3299: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 3300: my $uhome=&homeserver($uname,$udomain);
3301: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3302: my @keyarray=();
1.800 albertel 3303: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 3304: next if ($key =~ /^error: 2 /);
1.800 albertel 3305: push(@keyarray,&unescape($key));
1.407 www 3306: }
3307: return @keyarray;
1.318 matthew 3308: }
3309:
1.319 matthew 3310: # --------------------------------------------------------------- currentdump
3311: sub currentdump {
1.328 matthew 3312: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 3313: $courseid = $env{'request.course.id'} if (! defined($courseid));
3314: $sdom = $env{'user.domain'} if (! defined($sdom));
3315: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 3316: my $uhome = &homeserver($sname,$sdom);
3317: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 3318: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 3319: #
1.318 matthew 3320: my %returnhash=();
1.319 matthew 3321: #
3322: if ($rep eq "unknown_cmd") {
3323: # an old lond will not know currentdump
3324: # Do a dump and make it look like a currentdump
1.822 albertel 3325: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 3326: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3327: my %hash = @tmp;
3328: @tmp=();
1.424 matthew 3329: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 3330: } else {
3331: my @pairs=split(/\&/,$rep);
1.800 albertel 3332: foreach my $pair (@pairs) {
3333: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 3334: my ($symb,$param) = split(/:/,$key);
3335: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 3336: &thaw_unescape($value);
1.319 matthew 3337: }
1.191 harris41 3338: }
1.12 www 3339: return %returnhash;
1.424 matthew 3340: }
3341:
3342: sub convert_dump_to_currentdump{
3343: my %hash = %{shift()};
3344: my %returnhash;
3345: # Code ripped from lond, essentially. The only difference
3346: # here is the unescaping done by lonnet::dump(). Conceivably
3347: # we might run in to problems with parameter names =~ /^v\./
3348: while (my ($key,$value) = each(%hash)) {
3349: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 3350: $symb = &unescape($symb);
3351: $param = &unescape($param);
1.424 matthew 3352: next if ($v eq 'version' || $symb eq 'keys');
3353: next if (exists($returnhash{$symb}) &&
3354: exists($returnhash{$symb}->{$param}) &&
3355: $returnhash{$symb}->{'v.'.$param} > $v);
3356: $returnhash{$symb}->{$param}=$value;
3357: $returnhash{$symb}->{'v.'.$param}=$v;
3358: }
3359: #
3360: # Remove all of the keys in the hashes which keep track of
3361: # the version of the parameter.
3362: while (my ($symb,$param_hash) = each(%returnhash)) {
3363: # use a foreach because we are going to delete from the hash.
3364: foreach my $key (keys(%$param_hash)) {
3365: delete($param_hash->{$key}) if ($key =~ /^v\./);
3366: }
3367: }
3368: return \%returnhash;
1.12 www 3369: }
3370:
1.627 albertel 3371: # ------------------------------------------------------ critical inc interface
3372:
3373: sub cinc {
3374: return &inc(@_,'critical');
3375: }
3376:
1.449 matthew 3377: # --------------------------------------------------------------- inc interface
3378:
3379: sub inc {
1.627 albertel 3380: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 3381: if (!$udomain) { $udomain=$env{'user.domain'}; }
3382: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 3383: my $uhome=&homeserver($uname,$udomain);
3384: my $items='';
3385: if (! ref($store)) {
3386: # got a single value, so use that instead
3387: $items = &escape($store).'=&';
3388: } elsif (ref($store) eq 'SCALAR') {
3389: $items = &escape($$store).'=&';
3390: } elsif (ref($store) eq 'ARRAY') {
3391: $items = join('=&',map {&escape($_);} @{$store});
3392: } elsif (ref($store) eq 'HASH') {
3393: while (my($key,$value) = each(%{$store})) {
3394: $items.= &escape($key).'='.&escape($value).'&';
3395: }
3396: }
3397: $items=~s/\&$//;
1.627 albertel 3398: if ($critical) {
3399: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
3400: } else {
3401: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
3402: }
1.449 matthew 3403: }
3404:
1.12 www 3405: # --------------------------------------------------------------- put interface
3406:
3407: sub put {
1.134 albertel 3408: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3409: if (!$udomain) { $udomain=$env{'user.domain'}; }
3410: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3411: my $uhome=&homeserver($uname,$udomain);
1.12 www 3412: my $items='';
1.800 albertel 3413: foreach my $item (keys(%$storehash)) {
3414: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3415: }
1.12 www 3416: $items=~s/\&$//;
1.134 albertel 3417: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 3418: }
3419:
1.631 albertel 3420: # ------------------------------------------------------------ newput interface
3421:
3422: sub newput {
3423: my ($namespace,$storehash,$udomain,$uname)=@_;
3424: if (!$udomain) { $udomain=$env{'user.domain'}; }
3425: if (!$uname) { $uname=$env{'user.name'}; }
3426: my $uhome=&homeserver($uname,$udomain);
3427: my $items='';
3428: foreach my $key (keys(%$storehash)) {
3429: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3430: }
3431: $items=~s/\&$//;
3432: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
3433: }
3434:
3435: # --------------------------------------------------------- putstore interface
3436:
1.524 raeburn 3437: sub putstore {
1.715 albertel 3438: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 3439: if (!$udomain) { $udomain=$env{'user.domain'}; }
3440: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 3441: my $uhome=&homeserver($uname,$udomain);
3442: my $items='';
1.715 albertel 3443: foreach my $key (keys(%$storehash)) {
3444: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 3445: }
1.715 albertel 3446: $items=~s/\&$//;
1.716 albertel 3447: my $esc_symb=&escape($symb);
3448: my $esc_v=&escape($version);
1.715 albertel 3449: my $reply =
1.716 albertel 3450: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 3451: $uhome);
3452: if ($reply eq 'unknown_cmd') {
1.716 albertel 3453: # gfall back to way things use to be done
1.715 albertel 3454: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
3455: $uname);
1.524 raeburn 3456: }
1.715 albertel 3457: return $reply;
3458: }
3459:
3460: sub old_putstore {
1.716 albertel 3461: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3462: if (!$udomain) { $udomain=$env{'user.domain'}; }
3463: if (!$uname) { $uname=$env{'user.name'}; }
3464: my $uhome=&homeserver($uname,$udomain);
3465: my %newstorehash;
1.800 albertel 3466: foreach my $item (keys(%$storehash)) {
3467: my $key = $version.':'.&escape($symb).':'.$item;
3468: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 3469: }
3470: my $items='';
3471: my %allitems = ();
1.800 albertel 3472: foreach my $item (keys(%newstorehash)) {
3473: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 3474: my $key = $1.':keys:'.$2;
3475: $allitems{$key} .= $3.':';
3476: }
1.800 albertel 3477: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 3478: }
1.800 albertel 3479: foreach my $item (keys(%allitems)) {
3480: $allitems{$item} =~ s/\:$//;
3481: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 3482: }
3483: $items=~s/\&$//;
3484: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 3485: }
3486:
1.47 www 3487: # ------------------------------------------------------ critical put interface
3488:
3489: sub cput {
1.134 albertel 3490: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3491: if (!$udomain) { $udomain=$env{'user.domain'}; }
3492: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3493: my $uhome=&homeserver($uname,$udomain);
1.47 www 3494: my $items='';
1.800 albertel 3495: foreach my $item (keys(%$storehash)) {
3496: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3497: }
1.47 www 3498: $items=~s/\&$//;
1.134 albertel 3499: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3500: }
3501:
3502: # -------------------------------------------------------------- eget interface
3503:
3504: sub eget {
1.133 albertel 3505: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3506: my $items='';
1.800 albertel 3507: foreach my $item (@$storearr) {
3508: $items.=&escape($item).'&';
1.191 harris41 3509: }
1.12 www 3510: $items=~s/\&$//;
1.620 albertel 3511: if (!$udomain) { $udomain=$env{'user.domain'}; }
3512: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3513: my $uhome=&homeserver($uname,$udomain);
3514: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3515: my @pairs=split(/\&/,$rep);
3516: my %returnhash=();
1.42 www 3517: my $i=0;
1.800 albertel 3518: foreach my $item (@$storearr) {
3519: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3520: $i++;
1.191 harris41 3521: }
1.12 www 3522: return %returnhash;
3523: }
3524:
1.667 albertel 3525: # ------------------------------------------------------------ tmpput interface
3526: sub tmpput {
1.802 raeburn 3527: my ($storehash,$server,$context)=@_;
1.667 albertel 3528: my $items='';
1.800 albertel 3529: foreach my $item (keys(%$storehash)) {
3530: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 3531: }
3532: $items=~s/\&$//;
1.802 raeburn 3533: if (defined($context)) {
3534: $items .= ':'.&escape($context);
3535: }
1.667 albertel 3536: return &reply("tmpput:$items",$server);
3537: }
3538:
3539: # ------------------------------------------------------------ tmpget interface
3540: sub tmpget {
1.688 albertel 3541: my ($token,$server)=@_;
3542: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3543: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 3544: my %returnhash;
3545: foreach my $item (split(/\&/,$rep)) {
3546: my ($key,$value)=split(/=/,$item);
3547: $returnhash{&unescape($key)}=&thaw_unescape($value);
3548: }
3549: return %returnhash;
3550: }
3551:
1.688 albertel 3552: # ------------------------------------------------------------ tmpget interface
3553: sub tmpdel {
3554: my ($token,$server)=@_;
3555: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3556: return &reply("tmpdel:$token",$server);
3557: }
3558:
1.765 albertel 3559: # -------------------------------------------------- portfolio access checking
3560:
3561: sub portfolio_access {
1.766 albertel 3562: my ($requrl) = @_;
1.765 albertel 3563: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
3564: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 3565: if ($result) {
3566: my %setters;
3567: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3568: my ($startblock,$endblock) =
3569: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
3570: if ($startblock && $endblock) {
3571: return 'B';
3572: }
3573: } else {
3574: my ($startblock,$endblock) =
3575: &Apache::loncommon::blockcheck(\%setters,'port');
3576: if ($startblock && $endblock) {
3577: return 'B';
3578: }
3579: }
3580: }
1.765 albertel 3581: if ($result eq 'ok') {
1.766 albertel 3582: return 'F';
1.765 albertel 3583: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 3584: return 'A';
1.765 albertel 3585: }
1.766 albertel 3586: return '';
1.765 albertel 3587: }
3588:
3589: sub get_portfolio_access {
1.767 albertel 3590: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
3591:
3592: if (!ref($access_hash)) {
3593: my $current_perms = &get_portfile_permissions($udom,$unum);
3594: my %access_controls = &get_access_controls($current_perms,$group,
3595: $file_name);
3596: $access_hash = $access_controls{$file_name};
3597: }
3598:
1.765 albertel 3599: my ($public,$guest,@domains,@users,@courses,@groups);
3600: my $now = time;
3601: if (ref($access_hash) eq 'HASH') {
3602: foreach my $key (keys(%{$access_hash})) {
3603: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
3604: if ($start > $now) {
3605: next;
3606: }
3607: if ($end && $end<$now) {
3608: next;
3609: }
3610: if ($scope eq 'public') {
3611: $public = $key;
3612: last;
3613: } elsif ($scope eq 'guest') {
3614: $guest = $key;
3615: } elsif ($scope eq 'domains') {
3616: push(@domains,$key);
3617: } elsif ($scope eq 'users') {
3618: push(@users,$key);
3619: } elsif ($scope eq 'course') {
3620: push(@courses,$key);
3621: } elsif ($scope eq 'group') {
3622: push(@groups,$key);
3623: }
3624: }
3625: if ($public) {
3626: return 'ok';
3627: }
3628: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3629: if ($guest) {
3630: return $guest;
3631: }
3632: } else {
3633: if (@domains > 0) {
3634: foreach my $domkey (@domains) {
3635: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
3636: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
3637: return 'ok';
3638: }
3639: }
3640: }
3641: }
3642: if (@users > 0) {
3643: foreach my $userkey (@users) {
3644: if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
3645: return 'ok';
3646: }
3647: }
3648: }
3649: my %roleshash;
3650: my @courses_and_groups = @courses;
3651: push(@courses_and_groups,@groups);
3652: if (@courses_and_groups > 0) {
3653: my (%allgroups,%allroles);
3654: my ($start,$end,$role,$sec,$group);
3655: foreach my $envkey (%env) {
1.811 albertel 3656: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 3657: my $cid = $2.'_'.$3;
3658: if ($1 eq 'gr') {
3659: $group = $4;
3660: $allgroups{$cid}{$group} = $env{$envkey};
3661: } else {
3662: if ($4 eq '') {
3663: $sec = 'none';
3664: } else {
3665: $sec = $4;
3666: }
3667: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3668: }
1.811 albertel 3669: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 3670: my $cid = $2.'_'.$3;
3671: if ($4 eq '') {
3672: $sec = 'none';
3673: } else {
3674: $sec = $4;
3675: }
3676: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3677: }
3678: }
3679: if (keys(%allroles) == 0) {
3680: return;
3681: }
3682: foreach my $key (@courses_and_groups) {
3683: my %content = %{$$access_hash{$key}};
3684: my $cnum = $content{'number'};
3685: my $cdom = $content{'domain'};
3686: my $cid = $cdom.'_'.$cnum;
3687: if (!exists($allroles{$cid})) {
3688: next;
3689: }
3690: foreach my $role_id (keys(%{$content{'roles'}})) {
3691: my @sections = @{$content{'roles'}{$role_id}{'section'}};
3692: my @groups = @{$content{'roles'}{$role_id}{'group'}};
3693: my @status = @{$content{'roles'}{$role_id}{'access'}};
3694: my @roles = @{$content{'roles'}{$role_id}{'role'}};
3695: foreach my $role (keys(%{$allroles{$cid}})) {
3696: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
3697: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
3698: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
3699: if (grep/^all$/,@sections) {
3700: return 'ok';
3701: } else {
3702: if (grep/^$sec$/,@sections) {
3703: return 'ok';
3704: }
3705: }
3706: }
3707: }
3708: if (keys(%{$allgroups{$cid}}) == 0) {
3709: if (grep/^none$/,@groups) {
3710: return 'ok';
3711: }
3712: } else {
3713: if (grep/^all$/,@groups) {
3714: return 'ok';
3715: }
3716: foreach my $group (keys(%{$allgroups{$cid}})) {
3717: if (grep/^$group$/,@groups) {
3718: return 'ok';
3719: }
3720: }
3721: }
3722: }
3723: }
3724: }
3725: }
3726: }
3727: if ($guest) {
3728: return $guest;
3729: }
3730: }
3731: }
3732: return;
3733: }
3734:
3735: sub course_group_datechecker {
3736: my ($dates,$now,$status) = @_;
3737: my ($start,$end) = split(/\./,$dates);
3738: if (!$start && !$end) {
3739: return 'ok';
3740: }
3741: if (grep/^active$/,@{$status}) {
3742: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
3743: return 'ok';
3744: }
3745: }
3746: if (grep/^previous$/,@{$status}) {
3747: if ($end > $now ) {
3748: return 'ok';
3749: }
3750: }
3751: if (grep/^future$/,@{$status}) {
3752: if ($start > $now) {
3753: return 'ok';
3754: }
3755: }
3756: return;
3757: }
3758:
3759: sub parse_portfolio_url {
3760: my ($url) = @_;
3761:
3762: my ($type,$udom,$unum,$group,$file_name);
3763:
1.823 albertel 3764: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 3765: $type = 1;
3766: $udom = $1;
3767: $unum = $2;
3768: $file_name = $3;
1.823 albertel 3769: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 3770: $type = 2;
3771: $udom = $1;
3772: $unum = $2;
3773: $group = $3;
3774: $file_name = $3.'/'.$4;
3775: }
3776: if (wantarray) {
3777: return ($type,$udom,$unum,$file_name,$group);
3778: }
3779: return $type;
3780: }
3781:
3782: sub is_portfolio_url {
3783: my ($url) = @_;
3784: return scalar(&parse_portfolio_url($url));
3785: }
3786:
1.798 raeburn 3787: sub is_portfolio_file {
3788: my ($file) = @_;
1.820 raeburn 3789: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 3790: return 1;
3791: }
3792: return;
3793: }
3794:
3795:
1.341 www 3796: # ---------------------------------------------- Custom access rule evaluation
3797:
3798: sub customaccess {
3799: my ($priv,$uri)=@_;
1.807 albertel 3800: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 3801: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 3802: $udom = &LONCAPA::clean_domain($udom);
3803: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 3804: my $access=0;
1.800 albertel 3805: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
3806: my ($effect,$realm,$role)=split(/\:/,$right);
1.343 www 3807: if ($role) {
3808: if ($role ne $urole) { next; }
3809: }
1.800 albertel 3810: foreach my $scope (split(/\s*\,\s*/,$realm)) {
3811: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343 www 3812: if ($tdom) {
3813: if ($tdom ne $udom) { next; }
3814: }
3815: if ($tcrs) {
3816: if ($tcrs ne $ucrs) { next; }
3817: }
3818: if ($tsec) {
3819: if ($tsec ne $usec) { next; }
3820: }
3821: $access=($effect eq 'allow');
3822: last;
1.342 www 3823: }
1.402 bowersj2 3824: if ($realm eq '' && $role eq '') {
3825: $access=($effect eq 'allow');
3826: }
1.341 www 3827: }
3828: return $access;
3829: }
3830:
1.103 harris41 3831: # ------------------------------------------------- Check for a user privilege
1.12 www 3832:
3833: sub allowed {
1.810 raeburn 3834: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 3835: my $ver_orguri=$uri;
1.439 www 3836: $uri=&deversion($uri);
1.152 www 3837: my $orguri=$uri;
1.52 www 3838: $uri=&declutter($uri);
1.809 raeburn 3839:
1.810 raeburn 3840: if ($priv eq 'evb') {
3841: # Evade communication block restrictions for specified role in a course
3842: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
3843: return $1;
3844: } else {
3845: return;
3846: }
3847: }
3848:
1.620 albertel 3849: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 3850: # Free bre access to adm and meta resources
1.775 albertel 3851: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 3852: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
3853: && ($priv eq 'bre')) {
1.14 www 3854: return 'F';
1.159 www 3855: }
3856:
1.545 banghart 3857: # Free bre access to user's own portfolio contents
1.714 raeburn 3858: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 3859: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 3860: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 3861: my %setters;
3862: my ($startblock,$endblock) =
3863: &Apache::loncommon::blockcheck(\%setters,'port');
3864: if ($startblock && $endblock) {
3865: return 'B';
3866: } else {
3867: return 'F';
3868: }
1.545 banghart 3869: }
3870:
1.762 raeburn 3871: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 3872: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
3873: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
3874: if (exists($env{'request.course.id'})) {
3875: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3876: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3877: if (($domain eq $cdom) && ($name eq $cnum)) {
3878: my $courseprivid=$env{'request.course.id'};
3879: $courseprivid=~s/\_/\//;
3880: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
3881: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
3882: return $1;
1.762 raeburn 3883: } else {
3884: if ($env{'request.course.sec'}) {
3885: $courseprivid.='/'.$env{'request.course.sec'};
3886: }
3887: if ($env{'user.priv.'.$env{'request.role'}.'./'.
3888: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
3889: return $2;
3890: }
1.714 raeburn 3891: }
3892: }
3893: }
3894: }
3895:
1.159 www 3896: # Free bre to public access
3897:
3898: if ($priv eq 'bre') {
1.238 www 3899: my $copyright=&metadata($uri,'copyright');
1.620 albertel 3900: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 3901: return 'F';
3902: }
1.238 www 3903: if ($copyright eq 'priv') {
3904: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 3905: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 3906: return '';
3907: }
3908: }
3909: if ($copyright eq 'domain') {
3910: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 3911: unless (($env{'user.domain'} eq $1) ||
3912: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 3913: return '';
3914: }
1.262 matthew 3915: }
1.620 albertel 3916: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 3917: # Library role, so allow browsing of resources in this domain.
3918: return 'F';
1.238 www 3919: }
1.341 www 3920: if ($copyright eq 'custom') {
3921: unless (&customaccess($priv,$uri)) { return ''; }
3922: }
1.14 www 3923: }
1.264 matthew 3924: # Domain coordinator is trying to create a course
1.620 albertel 3925: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 3926: # uri is the requested domain in this case.
3927: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 3928: # a role of dc for the domain in question.
1.620 albertel 3929: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 3930: }
1.29 www 3931:
1.52 www 3932: my $thisallowed='';
3933: my $statecond=0;
3934: my $courseprivid='';
3935:
3936: # Course
3937:
1.620 albertel 3938: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 3939: $thisallowed.=$1;
3940: }
1.29 www 3941:
1.52 www 3942: # Domain
3943:
1.620 albertel 3944: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 3945: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 3946: $thisallowed.=$1;
3947: }
1.52 www 3948:
3949: # Course: uri itself is a course
1.66 www 3950: my $courseuri=$uri;
3951: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 3952: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 3953:
1.620 albertel 3954: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 3955: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 3956: $thisallowed.=$1;
3957: }
1.29 www 3958:
1.665 albertel 3959: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 3960: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 3961: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 3962: $thisallowed='';
1.671 raeburn 3963: my ($match)=&is_on_map($uri);
3964: if ($match) {
3965: if ($env{'user.priv.'.$env{'request.role'}.'./'}
3966: =~/\Q$priv\E\&([^\:]*)/) {
3967: $thisallowed.=$1;
3968: }
3969: } else {
1.705 albertel 3970: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 3971: if ($refuri) {
3972: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 3973: $thisallowed='F';
1.671 raeburn 3974: } else {
3975: $refuri=&declutter($refuri);
3976: my ($match) = &is_on_map($refuri);
3977: if ($match) {
3978: $thisallowed='F';
3979: }
1.669 raeburn 3980: }
1.671 raeburn 3981: }
3982: }
1.314 www 3983: }
1.492 albertel 3984:
1.766 albertel 3985: if ($priv eq 'bre'
3986: && $thisallowed ne 'F'
3987: && $thisallowed ne '2'
3988: && &is_portfolio_url($uri)) {
3989: $thisallowed = &portfolio_access($uri);
3990: }
3991:
1.52 www 3992: # Full access at system, domain or course-wide level? Exit.
1.29 www 3993:
3994: if ($thisallowed=~/F/) {
3995: return 'F';
3996: }
3997:
1.52 www 3998: # If this is generating or modifying users, exit with special codes
1.29 www 3999:
1.643 www 4000: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
4001: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 4002: my ($audom,$auname)=split('/',$uri);
1.643 www 4003: # no author name given, so this just checks on the general right to make a co-author in this domain
4004: unless ($auname) { return $thisallowed; }
4005: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 4006: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
4007: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
4008: ($audom ne $env{'request.role.domain'}))) { return ''; }
4009: }
1.52 www 4010: return $thisallowed;
4011: }
4012: #
1.103 harris41 4013: # Gathered so far: system, domain and course wide privileges
1.52 www 4014: #
4015: # Course: See if uri or referer is an individual resource that is part of
4016: # the course
4017:
1.620 albertel 4018: if ($env{'request.course.id'}) {
1.232 www 4019:
1.620 albertel 4020: $courseprivid=$env{'request.course.id'};
4021: if ($env{'request.course.sec'}) {
4022: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 4023: }
4024: $courseprivid=~s/\_/\//;
4025: my $checkreferer=1;
1.232 www 4026: my ($match,$cond)=&is_on_map($uri);
4027: if ($match) {
4028: $statecond=$cond;
1.620 albertel 4029: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4030: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4031: $thisallowed.=$1;
4032: $checkreferer=0;
4033: }
1.29 www 4034: }
1.83 www 4035:
1.148 www 4036: if ($checkreferer) {
1.620 albertel 4037: my $refuri=$env{'httpref.'.$orguri};
1.148 www 4038: unless ($refuri) {
1.800 albertel 4039: foreach my $key (keys(%env)) {
4040: if ($key=~/^httpref\..*\*/) {
4041: my $pattern=$key;
1.156 www 4042: $pattern=~s/^httpref\.\/res\///;
1.148 www 4043: $pattern=~s/\*/\[\^\/\]\+/g;
4044: $pattern=~s/\//\\\//g;
1.152 www 4045: if ($orguri=~/$pattern/) {
1.800 albertel 4046: $refuri=$env{$key};
1.148 www 4047: }
4048: }
1.191 harris41 4049: }
1.148 www 4050: }
1.232 www 4051:
1.148 www 4052: if ($refuri) {
1.152 www 4053: $refuri=&declutter($refuri);
1.232 www 4054: my ($match,$cond)=&is_on_map($refuri);
4055: if ($match) {
4056: my $refstatecond=$cond;
1.620 albertel 4057: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4058: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4059: $thisallowed.=$1;
1.53 www 4060: $uri=$refuri;
4061: $statecond=$refstatecond;
1.52 www 4062: }
4063: }
1.148 www 4064: }
1.29 www 4065: }
1.52 www 4066: }
1.29 www 4067:
1.52 www 4068: #
1.103 harris41 4069: # Gathered now: all privileges that could apply, and condition number
1.52 www 4070: #
4071: #
4072: # Full or no access?
4073: #
1.29 www 4074:
1.52 www 4075: if ($thisallowed=~/F/) {
4076: return 'F';
4077: }
1.29 www 4078:
1.52 www 4079: unless ($thisallowed) {
4080: return '';
4081: }
1.29 www 4082:
1.52 www 4083: # Restrictions exist, deal with them
4084: #
4085: # C:according to course preferences
4086: # R:according to resource settings
4087: # L:unless locked
4088: # X:according to user session state
4089: #
4090:
4091: # Possibly locked functionality, check all courses
1.54 www 4092: # Locks might take effect only after 10 minutes cache expiration for other
4093: # courses, and 2 minutes for current course
1.52 www 4094:
4095: my $envkey;
4096: if ($thisallowed=~/L/) {
1.620 albertel 4097: foreach $envkey (keys %env) {
1.54 www 4098: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
4099: my $courseid=$2;
4100: my $roleid=$1.'.'.$2;
1.92 www 4101: $courseid=~s/^\///;
1.54 www 4102: my $expiretime=600;
1.620 albertel 4103: if ($env{'request.role'} eq $roleid) {
1.54 www 4104: $expiretime=120;
4105: }
4106: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
4107: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 4108: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 4109: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 4110: }
1.620 albertel 4111: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
4112: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
4113: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
4114: &log($env{'user.domain'},$env{'user.name'},
4115: $env{'user.home'},
1.57 www 4116: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 4117: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4118: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4119: return '';
4120: }
4121: }
1.620 albertel 4122: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
4123: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
4124: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
4125: &log($env{'user.domain'},$env{'user.name'},
4126: $env{'user.home'},
1.57 www 4127: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 4128: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4129: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4130: return '';
4131: }
4132: }
4133: }
1.29 www 4134: }
1.52 www 4135: }
4136:
4137: #
4138: # Rest of the restrictions depend on selected course
4139: #
4140:
1.620 albertel 4141: unless ($env{'request.course.id'}) {
1.766 albertel 4142: if ($thisallowed eq 'A') {
4143: return 'A';
1.814 raeburn 4144: } elsif ($thisallowed eq 'B') {
4145: return 'B';
1.766 albertel 4146: } else {
4147: return '1';
4148: }
1.52 www 4149: }
1.29 www 4150:
1.52 www 4151: #
4152: # Now user is definitely in a course
4153: #
1.53 www 4154:
4155:
4156: # Course preferences
4157:
4158: if ($thisallowed=~/C/) {
1.620 albertel 4159: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4160: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
4161: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 4162: =~/\Q$rolecode\E/) {
1.689 albertel 4163: if ($priv ne 'pch') {
4164: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4165: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
4166: $env{'request.course.id'});
4167: }
1.237 www 4168: return '';
4169: }
4170:
1.620 albertel 4171: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 4172: =~/\Q$unamedom\E/) {
1.689 albertel 4173: if ($priv ne 'pch') {
4174: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
4175: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
4176: $env{'request.course.id'});
4177: }
1.54 www 4178: return '';
4179: }
1.53 www 4180: }
4181:
4182: # Resource preferences
4183:
4184: if ($thisallowed=~/R/) {
1.620 albertel 4185: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 4186: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 4187: if ($priv ne 'pch') {
4188: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4189: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
4190: }
4191: return '';
1.54 www 4192: }
1.53 www 4193: }
1.30 www 4194:
1.246 www 4195: # Restricted by state or randomout?
1.30 www 4196:
1.52 www 4197: if ($thisallowed=~/X/) {
1.620 albertel 4198: if ($env{'acc.randomout'}) {
1.579 albertel 4199: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 4200: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 4201: return '';
4202: }
1.247 www 4203: }
4204: if (&condval($statecond)) {
1.52 www 4205: return '2';
4206: } else {
4207: return '';
4208: }
4209: }
1.30 www 4210:
1.766 albertel 4211: if ($thisallowed eq 'A') {
4212: return 'A';
1.814 raeburn 4213: } elsif ($thisallowed eq 'B') {
4214: return 'B';
1.766 albertel 4215: }
1.52 www 4216: return 'F';
1.232 www 4217: }
4218:
1.710 albertel 4219: sub split_uri_for_cond {
4220: my $uri=&deversion(&declutter(shift));
4221: my @uriparts=split(/\//,$uri);
4222: my $filename=pop(@uriparts);
4223: my $pathname=join('/',@uriparts);
4224: return ($pathname,$filename);
4225: }
1.232 www 4226: # --------------------------------------------------- Is a resource on the map?
4227:
4228: sub is_on_map {
1.710 albertel 4229: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 4230: #Trying to find the conditional for the file
1.620 albertel 4231: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 4232: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 4233: if ($match) {
1.289 bowersj2 4234: return (1,$1);
4235: } else {
1.434 www 4236: return (0,0);
1.289 bowersj2 4237: }
1.12 www 4238: }
4239:
1.427 www 4240: # --------------------------------------------------------- Get symb from alias
4241:
4242: sub get_symb_from_alias {
4243: my $symb=shift;
4244: my ($map,$resid,$url)=&decode_symb($symb);
4245: # Already is a symb
4246: if ($url) { return $symb; }
4247: # Must be an alias
4248: my $aliassymb='';
4249: my %bighash;
1.620 albertel 4250: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 4251: &GDBM_READER(),0640)) {
4252: my $rid=$bighash{'mapalias_'.$symb};
4253: if ($rid) {
4254: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 4255: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
4256: $resid,$bighash{'src_'.$rid});
1.427 www 4257: }
4258: untie %bighash;
4259: }
4260: return $aliassymb;
4261: }
4262:
1.12 www 4263: # ----------------------------------------------------------------- Define Role
4264:
4265: sub definerole {
4266: if (allowed('mcr','/')) {
4267: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 4268: foreach my $role (split(':',$sysrole)) {
4269: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4270: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
4271: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
4272: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4273: return "refused:s:$crole&$cqual";
4274: }
4275: }
1.191 harris41 4276: }
1.800 albertel 4277: foreach my $role (split(':',$domrole)) {
4278: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4279: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
4280: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
4281: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 4282: return "refused:d:$crole&$cqual";
4283: }
4284: }
1.191 harris41 4285: }
1.800 albertel 4286: foreach my $role (split(':',$courole)) {
4287: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4288: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
4289: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
4290: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4291: return "refused:c:$crole&$cqual";
4292: }
4293: }
1.191 harris41 4294: }
1.620 albertel 4295: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4296: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 4297: "rolesdef_$rolename=".
4298: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 4299: return reply($command,$env{'user.home'});
1.12 www 4300: } else {
4301: return 'refused';
4302: }
1.105 harris41 4303: }
4304:
4305: # ---------------- Make a metadata query against the network of library servers
4306:
4307: sub metadata_query {
1.244 matthew 4308: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 4309: my %rhash;
1.845 albertel 4310: my %libserv = &all_library();
1.244 matthew 4311: my @server_list = (defined($server_array) ? @$server_array
4312: : keys(%libserv) );
4313: for my $server (@server_list) {
1.118 harris41 4314: unless ($custom or $customshow) {
4315: my $reply=&reply("querysend:".&escape($query),$server);
4316: $rhash{$server}=$reply;
4317: }
4318: else {
4319: my $reply=&reply("querysend:".&escape($query).':'.
4320: &escape($custom).':'.&escape($customshow),
4321: $server);
4322: $rhash{$server}=$reply;
4323: }
1.112 harris41 4324: }
1.118 harris41 4325: return \%rhash;
1.240 www 4326: }
4327:
4328: # ----------------------------------------- Send log queries and wait for reply
4329:
4330: sub log_query {
4331: my ($uname,$udom,$query,%filters)=@_;
4332: my $uhome=&homeserver($uname,$udom);
4333: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 4334: my $uhost=&hostname($uhome);
1.800 albertel 4335: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 4336: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
4337: $uhome);
1.479 albertel 4338: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 4339: return get_query_reply($queryid);
4340: }
4341:
1.818 raeburn 4342: # -------------------------- Update MySQL table for portfolio file
4343:
4344: sub update_portfolio_table {
1.821 raeburn 4345: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818 raeburn 4346: my $homeserver = &homeserver($uname,$udom);
4347: my $queryid=
1.821 raeburn 4348: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
4349: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 4350: my $reply = &get_query_reply($queryid);
4351: return $reply;
4352: }
4353:
1.508 raeburn 4354: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 4355:
4356: sub fetch_enrollment_query {
1.511 raeburn 4357: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 4358: my $homeserver;
1.547 raeburn 4359: my $maxtries = 1;
1.508 raeburn 4360: if ($context eq 'automated') {
4361: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 4362: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 4363: } else {
4364: $homeserver = &homeserver($cnum,$dom);
4365: }
1.838 albertel 4366: my $host=&hostname($homeserver);
1.506 raeburn 4367: my $cmd = '';
1.800 albertel 4368: foreach my $affiliate (keys %{$affiliatesref}) {
4369: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 4370: }
4371: $cmd =~ s/%%$//;
4372: $cmd = &escape($cmd);
4373: my $query = 'fetchenrollment';
1.620 albertel 4374: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 4375: unless ($queryid=~/^\Q$host\E\_/) {
4376: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
4377: return 'error: '.$queryid;
4378: }
1.506 raeburn 4379: my $reply = &get_query_reply($queryid);
1.547 raeburn 4380: my $tries = 1;
4381: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4382: $reply = &get_query_reply($queryid);
4383: $tries ++;
4384: }
1.526 raeburn 4385: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 4386: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 4387: } else {
1.515 raeburn 4388: my @responses = split/:/,$reply;
4389: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 4390: foreach my $line (@responses) {
4391: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 4392: $$replyref{$key} = $value;
4393: }
4394: } else {
1.506 raeburn 4395: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 4396: foreach my $line (@responses) {
4397: my ($key,$value) = split(/=/,$line);
1.506 raeburn 4398: $$replyref{$key} = $value;
4399: if ($value > 0) {
1.800 albertel 4400: foreach my $item (@{$$affiliatesref{$key}}) {
4401: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 4402: my $destname = $pathname.'/'.$filename;
4403: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 4404: if ($xml_classlist =~ /^error/) {
4405: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
4406: } else {
1.506 raeburn 4407: if ( open(FILE,">$destname") ) {
4408: print FILE &unescape($xml_classlist);
4409: close(FILE);
1.526 raeburn 4410: } else {
4411: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 4412: }
4413: }
4414: }
4415: }
4416: }
4417: }
4418: return 'ok';
4419: }
4420: return 'error';
4421: }
4422:
1.242 www 4423: sub get_query_reply {
4424: my $queryid=shift;
1.240 www 4425: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
4426: my $reply='';
4427: for (1..100) {
4428: sleep 2;
4429: if (-e $replyfile.'.end') {
1.448 albertel 4430: if (open(my $fh,$replyfile)) {
1.240 www 4431: $reply.=<$fh>;
1.448 albertel 4432: close($fh);
1.240 www 4433: } else { return 'error: reply_file_error'; }
1.242 www 4434: return &unescape($reply);
4435: }
1.240 www 4436: }
1.242 www 4437: return 'timeout:'.$queryid;
1.240 www 4438: }
4439:
4440: sub courselog_query {
1.241 www 4441: #
4442: # possible filters:
4443: # url: url or symb
4444: # username
4445: # domain
4446: # action: view, submit, grade
4447: # start: timestamp
4448: # end: timestamp
4449: #
1.240 www 4450: my (%filters)=@_;
1.620 albertel 4451: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 4452: if ($filters{'url'}) {
4453: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
4454: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
4455: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
4456: }
1.620 albertel 4457: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4458: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 4459: return &log_query($cname,$cdom,'courselog',%filters);
4460: }
4461:
4462: sub userlog_query {
1.858 raeburn 4463: #
4464: # possible filters:
4465: # action: log check role
4466: # start: timestamp
4467: # end: timestamp
4468: #
1.240 www 4469: my ($uname,$udom,%filters)=@_;
4470: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 4471: }
4472:
1.506 raeburn 4473: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
4474:
4475: sub auto_run {
1.508 raeburn 4476: my ($cnum,$cdom) = @_;
4477: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 4478: my $response = &reply('autorun:'.$cdom,$homeserver);
1.506 raeburn 4479: return $response;
4480: }
1.776 albertel 4481:
1.506 raeburn 4482: sub auto_get_sections {
1.508 raeburn 4483: my ($cnum,$cdom,$inst_coursecode) = @_;
4484: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 4485: my @secs = ();
1.511 raeburn 4486: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 4487: unless ($response eq 'refused') {
4488: @secs = split/:/,$response;
4489: }
4490: return @secs;
4491: }
1.776 albertel 4492:
1.506 raeburn 4493: sub auto_new_course {
1.508 raeburn 4494: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
4495: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 4496: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 4497: return $response;
4498: }
1.776 albertel 4499:
1.506 raeburn 4500: sub auto_validate_courseID {
1.508 raeburn 4501: my ($cnum,$cdom,$inst_course_id) = @_;
4502: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 4503: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 4504: return $response;
4505: }
1.776 albertel 4506:
1.506 raeburn 4507: sub auto_create_password {
1.508 raeburn 4508: my ($cnum,$cdom,$authparam) = @_;
4509: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 4510: my $create_passwd = 0;
4511: my $authchk = '';
1.511 raeburn 4512: my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506 raeburn 4513: if ($response eq 'refused') {
4514: $authchk = 'refused';
4515: } else {
4516: ($authparam,$create_passwd,$authchk) = split/:/,$response;
4517: }
4518: return ($authparam,$create_passwd,$authchk);
4519: }
4520:
1.706 raeburn 4521: sub auto_photo_permission {
4522: my ($cnum,$cdom,$students) = @_;
4523: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 4524: my ($outcome,$perm_reqd,$conditions) =
4525: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 4526: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4527: return (undef,undef);
4528: }
1.706 raeburn 4529: return ($outcome,$perm_reqd,$conditions);
4530: }
4531:
4532: sub auto_checkphotos {
4533: my ($uname,$udom,$pid) = @_;
4534: my $homeserver = &homeserver($uname,$udom);
4535: my ($result,$resulttype);
4536: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 4537: &escape($uname).':'.&escape($pid),
4538: $homeserver));
1.709 albertel 4539: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4540: return (undef,undef);
4541: }
1.706 raeburn 4542: if ($outcome) {
4543: ($result,$resulttype) = split(/:/,$outcome);
4544: }
4545: return ($result,$resulttype);
4546: }
4547:
4548: sub auto_photochoice {
4549: my ($cnum,$cdom) = @_;
4550: my $homeserver = &homeserver($cnum,$cdom);
4551: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 4552: &escape($cdom),
4553: $homeserver)));
1.709 albertel 4554: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4555: return (undef,undef);
4556: }
1.706 raeburn 4557: return ($update,$comment);
4558: }
4559:
4560: sub auto_photoupdate {
4561: my ($affiliatesref,$dom,$cnum,$photo) = @_;
4562: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 4563: my $host=&hostname($homeserver);
1.706 raeburn 4564: my $cmd = '';
4565: my $maxtries = 1;
1.800 albertel 4566: foreach my $affiliate (keys(%{$affiliatesref})) {
4567: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 4568: }
4569: $cmd =~ s/%%$//;
4570: $cmd = &escape($cmd);
4571: my $query = 'institutionalphotos';
4572: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
4573: unless ($queryid=~/^\Q$host\E\_/) {
4574: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
4575: return 'error: '.$queryid;
4576: }
4577: my $reply = &get_query_reply($queryid);
4578: my $tries = 1;
4579: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4580: $reply = &get_query_reply($queryid);
4581: $tries ++;
4582: }
4583: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
4584: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
4585: } else {
4586: my @responses = split(/:/,$reply);
4587: my $outcome = shift(@responses);
4588: foreach my $item (@responses) {
4589: my ($key,$value) = split(/=/,$item);
4590: $$photo{$key} = $value;
4591: }
4592: return $outcome;
4593: }
4594: return 'error';
4595: }
4596:
1.521 raeburn 4597: sub auto_instcode_format {
1.793 albertel 4598: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
4599: $cat_order) = @_;
1.521 raeburn 4600: my $courses = '';
1.772 raeburn 4601: my @homeservers;
1.521 raeburn 4602: if ($caller eq 'global') {
1.841 albertel 4603: my %servers = &get_servers($codedom,'library');
4604: foreach my $tryserver (keys(%servers)) {
4605: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4606: push(@homeservers,$tryserver);
4607: }
1.584 raeburn 4608: }
1.521 raeburn 4609: } else {
1.772 raeburn 4610: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 4611: }
1.793 albertel 4612: foreach my $code (keys(%{$instcodes})) {
4613: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 4614: }
4615: chop($courses);
1.772 raeburn 4616: my $ok_response = 0;
4617: my $response;
4618: while (@homeservers > 0 && $ok_response == 0) {
4619: my $server = shift(@homeservers);
4620: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
4621: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
4622: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.793 albertel 4623: split/:/,$response;
1.772 raeburn 4624: %{$codes} = (%{$codes},&str2hash($codes_str));
4625: push(@{$codetitles},&str2array($codetitles_str));
4626: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
4627: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
4628: $ok_response = 1;
4629: }
4630: }
4631: if ($ok_response) {
1.521 raeburn 4632: return 'ok';
1.772 raeburn 4633: } else {
4634: return $response;
1.521 raeburn 4635: }
4636: }
4637:
1.792 raeburn 4638: sub auto_instcode_defaults {
4639: my ($domain,$returnhash,$code_order) = @_;
4640: my @homeservers;
1.841 albertel 4641:
4642: my %servers = &get_servers($domain,'library');
4643: foreach my $tryserver (keys(%servers)) {
4644: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4645: push(@homeservers,$tryserver);
4646: }
1.792 raeburn 4647: }
1.841 albertel 4648:
1.792 raeburn 4649: my $response;
1.841 albertel 4650: foreach my $server (@homeservers) {
1.792 raeburn 4651: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 4652: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
4653:
4654: foreach my $pair (split(/\&/,$response)) {
4655: my ($name,$value)=split(/\=/,$pair);
4656: if ($name eq 'code_order') {
4657: @{$code_order} = split(/\&/,&unescape($value));
4658: } else {
4659: $returnhash->{&unescape($name)}=&unescape($value);
4660: }
4661: }
4662: return 'ok';
1.792 raeburn 4663: }
1.841 albertel 4664:
4665: return $response;
1.792 raeburn 4666: }
4667:
1.777 albertel 4668: sub auto_validate_class_sec {
1.773 raeburn 4669: my ($cdom,$cnum,$owner,$inst_class) = @_;
4670: my $homeserver = &homeserver($cnum,$cdom);
4671: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774 banghart 4672: &escape($owner).':'.$cdom,$homeserver);
1.773 raeburn 4673: return $response;
4674: }
4675:
1.679 raeburn 4676: # ------------------------------------------------------- Course Group routines
4677:
4678: sub get_coursegroups {
1.809 raeburn 4679: my ($cdom,$cnum,$group,$namespace) = @_;
4680: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 4681: }
4682:
1.679 raeburn 4683: sub modify_coursegroup {
4684: my ($cdom,$cnum,$groupsettings) = @_;
4685: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
4686: }
4687:
1.809 raeburn 4688: sub toggle_coursegroup_status {
4689: my ($cdom,$cnum,$group,$action) = @_;
4690: my ($from_namespace,$to_namespace);
4691: if ($action eq 'delete') {
4692: $from_namespace = 'coursegroups';
4693: $to_namespace = 'deleted_groups';
4694: } else {
4695: $from_namespace = 'deleted_groups';
4696: $to_namespace = 'coursegroups';
4697: }
4698: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 4699: if (my $tmp = &error(%curr_group)) {
4700: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
4701: return ('read error',$tmp);
4702: } else {
4703: my %savedsettings = %curr_group;
1.809 raeburn 4704: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 4705: my $deloutcome;
4706: if ($result eq 'ok') {
1.809 raeburn 4707: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 4708: } else {
4709: return ('write error',$result);
4710: }
4711: if ($deloutcome eq 'ok') {
4712: return 'ok';
4713: } else {
4714: return ('delete error',$deloutcome);
4715: }
4716: }
4717: }
4718:
1.679 raeburn 4719: sub modify_group_roles {
4720: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
4721: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
4722: my $role = 'gr/'.&escape($userprivs);
4723: my ($uname,$udom) = split(/:/,$user);
4724: my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684 raeburn 4725: if ($result eq 'ok') {
4726: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
4727: }
1.679 raeburn 4728: return $result;
4729: }
4730:
4731: sub modify_coursegroup_membership {
4732: my ($cdom,$cnum,$membership) = @_;
4733: my $result = &put('groupmembership',$membership,$cdom,$cnum);
4734: return $result;
4735: }
4736:
1.682 raeburn 4737: sub get_active_groups {
4738: my ($udom,$uname,$cdom,$cnum) = @_;
4739: my $now = time;
4740: my %groups = ();
4741: foreach my $key (keys(%env)) {
1.811 albertel 4742: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 4743: my ($start,$end) = split(/\./,$env{$key});
4744: if (($end!=0) && ($end<$now)) { next; }
4745: if (($start!=0) && ($start>$now)) { next; }
4746: if ($1 eq $cdom && $2 eq $cnum) {
4747: $groups{$3} = $env{$key} ;
4748: }
4749: }
4750: }
4751: return %groups;
4752: }
4753:
1.683 raeburn 4754: sub get_group_membership {
4755: my ($cdom,$cnum,$group) = @_;
4756: return(&dump('groupmembership',$cdom,$cnum,$group));
4757: }
4758:
4759: sub get_users_groups {
4760: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 4761: my @usersgroups;
1.683 raeburn 4762: my $cachetime=1800;
4763:
4764: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 4765: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
4766: if (defined($cached)) {
1.734 albertel 4767: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 4768: } else {
4769: $grouplist = '';
1.816 raeburn 4770: my $courseurl = &courseid_to_courseurl($courseid);
4771: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 4772: my $access_end = $env{'course.'.$courseid.
4773: '.default_enrollment_end_date'};
4774: my $now = time;
4775: foreach my $key (keys(%roleshash)) {
4776: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
4777: my $group = $1;
4778: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
4779: my $start = $2;
4780: my $end = $1;
4781: if ($start == -1) { next; } # deleted from group
4782: if (($start!=0) && ($start>$now)) { next; }
4783: if (($end!=0) && ($end<$now)) {
4784: if ($access_end && $access_end < $now) {
4785: if ($access_end - $end < 86400) {
4786: push(@usersgroups,$group);
1.733 raeburn 4787: }
4788: }
1.817 raeburn 4789: next;
1.733 raeburn 4790: }
1.817 raeburn 4791: push(@usersgroups,$group);
1.683 raeburn 4792: }
4793: }
4794: }
1.817 raeburn 4795: @usersgroups = &sort_course_groups($courseid,@usersgroups);
4796: $grouplist = join(':',@usersgroups);
4797: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 4798: }
1.733 raeburn 4799: return @usersgroups;
1.683 raeburn 4800: }
4801:
4802: sub devalidate_getgroups_cache {
4803: my ($udom,$uname,$cdom,$cnum)=@_;
4804: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 4805:
1.683 raeburn 4806: my $hashid="$udom:$uname:$courseid";
4807: &devalidate_cache_new('getgroups',$hashid);
4808: }
4809:
1.12 www 4810: # ------------------------------------------------------------------ Plain Text
4811:
4812: sub plaintext {
1.742 raeburn 4813: my ($short,$type,$cid) = @_;
1.758 albertel 4814: if ($short =~ /^cr/) {
4815: return (split('/',$short))[-1];
4816: }
1.742 raeburn 4817: if (!defined($cid)) {
4818: $cid = $env{'request.course.id'};
4819: }
4820: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
4821: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
4822: '.plaintext'});
4823: }
4824: my %rolenames = (
4825: Course => 'std',
4826: Group => 'alt1',
4827: );
4828: if (defined($type) &&
4829: defined($rolenames{$type}) &&
4830: defined($prp{$short}{$rolenames{$type}})) {
4831: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
4832: } else {
4833: return &Apache::lonlocal::mt($prp{$short}{'std'});
4834: }
1.12 www 4835: }
4836:
4837: # ----------------------------------------------------------------- Assign Role
4838:
4839: sub assignrole {
1.357 www 4840: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21 www 4841: my $mrole;
4842: if ($role =~ /^cr\//) {
1.393 www 4843: my $cwosec=$url;
1.811 albertel 4844: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 4845: unless (&allowed('ccr',$cwosec)) {
1.104 www 4846: &logthis('Refused custom assignrole: '.
4847: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 4848: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 4849: return 'refused';
4850: }
1.21 www 4851: $mrole='cr';
1.678 raeburn 4852: } elsif ($role =~ /^gr\//) {
4853: my $cwogrp=$url;
1.811 albertel 4854: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 4855: unless (&allowed('mdg',$cwogrp)) {
4856: &logthis('Refused group assignrole: '.
4857: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4858: $env{'user.name'}.' at '.$env{'user.domain'});
4859: return 'refused';
4860: }
4861: $mrole='gr';
1.21 www 4862: } else {
1.82 www 4863: my $cwosec=$url;
1.811 albertel 4864: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373 www 4865: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
1.104 www 4866: &logthis('Refused assignrole: '.
4867: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 4868: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 4869: return 'refused';
4870: }
1.21 www 4871: $mrole=$role;
4872: }
1.620 albertel 4873: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 4874: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 4875: if ($end) { $command.='_'.$end; }
1.21 www 4876: if ($start) {
4877: if ($end) {
1.81 www 4878: $command.='_'.$start;
1.21 www 4879: } else {
1.81 www 4880: $command.='_0_'.$start;
1.21 www 4881: }
4882: }
1.739 raeburn 4883: my $origstart = $start;
4884: my $origend = $end;
1.357 www 4885: # actually delete
4886: if ($deleteflag) {
1.373 www 4887: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 4888: # modify command to delete the role
1.620 albertel 4889: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 4890: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 4891: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 4892: # set start and finish to negative values for userrolelog
4893: $start=-1;
4894: $end=-1;
4895: }
4896: }
4897: # send command
1.349 www 4898: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 4899: # log new user role if status is ok
1.349 www 4900: if ($answer eq 'ok') {
1.663 raeburn 4901: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 4902: # for course roles, perform group memberships changes triggered by role change.
4903: unless ($role =~ /^gr/) {
4904: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
4905: $origstart);
4906: }
1.349 www 4907: }
4908: return $answer;
1.169 harris41 4909: }
4910:
4911: # -------------------------------------------------- Modify user authentication
1.197 www 4912: # Overrides without validation
4913:
1.169 harris41 4914: sub modifyuserauth {
4915: my ($udom,$uname,$umode,$upass)=@_;
4916: my $uhome=&homeserver($uname,$udom);
1.197 www 4917: unless (&allowed('mau',$udom)) { return 'refused'; }
4918: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 4919: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4920: ' in domain '.$env{'request.role.domain'});
1.169 harris41 4921: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
4922: &escape($upass),$uhome);
1.620 albertel 4923: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 4924: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
4925: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
4926: &log($udom,,$uname,$uhome,
1.620 albertel 4927: 'Authentication changed by '.$env{'user.domain'}.', '.
4928: $env{'user.name'}.', '.$umode.
1.197 www 4929: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 4930: unless ($reply eq 'ok') {
1.197 www 4931: &logthis('Authentication mode error: '.$reply);
1.169 harris41 4932: return 'error: '.$reply;
4933: }
1.170 harris41 4934: return 'ok';
1.80 www 4935: }
4936:
1.81 www 4937: # --------------------------------------------------------------- Modify a user
1.80 www 4938:
1.81 www 4939: sub modifyuser {
1.206 matthew 4940: my ($udom, $uname, $uid,
4941: $umode, $upass, $first,
4942: $middle, $last, $gene,
1.387 www 4943: $forceid, $desiredhome, $email)=@_;
1.807 albertel 4944: $udom= &LONCAPA::clean_domain($udom);
4945: $uname=&LONCAPA::clean_username($uname);
1.81 www 4946: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 4947: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 4948: $last.', '.$gene.'(forceid: '.$forceid.')'.
4949: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
4950: ' desiredhome not specified').
1.620 albertel 4951: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4952: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 4953: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 4954: # ----------------------------------------------------------------- Create User
1.406 albertel 4955: if (($uhome eq 'no_host') &&
4956: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 4957: my $unhome='';
1.844 albertel 4958: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 4959: $unhome = $desiredhome;
1.620 albertel 4960: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
4961: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 4962: } else { # load balancing routine for determining $unhome
1.81 www 4963: my $loadm=10000000;
1.841 albertel 4964: my %servers = &get_servers($udom,'library');
4965: foreach my $tryserver (keys(%servers)) {
4966: my $answer=reply('load',$tryserver);
4967: if (($answer=~/\d+/) && ($answer<$loadm)) {
4968: $loadm=$answer;
4969: $unhome=$tryserver;
4970: }
1.80 www 4971: }
4972: }
4973: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 4974: return 'error: unable to find a home server for '.$uname.
4975: ' in domain '.$udom;
1.80 www 4976: }
4977: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
4978: &escape($upass),$unhome);
4979: unless ($reply eq 'ok') {
4980: return 'error: '.$reply;
4981: }
1.230 stredwic 4982: $uhome=&homeserver($uname,$udom,'true');
1.80 www 4983: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 4984: return 'error: unable verify users home machine.';
1.80 www 4985: }
1.209 matthew 4986: } # End of creation of new user
1.80 www 4987: # ---------------------------------------------------------------------- Add ID
4988: if ($uid) {
4989: $uid=~tr/A-Z/a-z/;
4990: my %uidhash=&idrget($udom,$uname);
1.196 www 4991: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
4992: && (!$forceid)) {
1.80 www 4993: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 4994: return 'error: user id "'.$uid.'" does not match '.
4995: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 4996: }
4997: } else {
4998: &idput($udom,($uname => $uid));
4999: }
5000: }
5001: # -------------------------------------------------------------- Add names, etc
1.313 matthew 5002: my @tmp=&get('environment',
1.134 albertel 5003: ['firstname','middlename','lastname','generation'],
5004: $udom,$uname);
1.313 matthew 5005: my %names;
5006: if ($tmp[0] =~ m/^error:.*/) {
5007: %names=();
5008: } else {
5009: %names = @tmp;
5010: }
1.388 www 5011: #
5012: # Make sure to not trash student environment if instructor does not bother
5013: # to supply name and email information
5014: #
5015: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 5016: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 5017: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 5018: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 5019: if ($email) {
5020: $email=~s/[^\w\@\.\-\,]//gs;
5021: if ($email=~/\@/) { $names{'notification'} = $email;
5022: $names{'critnotification'} = $email;
5023: $names{'permanentemail'} = $email; }
5024: }
1.134 albertel 5025: my $reply = &put('environment', \%names, $udom,$uname);
5026: if ($reply ne 'ok') { return 'error: '.$reply; }
1.680 www 5027: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81 www 5028: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 5029: $umode.', '.$first.', '.$middle.', '.
5030: $last.', '.$gene.' by '.
1.620 albertel 5031: $env{'user.name'}.' at '.$env{'user.domain'});
1.134 albertel 5032: return 'ok';
1.80 www 5033: }
5034:
1.81 www 5035: # -------------------------------------------------------------- Modify student
1.80 www 5036:
1.81 www 5037: sub modifystudent {
5038: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515 raeburn 5039: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455 albertel 5040: if (!$cid) {
1.620 albertel 5041: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5042: return 'not_in_class';
5043: }
1.80 www 5044: }
5045: # --------------------------------------------------------------- Make the user
1.81 www 5046: my $reply=&modifyuser
1.209 matthew 5047: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 5048: $desiredhome,$email);
1.80 www 5049: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 5050: # This will cause &modify_student_enrollment to get the uid from the
5051: # students environment
5052: $uid = undef if (!$forceid);
1.455 albertel 5053: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515 raeburn 5054: $gene,$usec,$end,$start,$type,$locktype,$cid);
1.297 matthew 5055: return $reply;
5056: }
5057:
5058: sub modify_student_enrollment {
1.515 raeburn 5059: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455 albertel 5060: my ($cdom,$cnum,$chome);
5061: if (!$cid) {
1.620 albertel 5062: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5063: return 'not_in_class';
5064: }
1.620 albertel 5065: $cdom=$env{'course.'.$cid.'.domain'};
5066: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 5067: } else {
5068: ($cdom,$cnum)=split(/_/,$cid);
5069: }
1.620 albertel 5070: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 5071: if (!$chome) {
1.457 raeburn 5072: $chome=&homeserver($cnum,$cdom);
1.297 matthew 5073: }
1.455 albertel 5074: if (!$chome) { return 'unknown_course'; }
1.297 matthew 5075: # Make sure the user exists
1.81 www 5076: my $uhome=&homeserver($uname,$udom);
5077: if (($uhome eq '') || ($uhome eq 'no_host')) {
5078: return 'error: no such user';
5079: }
1.297 matthew 5080: # Get student data if we were not given enough information
5081: if (!defined($first) || $first eq '' ||
5082: !defined($last) || $last eq '' ||
5083: !defined($uid) || $uid eq '' ||
5084: !defined($middle) || $middle eq '' ||
5085: !defined($gene) || $gene eq '') {
1.294 matthew 5086: # They did not supply us with enough data to enroll the student, so
5087: # we need to pick up more information.
1.297 matthew 5088: my %tmp = &get('environment',
1.294 matthew 5089: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 5090: ,$udom,$uname);
5091:
1.800 albertel 5092: #foreach my $key (keys(%tmp)) {
5093: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 5094: #}
1.294 matthew 5095: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
5096: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
5097: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 5098: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 5099: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
5100: }
1.556 albertel 5101: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 5102: my $reply=cput('classlist',
5103: {"$uname:$udom" =>
1.515 raeburn 5104: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 5105: $cdom,$cnum);
1.81 www 5106: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
5107: return 'error: '.$reply;
1.652 albertel 5108: } else {
5109: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 5110: }
1.297 matthew 5111: # Add student role to user
1.83 www 5112: my $uurl='/'.$cid;
1.81 www 5113: $uurl=~s/\_/\//g;
5114: if ($usec) {
5115: $uurl.='/'.$usec;
5116: }
5117: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21 www 5118: }
5119:
1.556 albertel 5120: sub format_name {
5121: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
5122: my $name;
5123: if ($first ne 'lastname') {
5124: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
5125: } else {
5126: if ($lastname=~/\S/) {
5127: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
5128: $name=~s/\s+,/,/;
5129: } else {
5130: $name.= $firstname.' '.$middlename.' '.$generation;
5131: }
5132: }
5133: $name=~s/^\s+//;
5134: $name=~s/\s+$//;
5135: $name=~s/\s+/ /g;
5136: return $name;
5137: }
5138:
1.84 www 5139: # ------------------------------------------------- Write to course preferences
5140:
5141: sub writecoursepref {
5142: my ($courseid,%prefs)=@_;
5143: $courseid=~s/^\///;
5144: $courseid=~s/\_/\//g;
5145: my ($cdomain,$cnum)=split(/\//,$courseid);
5146: my $chome=homeserver($cnum,$cdomain);
5147: if (($chome eq '') || ($chome eq 'no_host')) {
5148: return 'error: no such course';
5149: }
5150: my $cstring='';
1.800 albertel 5151: foreach my $pref (keys(%prefs)) {
5152: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 5153: }
1.84 www 5154: $cstring=~s/\&$//;
5155: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
5156: }
5157:
5158: # ---------------------------------------------------------- Make/modify course
5159:
5160: sub createcourse {
1.741 raeburn 5161: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
5162: $course_owner,$crstype)=@_;
1.84 www 5163: $url=&declutter($url);
5164: my $cid='';
1.264 matthew 5165: unless (&allowed('ccc',$udom)) {
1.84 www 5166: return 'refused';
5167: }
5168: # ------------------------------------------------------------------- Create ID
1.674 www 5169: my $uname=int(1+rand(9)).
5170: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
5171: substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84 www 5172: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
5173: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 5174: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 5175: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5176: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
5177: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 5178: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5179: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5180: return 'error: unable to generate unique course-ID';
5181: }
5182: }
1.264 matthew 5183: # ------------------------------------------------ Check supplied server name
1.620 albertel 5184: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845 albertel 5185: if (! &is_library($course_server)) {
1.264 matthew 5186: return 'error:bad server name '.$course_server;
5187: }
1.84 www 5188: # ------------------------------------------------------------- Make the course
5189: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 5190: $course_server);
1.84 www 5191: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 5192: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5193: if (($uhome eq '') || ($uhome eq 'no_host')) {
5194: return 'error: no such course';
5195: }
1.271 www 5196: # ----------------------------------------------------------------- Course made
1.516 raeburn 5197: # log existence
5198: &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741 raeburn 5199: ':'.&escape($inst_code).':'.&escape($course_owner).':'.
5200: &escape($crstype),$uhome);
1.358 www 5201: &flushcourselogs();
5202: # set toplevel url
1.271 www 5203: my $topurl=$url;
5204: unless ($nonstandard) {
5205: # ------------------------------------------ For standard courses, make top url
5206: my $mapurl=&clutter($url);
1.278 www 5207: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 5208: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 5209: <map>
5210: <resource id="1" type="start"></resource>
5211: <resource id="2" src="$mapurl"></resource>
5212: <resource id="3" type="finish"></resource>
5213: <link index="1" from="1" to="2"></link>
5214: <link index="2" from="2" to="3"></link>
5215: </map>
5216: ENDINITMAP
5217: $topurl=&declutter(
1.638 albertel 5218: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 5219: );
5220: }
5221: # ----------------------------------------------------------- Write preferences
1.84 www 5222: &writecoursepref($udom.'_'.$uname,
5223: ('description' => $description,
1.271 www 5224: 'url' => $topurl));
1.84 www 5225: return '/'.$udom.'/'.$uname;
5226: }
5227:
1.813 albertel 5228: sub is_course {
5229: my ($cdom,$cnum) = @_;
5230: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
5231: undef,'.');
5232: if (exists($courses{$cdom.'_'.$cnum})) {
5233: return 1;
5234: }
5235: return 0;
5236: }
5237:
1.21 www 5238: # ---------------------------------------------------------- Assign Custom Role
5239:
5240: sub assigncustomrole {
1.357 www 5241: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21 www 5242: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357 www 5243: $end,$start,$deleteflag);
1.21 www 5244: }
5245:
5246: # ----------------------------------------------------------------- Revoke Role
5247:
5248: sub revokerole {
1.357 www 5249: my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21 www 5250: my $now=time;
1.357 www 5251: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21 www 5252: }
5253:
5254: # ---------------------------------------------------------- Revoke Custom Role
5255:
5256: sub revokecustomrole {
1.357 www 5257: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21 www 5258: my $now=time;
1.357 www 5259: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
5260: $deleteflag);
1.17 www 5261: }
5262:
1.533 banghart 5263: # ------------------------------------------------------------ Disk usage
1.535 albertel 5264: sub diskusage {
1.533 banghart 5265: my ($udom,$uname,$directoryRoot)=@_;
5266: $directoryRoot =~ s/\/$//;
1.535 albertel 5267: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514 albertel 5268: return $listing;
1.512 banghart 5269: }
5270:
1.566 banghart 5271: sub is_locked {
5272: my ($file_name, $domain, $user) = @_;
5273: my @check;
5274: my $is_locked;
5275: push @check, $file_name;
1.613 albertel 5276: my %locked = &get('file_permissions',\@check,
1.620 albertel 5277: $env{'user.domain'},$env{'user.name'});
1.615 albertel 5278: my ($tmp)=keys(%locked);
5279: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 5280:
1.566 banghart 5281: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 5282: $is_locked = 'false';
5283: foreach my $entry (@{$locked{$file_name}}) {
5284: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 5285: $is_locked = 'true';
5286: last;
1.745 raeburn 5287: }
5288: }
1.566 banghart 5289: } else {
5290: $is_locked = 'false';
5291: }
5292: }
5293:
1.759 albertel 5294: sub declutter_portfile {
5295: my ($file) = @_;
1.833 albertel 5296: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 5297: return $file;
5298: }
5299:
1.559 banghart 5300: # ------------------------------------------------------------- Mark as Read Only
5301:
5302: sub mark_as_readonly {
5303: my ($domain,$user,$files,$what) = @_;
1.613 albertel 5304: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5305: my ($tmp)=keys(%current_permissions);
5306: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 5307: foreach my $file (@{$files}) {
1.759 albertel 5308: $file = &declutter_portfile($file);
1.561 banghart 5309: push(@{$current_permissions{$file}},$what);
1.559 banghart 5310: }
1.613 albertel 5311: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 5312: return;
5313: }
5314:
1.572 banghart 5315: # ------------------------------------------------------------Save Selected Files
5316:
5317: sub save_selected_files {
5318: my ($user, $path, @files) = @_;
5319: my $filename = $user."savedfiles";
1.573 banghart 5320: my @other_files = &files_not_in_path($user, $path);
1.574 banghart 5321: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 5322: foreach my $file (@files) {
1.620 albertel 5323: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 5324: }
5325: foreach my $file (@other_files) {
1.574 banghart 5326: print (OUT $file."\n");
1.572 banghart 5327: }
1.574 banghart 5328: close (OUT);
1.572 banghart 5329: return 'ok';
5330: }
5331:
1.574 banghart 5332: sub clear_selected_files {
5333: my ($user) = @_;
5334: my $filename = $user."savedfiles";
5335: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5336: print (OUT undef);
5337: close (OUT);
5338: return ("ok");
5339: }
5340:
1.572 banghart 5341: sub files_in_path {
5342: my ($user, $path) = @_;
5343: my $filename = $user."savedfiles";
5344: my %return_files;
1.574 banghart 5345: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 5346: while (my $line_in = <IN>) {
1.574 banghart 5347: chomp ($line_in);
5348: my @paths_and_file = split (m!/!, $line_in);
5349: my $file_part = pop (@paths_and_file);
5350: my $path_part = join ('/', @paths_and_file);
1.573 banghart 5351: $path_part.='/';
5352: my $path_and_file = $path_part.$file_part;
5353: if ($path_part eq $path) {
5354: $return_files{$file_part}= 'selected';
5355: }
5356: }
1.574 banghart 5357: close (IN);
5358: return (\%return_files);
1.572 banghart 5359: }
5360:
5361: # called in portfolio select mode, to show files selected NOT in current directory
5362: sub files_not_in_path {
5363: my ($user, $path) = @_;
5364: my $filename = $user."savedfiles";
5365: my @return_files;
5366: my $path_part;
1.800 albertel 5367: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5368: while (my $line = <IN>) {
1.572 banghart 5369: #ok, I know it's clunky, but I want it to work
1.800 albertel 5370: my @paths_and_file = split(m|/|, $line);
5371: my $file_part = pop(@paths_and_file);
5372: chomp($file_part);
5373: my $path_part = join('/', @paths_and_file);
1.572 banghart 5374: $path_part .= '/';
5375: my $path_and_file = $path_part.$file_part;
5376: if ($path_part ne $path) {
1.800 albertel 5377: push(@return_files, ($path_and_file));
1.572 banghart 5378: }
5379: }
1.800 albertel 5380: close(OUT);
1.574 banghart 5381: return (@return_files);
1.572 banghart 5382: }
5383:
1.745 raeburn 5384: #----------------------------------------------Get portfolio file permissions
1.629 banghart 5385:
1.745 raeburn 5386: sub get_portfile_permissions {
5387: my ($domain,$user) = @_;
1.613 albertel 5388: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5389: my ($tmp)=keys(%current_permissions);
5390: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 5391: return \%current_permissions;
5392: }
5393:
5394: #---------------------------------------------Get portfolio file access controls
5395:
1.749 raeburn 5396: sub get_access_controls {
1.745 raeburn 5397: my ($current_permissions,$group,$file) = @_;
1.769 albertel 5398: my %access;
5399: my $real_file = $file;
5400: $file =~ s/\.meta$//;
1.745 raeburn 5401: if (defined($file)) {
1.749 raeburn 5402: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
5403: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 5404: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 5405: }
5406: }
1.745 raeburn 5407: } else {
1.749 raeburn 5408: foreach my $key (keys(%{$current_permissions})) {
5409: if ($key =~ /\0accesscontrol$/) {
5410: if (defined($group)) {
5411: if ($key !~ m-^\Q$group\E/-) {
5412: next;
5413: }
5414: }
5415: my ($fullpath) = split(/\0/,$key);
5416: if (ref($$current_permissions{$key}) eq 'HASH') {
5417: foreach my $control (keys(%{$$current_permissions{$key}})) {
5418: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
5419: }
5420: }
5421: }
5422: }
5423: }
5424: return %access;
5425: }
5426:
5427: sub modify_access_controls {
5428: my ($file_name,$changes,$domain,$user)=@_;
5429: my ($outcome,$deloutcome);
5430: my %store_permissions;
5431: my %new_values;
5432: my %new_control;
5433: my %translation;
5434: my @deletions = ();
5435: my $now = time;
5436: if (exists($$changes{'activate'})) {
5437: if (ref($$changes{'activate'}) eq 'HASH') {
5438: my @newitems = sort(keys(%{$$changes{'activate'}}));
5439: my $numnew = scalar(@newitems);
5440: for (my $i=0; $i<$numnew; $i++) {
5441: my $newkey = $newitems[$i];
5442: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 5443: if ($newkey =~ /^\d+:/) {
5444: $newkey =~ s/^(\d+)/$newid/;
5445: $translation{$1} = $newid;
5446: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
5447: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
5448: $translation{$1} = $newid;
5449: }
1.749 raeburn 5450: $new_values{$file_name."\0".$newkey} =
5451: $$changes{'activate'}{$newitems[$i]};
5452: $new_control{$newkey} = $now;
5453: }
5454: }
5455: }
5456: my %todelete;
5457: my %changed_items;
5458: foreach my $action ('delete','update') {
5459: if (exists($$changes{$action})) {
5460: if (ref($$changes{$action}) eq 'HASH') {
5461: foreach my $key (keys(%{$$changes{$action}})) {
5462: my ($itemnum) = ($key =~ /^([^:]+):/);
5463: if ($action eq 'delete') {
5464: $todelete{$itemnum} = 1;
5465: } else {
5466: $changed_items{$itemnum} = $key;
5467: }
5468: }
1.745 raeburn 5469: }
5470: }
1.749 raeburn 5471: }
5472: # get lock on access controls for file.
5473: my $lockhash = {
5474: $file_name."\0".'locked_access_records' => $env{'user.name'}.
5475: ':'.$env{'user.domain'},
5476: };
5477: my $tries = 0;
5478: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5479:
5480: while (($gotlock ne 'ok') && $tries <3) {
5481: $tries ++;
5482: sleep 1;
5483: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5484: }
5485: if ($gotlock eq 'ok') {
5486: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
5487: my ($tmp)=keys(%curr_permissions);
5488: if ($tmp=~/^error:/) { undef(%curr_permissions); }
5489: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
5490: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
5491: if (ref($curr_controls) eq 'HASH') {
5492: foreach my $control_item (keys(%{$curr_controls})) {
5493: my ($itemnum) = ($control_item =~ /^([^:]+):/);
5494: if (defined($todelete{$itemnum})) {
5495: push(@deletions,$file_name."\0".$control_item);
5496: } else {
5497: if (defined($changed_items{$itemnum})) {
5498: $new_control{$changed_items{$itemnum}} = $now;
5499: push(@deletions,$file_name."\0".$control_item);
5500: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
5501: } else {
5502: $new_control{$control_item} = $$curr_controls{$control_item};
5503: }
5504: }
1.745 raeburn 5505: }
5506: }
5507: }
1.749 raeburn 5508: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
5509: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
5510: $outcome = &put('file_permissions',\%new_values,$domain,$user);
5511: # remove lock
5512: my @del_lock = ($file_name."\0".'locked_access_records');
5513: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 5514: my ($file,$group);
5515: if (&is_course($domain,$user)) {
5516: ($group,$file) = split(/\//,$file_name,2);
5517: } else {
5518: $file = $file_name;
5519: }
5520: my $sqlresult =
5521: &update_portfolio_table($user,$domain,$file,'portfolio_access',
5522: $group);
1.749 raeburn 5523: } else {
5524: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 5525: }
1.749 raeburn 5526: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 5527: }
5528:
1.827 raeburn 5529: sub make_public_indefinitely {
5530: my ($requrl) = @_;
5531: my $now = time;
5532: my $action = 'activate';
5533: my $aclnum = 0;
5534: if (&is_portfolio_url($requrl)) {
5535: my (undef,$udom,$unum,$file_name,$group) =
5536: &parse_portfolio_url($requrl);
5537: my $current_perms = &get_portfile_permissions($udom,$unum);
5538: my %access_controls = &get_access_controls($current_perms,
5539: $group,$file_name);
5540: foreach my $key (keys(%{$access_controls{$file_name}})) {
5541: my ($num,$scope,$end,$start) =
5542: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5543: if ($scope eq 'public') {
5544: if ($start <= $now && $end == 0) {
5545: $action = 'none';
5546: } else {
5547: $action = 'update';
5548: $aclnum = $num;
5549: }
5550: last;
5551: }
5552: }
5553: if ($action eq 'none') {
5554: return 'ok';
5555: } else {
5556: my %changes;
5557: my $newend = 0;
5558: my $newstart = $now;
5559: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
5560: $changes{$action}{$newkey} = {
5561: type => 'public',
5562: time => {
5563: start => $newstart,
5564: end => $newend,
5565: },
5566: };
5567: my ($outcome,$deloutcome,$new_values,$translation) =
5568: &modify_access_controls($file_name,\%changes,$udom,$unum);
5569: return $outcome;
5570: }
5571: } else {
5572: return 'invalid';
5573: }
5574: }
5575:
1.745 raeburn 5576: #------------------------------------------------------Get Marked as Read Only
5577:
5578: sub get_marked_as_readonly {
5579: my ($domain,$user,$what,$group) = @_;
5580: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 5581: my @readonly_files;
1.629 banghart 5582: my $cmp1=$what;
5583: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 5584: while (my ($file_name,$value) = each(%{$current_permissions})) {
5585: if (defined($group)) {
5586: if ($file_name !~ m-^\Q$group\E/-) {
5587: next;
5588: }
5589: }
1.561 banghart 5590: if (ref($value) eq "ARRAY"){
5591: foreach my $stored_what (@{$value}) {
1.629 banghart 5592: my $cmp2=$stored_what;
1.759 albertel 5593: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 5594: $cmp2=join('',@{$stored_what});
1.745 raeburn 5595: }
1.629 banghart 5596: if ($cmp1 eq $cmp2) {
1.561 banghart 5597: push(@readonly_files, $file_name);
1.745 raeburn 5598: last;
1.563 banghart 5599: } elsif (!defined($what)) {
5600: push(@readonly_files, $file_name);
1.745 raeburn 5601: last;
1.561 banghart 5602: }
5603: }
1.745 raeburn 5604: }
1.561 banghart 5605: }
5606: return @readonly_files;
5607: }
1.577 banghart 5608: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 5609:
1.577 banghart 5610: sub get_marked_as_readonly_hash {
1.745 raeburn 5611: my ($current_permissions,$group,$what) = @_;
1.577 banghart 5612: my %readonly_files;
1.745 raeburn 5613: while (my ($file_name,$value) = each(%{$current_permissions})) {
5614: if (defined($group)) {
5615: if ($file_name !~ m-^\Q$group\E/-) {
5616: next;
5617: }
5618: }
1.577 banghart 5619: if (ref($value) eq "ARRAY"){
5620: foreach my $stored_what (@{$value}) {
1.745 raeburn 5621: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 5622: foreach my $lock_descriptor(@{$stored_what}) {
5623: if ($lock_descriptor eq 'graded') {
5624: $readonly_files{$file_name} = 'graded';
5625: } elsif ($lock_descriptor eq 'handback') {
5626: $readonly_files{$file_name} = 'handback';
5627: } else {
5628: if (!exists($readonly_files{$file_name})) {
5629: $readonly_files{$file_name} = 'locked';
5630: }
5631: }
1.745 raeburn 5632: }
1.750 banghart 5633: }
1.577 banghart 5634: }
5635: }
5636: }
5637: return %readonly_files;
5638: }
1.559 banghart 5639: # ------------------------------------------------------------ Unmark as Read Only
5640:
5641: sub unmark_as_readonly {
1.629 banghart 5642: # unmarks $file_name (if $file_name is defined), or all files locked by $what
5643: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 5644: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 5645: $file_name = &declutter_portfile($file_name);
1.634 albertel 5646: my $symb_crs = $what;
5647: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 5648: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 5649: my ($tmp)=keys(%current_permissions);
5650: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 5651: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 5652: foreach my $file (@readonly_files) {
1.759 albertel 5653: my $clean_file = &declutter_portfile($file);
5654: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 5655: my $current_locks = $current_permissions{$file};
1.563 banghart 5656: my @new_locks;
5657: my @del_keys;
5658: if (ref($current_locks) eq "ARRAY"){
5659: foreach my $locker (@{$current_locks}) {
1.632 albertel 5660: my $compare=$locker;
1.749 raeburn 5661: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 5662: $compare=join('',@{$locker});
1.746 raeburn 5663: if ($compare ne $symb_crs) {
5664: push(@new_locks, $locker);
5665: }
1.563 banghart 5666: }
5667: }
1.650 albertel 5668: if (scalar(@new_locks) > 0) {
1.563 banghart 5669: $current_permissions{$file} = \@new_locks;
5670: } else {
5671: push(@del_keys, $file);
1.613 albertel 5672: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 5673: delete($current_permissions{$file});
1.563 banghart 5674: }
5675: }
1.561 banghart 5676: }
1.613 albertel 5677: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 5678: return;
5679: }
1.512 banghart 5680:
1.17 www 5681: # ------------------------------------------------------------ Directory lister
5682:
5683: sub dirlist {
1.253 stredwic 5684: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
5685:
1.18 www 5686: $uri=~s/^\///;
5687: $uri=~s/\/$//;
1.253 stredwic 5688: my ($udom, $uname);
5689: (undef,$udom,$uname)=split(/\//,$uri);
5690: if(defined($userdomain)) {
5691: $udom = $userdomain;
5692: }
5693: if(defined($username)) {
5694: $uname = $username;
5695: }
5696:
5697: my $dirRoot = $perlvar{'lonDocRoot'};
5698: if(defined($alternateDirectoryRoot)) {
5699: $dirRoot = $alternateDirectoryRoot;
5700: $dirRoot =~ s/\/$//;
1.751 banghart 5701: }
1.253 stredwic 5702:
5703: if($udom) {
5704: if($uname) {
1.800 albertel 5705: my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
5706: &homeserver($uname,$udom));
1.605 matthew 5707: my @listing_results;
5708: if ($listing eq 'unknown_cmd') {
1.800 albertel 5709: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
5710: &homeserver($uname,$udom));
1.605 matthew 5711: @listing_results = split(/:/,$listing);
5712: } else {
5713: @listing_results = map { &unescape($_); } split(/:/,$listing);
5714: }
5715: return @listing_results;
1.253 stredwic 5716: } elsif(!defined($alternateDirectoryRoot)) {
1.800 albertel 5717: my %allusers;
1.841 albertel 5718: my %servers = &get_servers($udom,'library');
5719: foreach my $tryserver (keys(%servers)) {
5720: my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
5721: $udom, $tryserver);
5722: my @listing_results;
5723: if ($listing eq 'unknown_cmd') {
5724: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
5725: $udom, $tryserver);
5726: @listing_results = split(/:/,$listing);
5727: } else {
5728: @listing_results =
5729: map { &unescape($_); } split(/:/,$listing);
5730: }
5731: if ($listing_results[0] ne 'no_such_dir' &&
5732: $listing_results[0] ne 'empty' &&
5733: $listing_results[0] ne 'con_lost') {
5734: foreach my $line (@listing_results) {
5735: my ($entry) = split(/&/,$line,2);
5736: $allusers{$entry} = 1;
5737: }
5738: }
1.253 stredwic 5739: }
5740: my $alluserstr='';
1.800 albertel 5741: foreach my $user (sort(keys(%allusers))) {
5742: $alluserstr.=$user.'&user:';
1.253 stredwic 5743: }
5744: $alluserstr=~s/:$//;
5745: return split(/:/,$alluserstr);
5746: } else {
1.800 albertel 5747: return ('missing user name');
1.253 stredwic 5748: }
5749: } elsif(!defined($alternateDirectoryRoot)) {
1.841 albertel 5750: my @all_domains = sort(&all_domains());
5751: foreach my $domain (@all_domains) {
5752: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
5753: }
5754: return @all_domains;
5755: } else {
1.800 albertel 5756: return ('missing domain');
1.275 stredwic 5757: }
5758: }
5759:
5760: # --------------------------------------------- GetFileTimestamp
5761: # This function utilizes dirlist and returns the date stamp for
5762: # when it was last modified. It will also return an error of -1
5763: # if an error occurs
5764:
1.410 matthew 5765: ##
5766: ## FIXME: This subroutine assumes its caller knows something about the
5767: ## directory structure of the home server for the student ($root).
5768: ## Not a good assumption to make. Since this is for looking up files
5769: ## in user directories, the full path should be constructed by lond, not
5770: ## whatever machine we request data from.
5771: ##
1.275 stredwic 5772: sub GetFileTimestamp {
5773: my ($studentDomain,$studentName,$filename,$root)=@_;
1.807 albertel 5774: $studentDomain = &LONCAPA::clean_domain($studentDomain);
5775: $studentName = &LONCAPA::clean_username($studentName);
1.275 stredwic 5776: my $subdir=$studentName.'__';
5777: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
5778: my $proname="$studentDomain/$subdir/$studentName";
5779: $proname .= '/'.$filename;
1.375 matthew 5780: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
5781: $studentName, $root);
1.275 stredwic 5782: my @stats = split('&', $fileStat);
5783: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 5784: # @stats contains first the filename, then the stat output
5785: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 5786: } else {
5787: return -1;
1.253 stredwic 5788: }
1.26 www 5789: }
5790:
1.712 albertel 5791: sub stat_file {
5792: my ($uri) = @_;
1.787 albertel 5793: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 5794:
1.712 albertel 5795: my ($udom,$uname,$file,$dir);
5796: if ($uri =~ m-^/(uploaded|editupload)/-) {
5797: ($udom,$uname,$file) =
1.811 albertel 5798: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 5799: $file = 'userfiles/'.$file;
1.740 www 5800: $dir = &propath($udom,$uname);
1.712 albertel 5801: }
5802: if ($uri =~ m-^/res/-) {
5803: ($udom,$uname) =
1.807 albertel 5804: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 5805: $file = $uri;
5806: }
5807:
5808: if (!$udom || !$uname || !$file) {
5809: # unable to handle the uri
5810: return ();
5811: }
5812:
5813: my ($result) = &dirlist($file,$udom,$uname,$dir);
5814: my @stats = split('&', $result);
1.721 banghart 5815:
1.712 albertel 5816: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
5817: shift(@stats); #filename is first
5818: return @stats;
5819: }
5820: return ();
5821: }
5822:
1.26 www 5823: # -------------------------------------------------------- Value of a Condition
5824:
1.713 albertel 5825: # gets the value of a specific preevaluated condition
5826: # stored in the string $env{user.state.<cid>}
5827: # or looks up a condition reference in the bighash and if if hasn't
5828: # already been evaluated recurses into docondval to get the value of
5829: # the condition, then memoizing it to
5830: # $env{user.state.<cid>.<condition>}
1.40 www 5831: sub directcondval {
5832: my $number=shift;
1.620 albertel 5833: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 5834: &Apache::lonuserstate::evalstate();
5835: }
1.713 albertel 5836: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
5837: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
5838: } elsif ($number =~ /^_/) {
5839: my $sub_condition;
5840: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5841: &GDBM_READER(),0640)) {
5842: $sub_condition=$bighash{'conditions'.$number};
5843: untie(%bighash);
5844: }
5845: my $value = &docondval($sub_condition);
5846: &appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
5847: return $value;
5848: }
1.620 albertel 5849: if ($env{'user.state.'.$env{'request.course.id'}}) {
5850: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 5851: } else {
5852: return 2;
5853: }
5854: }
5855:
1.713 albertel 5856: # get the collection of conditions for this resource
1.26 www 5857: sub condval {
5858: my $condidx=shift;
1.54 www 5859: my $allpathcond='';
1.713 albertel 5860: foreach my $cond (split(/\|/,$condidx)) {
5861: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
5862: $allpathcond.=
5863: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
5864: }
1.191 harris41 5865: }
1.54 www 5866: $allpathcond=~s/\|$//;
1.713 albertel 5867: return &docondval($allpathcond);
5868: }
5869:
5870: #evaluates an expression of conditions
5871: sub docondval {
5872: my ($allpathcond) = @_;
5873: my $result=0;
5874: if ($env{'request.course.id'}
5875: && defined($allpathcond)) {
5876: my $operand='|';
5877: my @stack;
5878: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
5879: if ($chunk eq '(') {
5880: push @stack,($operand,$result);
5881: } elsif ($chunk eq ')') {
5882: my $before=pop @stack;
5883: if (pop @stack eq '&') {
5884: $result=$result>$before?$before:$result;
5885: } else {
5886: $result=$result>$before?$result:$before;
5887: }
5888: } elsif (($chunk eq '&') || ($chunk eq '|')) {
5889: $operand=$chunk;
5890: } else {
5891: my $new=directcondval($chunk);
5892: if ($operand eq '&') {
5893: $result=$result>$new?$new:$result;
5894: } else {
5895: $result=$result>$new?$result:$new;
5896: }
5897: }
5898: }
1.26 www 5899: }
5900: return $result;
1.421 albertel 5901: }
5902:
5903: # ---------------------------------------------------- Devalidate courseresdata
5904:
5905: sub devalidatecourseresdata {
5906: my ($coursenum,$coursedomain)=@_;
5907: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 5908: &devalidate_cache_new('courseres',$hashid);
1.28 www 5909: }
5910:
1.763 www 5911:
1.200 www 5912: # --------------------------------------------------- Course Resourcedata Query
5913:
1.624 albertel 5914: sub get_courseresdata {
5915: my ($coursenum,$coursedomain)=@_;
1.200 www 5916: my $coursehom=&homeserver($coursenum,$coursedomain);
5917: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 5918: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 5919: my %dumpreply;
1.417 albertel 5920: unless (defined($cached)) {
1.624 albertel 5921: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 5922: $result=\%dumpreply;
1.251 albertel 5923: my ($tmp) = keys(%dumpreply);
5924: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 5925: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 5926: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
5927: return $tmp;
1.416 albertel 5928: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 5929: $result=undef;
1.599 albertel 5930: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 5931: }
5932: }
1.624 albertel 5933: return $result;
5934: }
5935:
1.633 albertel 5936: sub devalidateuserresdata {
5937: my ($uname,$udom)=@_;
5938: my $hashid="$udom:$uname";
5939: &devalidate_cache_new('userres',$hashid);
5940: }
5941:
1.624 albertel 5942: sub get_userresdata {
5943: my ($uname,$udom)=@_;
5944: #most student don\'t have any data set, check if there is some data
5945: if (&EXT_cache_status($udom,$uname)) { return undef; }
5946:
5947: my $hashid="$udom:$uname";
5948: my ($result,$cached)=&is_cached_new('userres',$hashid);
5949: if (!defined($cached)) {
5950: my %resourcedata=&dump('resourcedata',$udom,$uname);
5951: $result=\%resourcedata;
5952: &do_cache_new('userres',$hashid,$result,600);
5953: }
5954: my ($tmp)=keys(%$result);
5955: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
5956: return $result;
5957: }
5958: #error 2 occurs when the .db doesn't exist
5959: if ($tmp!~/error: 2 /) {
1.672 albertel 5960: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 5961: " Trying to get resource data for ".
5962: $uname." at ".$udom.": ".
5963: $tmp."</font>");
5964: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 5965: #&EXT_cache_set($udom,$uname);
5966: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 5967: undef($tmp); # not really an error so don't send it back
1.624 albertel 5968: }
5969: return $tmp;
5970: }
5971:
5972: sub resdata {
5973: my ($name,$domain,$type,@which)=@_;
5974: my $result;
5975: if ($type eq 'course') {
5976: $result=&get_courseresdata($name,$domain);
5977: } elsif ($type eq 'user') {
5978: $result=&get_userresdata($name,$domain);
5979: }
5980: if (!ref($result)) { return $result; }
1.251 albertel 5981: foreach my $item (@which) {
1.417 albertel 5982: if (defined($result->{$item})) {
5983: return $result->{$item};
1.251 albertel 5984: }
1.250 albertel 5985: }
1.291 albertel 5986: return undef;
1.200 www 5987: }
5988:
1.379 matthew 5989: #
5990: # EXT resource caching routines
5991: #
5992:
5993: sub clear_EXT_cache_status {
1.383 albertel 5994: &delenv('cache.EXT.');
1.379 matthew 5995: }
5996:
5997: sub EXT_cache_status {
5998: my ($target_domain,$target_user) = @_;
1.383 albertel 5999: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 6000: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 6001: # We know already the user has no data
6002: return 1;
6003: } else {
6004: return 0;
6005: }
6006: }
6007:
6008: sub EXT_cache_set {
6009: my ($target_domain,$target_user) = @_;
1.383 albertel 6010: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633 albertel 6011: #&appenv($cachename => time);
1.379 matthew 6012: }
6013:
1.28 www 6014: # --------------------------------------------------------- Value of a Variable
1.58 www 6015: sub EXT {
1.715 albertel 6016:
1.395 albertel 6017: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 6018: unless ($varname) { return ''; }
1.218 albertel 6019: #get real user name/domain, courseid and symb
6020: my $courseid;
1.359 albertel 6021: my $publicuser;
1.427 www 6022: if ($symbparm) {
6023: $symbparm=&get_symb_from_alias($symbparm);
6024: }
1.218 albertel 6025: if (!($uname && $udom)) {
1.790 albertel 6026: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 6027: if (!$symbparm) { $symbparm=$cursymb; }
6028: } else {
1.620 albertel 6029: $courseid=$env{'request.course.id'};
1.218 albertel 6030: }
1.48 www 6031: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
6032: my $rest;
1.320 albertel 6033: if (defined($therest[0])) {
1.48 www 6034: $rest=join('.',@therest);
6035: } else {
6036: $rest='';
6037: }
1.320 albertel 6038:
1.57 www 6039: my $qualifierrest=$qualifier;
6040: if ($rest) { $qualifierrest.='.'.$rest; }
6041: my $spacequalifierrest=$space;
6042: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 6043: if ($realm eq 'user') {
1.48 www 6044: # --------------------------------------------------------------- user.resource
6045: if ($space eq 'resource') {
1.651 albertel 6046: if ( (defined($Apache::lonhomework::parsing_a_problem)
6047: || defined($Apache::lonhomework::parsing_a_task))
6048: &&
1.744 albertel 6049: ($symbparm eq &symbread()) ) {
6050: # if we are in the middle of processing the resource the
6051: # get the value we are planning on committing
6052: if (defined($Apache::lonhomework::results{$qualifierrest})) {
6053: return $Apache::lonhomework::results{$qualifierrest};
6054: } else {
6055: return $Apache::lonhomework::history{$qualifierrest};
6056: }
1.335 albertel 6057: } else {
1.359 albertel 6058: my %restored;
1.620 albertel 6059: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 6060: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
6061: } else {
6062: %restored=&restore($symbparm,$courseid,$udom,$uname);
6063: }
1.335 albertel 6064: return $restored{$qualifierrest};
6065: }
1.48 www 6066: # ----------------------------------------------------------------- user.access
6067: } elsif ($space eq 'access') {
1.218 albertel 6068: # FIXME - not supporting calls for a specific user
1.48 www 6069: return &allowed($qualifier,$rest);
6070: # ------------------------------------------ user.preferences, user.environment
6071: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 6072: if (($uname eq $env{'user.name'}) &&
6073: ($udom eq $env{'user.domain'})) {
6074: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 6075: } else {
1.359 albertel 6076: my %returnhash;
6077: if (!$publicuser) {
6078: %returnhash=&userenvironment($udom,$uname,
6079: $qualifierrest);
6080: }
1.218 albertel 6081: return $returnhash{$qualifierrest};
6082: }
1.48 www 6083: # ----------------------------------------------------------------- user.course
6084: } elsif ($space eq 'course') {
1.218 albertel 6085: # FIXME - not supporting calls for a specific user
1.620 albertel 6086: return $env{join('.',('request.course',$qualifier))};
1.48 www 6087: # ------------------------------------------------------------------- user.role
6088: } elsif ($space eq 'role') {
1.218 albertel 6089: # FIXME - not supporting calls for a specific user
1.620 albertel 6090: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 6091: if ($qualifier eq 'value') {
6092: return $role;
6093: } elsif ($qualifier eq 'extent') {
6094: return $where;
6095: }
6096: # ----------------------------------------------------------------- user.domain
6097: } elsif ($space eq 'domain') {
1.218 albertel 6098: return $udom;
1.48 www 6099: # ------------------------------------------------------------------- user.name
6100: } elsif ($space eq 'name') {
1.218 albertel 6101: return $uname;
1.48 www 6102: # ---------------------------------------------------- Any other user namespace
1.29 www 6103: } else {
1.359 albertel 6104: my %reply;
6105: if (!$publicuser) {
6106: %reply=&get($space,[$qualifierrest],$udom,$uname);
6107: }
6108: return $reply{$qualifierrest};
1.48 www 6109: }
1.236 www 6110: } elsif ($realm eq 'query') {
6111: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 6112: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
6113: [$spacequalifierrest]);
1.620 albertel 6114: return $env{'form.'.$spacequalifierrest};
1.236 www 6115: } elsif ($realm eq 'request') {
1.48 www 6116: # ------------------------------------------------------------- request.browser
6117: if ($space eq 'browser') {
1.430 www 6118: if ($qualifier eq 'textremote') {
1.676 albertel 6119: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 6120: return 1;
6121: } else {
6122: return 0;
6123: }
6124: } else {
1.620 albertel 6125: return $env{'browser.'.$qualifier};
1.430 www 6126: }
1.57 www 6127: # ------------------------------------------------------------ request.filename
6128: } else {
1.620 albertel 6129: return $env{'request.'.$spacequalifierrest};
1.29 www 6130: }
1.28 www 6131: } elsif ($realm eq 'course') {
1.48 www 6132: # ---------------------------------------------------------- course.description
1.620 albertel 6133: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 6134: } elsif ($realm eq 'resource') {
1.165 www 6135:
1.620 albertel 6136: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 6137: if (!$symbparm) { $symbparm=&symbread(); }
6138: }
1.693 albertel 6139:
6140: if ($space eq 'title') {
6141: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
6142: return &gettitle($symbparm);
6143: }
6144:
6145: if ($space eq 'map') {
6146: my ($map) = &decode_symb($symbparm);
6147: return &symbread($map);
6148: }
6149:
6150: my ($section, $group, @groups);
1.593 albertel 6151: my ($courselevelm,$courselevel);
1.539 albertel 6152: if ($symbparm && defined($courseid) &&
1.620 albertel 6153: $courseid eq $env{'request.course.id'}) {
1.165 www 6154:
1.218 albertel 6155: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 6156:
1.60 www 6157: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 6158: my $symbp=$symbparm;
1.735 albertel 6159: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 6160:
6161: my $symbparm=$symbp.'.'.$spacequalifierrest;
6162: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
6163:
1.620 albertel 6164: if (($env{'user.name'} eq $uname) &&
6165: ($env{'user.domain'} eq $udom)) {
6166: $section=$env{'request.course.sec'};
1.733 raeburn 6167: @groups = split(/:/,$env{'request.course.groups'});
6168: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 6169: } else {
1.539 albertel 6170: if (! defined($usection)) {
1.551 albertel 6171: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 6172: } else {
6173: $section = $usection;
6174: }
1.733 raeburn 6175: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 6176: }
6177:
6178: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
6179: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
6180: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
6181:
1.593 albertel 6182: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 6183: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 6184: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 6185:
1.60 www 6186: # ----------------------------------------------------------- first, check user
1.624 albertel 6187:
6188: my $userreply=&resdata($uname,$udom,'user',
6189: ($courselevelr,$courselevelm,
6190: $courselevel));
6191: if (defined($userreply)) { return $userreply; }
1.95 www 6192:
1.594 albertel 6193: # ------------------------------------------------ second, check some of course
1.684 raeburn 6194: my $coursereply;
1.691 raeburn 6195: if (@groups > 0) {
6196: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
6197: $mapparm,$spacequalifierrest);
1.684 raeburn 6198: if (defined($coursereply)) { return $coursereply; }
6199: }
1.96 www 6200:
1.684 raeburn 6201: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624 albertel 6202: $env{'course.'.$courseid.'.domain'},
6203: 'course',
6204: ($seclevelr,$seclevelm,$seclevel,
6205: $courselevelr));
1.287 albertel 6206: if (defined($coursereply)) { return $coursereply; }
1.200 www 6207:
1.60 www 6208: # ------------------------------------------------------ third, check map parms
1.218 albertel 6209: my %parmhash=();
6210: my $thisparm='';
6211: if (tie(%parmhash,'GDBM_File',
1.620 albertel 6212: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 6213: &GDBM_READER(),0640)) {
1.218 albertel 6214: $thisparm=$parmhash{$symbparm};
6215: untie(%parmhash);
6216: }
6217: if ($thisparm) { return $thisparm; }
6218: }
1.594 albertel 6219: # ------------------------------------------ fourth, look in resource metadata
1.71 www 6220:
1.218 albertel 6221: $spacequalifierrest=~s/\./\_/;
1.282 albertel 6222: my $filename;
6223: if (!$symbparm) { $symbparm=&symbread(); }
6224: if ($symbparm) {
1.409 www 6225: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 6226: } else {
1.620 albertel 6227: $filename=$env{'request.filename'};
1.282 albertel 6228: }
6229: my $metadata=&metadata($filename,$spacequalifierrest);
1.288 albertel 6230: if (defined($metadata)) { return $metadata; }
1.282 albertel 6231: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288 albertel 6232: if (defined($metadata)) { return $metadata; }
1.142 www 6233:
1.594 albertel 6234: # ---------------------------------------------- fourth, look in rest pf course
1.593 albertel 6235: if ($symbparm && defined($courseid) &&
1.620 albertel 6236: $courseid eq $env{'request.course.id'}) {
1.624 albertel 6237: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
6238: $env{'course.'.$courseid.'.domain'},
6239: 'course',
6240: ($courselevelm,$courselevel));
1.593 albertel 6241: if (defined($coursereply)) { return $coursereply; }
6242: }
1.145 www 6243: # ------------------------------------------------------------------ Cascade up
1.218 albertel 6244: unless ($space eq '0') {
1.336 albertel 6245: my @parts=split(/_/,$space);
6246: my $id=pop(@parts);
6247: my $part=join('_',@parts);
6248: if ($part eq '') { $part='0'; }
6249: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 6250: $symbparm,$udom,$uname,$section,1);
1.337 albertel 6251: if (defined($partgeneral)) { return $partgeneral; }
1.218 albertel 6252: }
1.395 albertel 6253: if ($recurse) { return undef; }
6254: my $pack_def=&packages_tab_default($filename,$varname);
6255: if (defined($pack_def)) { return $pack_def; }
1.71 www 6256:
1.48 www 6257: # ---------------------------------------------------- Any other user namespace
6258: } elsif ($realm eq 'environment') {
6259: # ----------------------------------------------------------------- environment
1.620 albertel 6260: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
6261: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 6262: } else {
1.770 albertel 6263: if ($uname eq 'anonymous' && $udom eq '') {
6264: return '';
6265: }
1.219 albertel 6266: my %returnhash=&userenvironment($udom,$uname,
6267: $spacequalifierrest);
6268: return $returnhash{$spacequalifierrest};
6269: }
1.28 www 6270: } elsif ($realm eq 'system') {
1.48 www 6271: # ----------------------------------------------------------------- system.time
6272: if ($space eq 'time') {
6273: return time;
6274: }
1.696 albertel 6275: } elsif ($realm eq 'server') {
6276: # ----------------------------------------------------------------- system.time
6277: if ($space eq 'name') {
6278: return $ENV{'SERVER_NAME'};
6279: }
1.28 www 6280: }
1.48 www 6281: return '';
1.61 www 6282: }
6283:
1.691 raeburn 6284: sub check_group_parms {
6285: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
6286: my @groupitems = ();
6287: my $resultitem;
6288: my @levels = ($symbparm,$mapparm,$what);
6289: foreach my $group (@{$groups}) {
6290: foreach my $level (@levels) {
6291: my $item = $courseid.'.['.$group.'].'.$level;
6292: push(@groupitems,$item);
6293: }
6294: }
6295: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
6296: $env{'course.'.$courseid.'.domain'},
6297: 'course',@groupitems);
6298: return $coursereply;
6299: }
6300:
6301: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 6302: my ($courseid,@groups) = @_;
6303: @groups = sort(@groups);
1.691 raeburn 6304: return @groups;
6305: }
6306:
1.395 albertel 6307: sub packages_tab_default {
6308: my ($uri,$varname)=@_;
6309: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 6310:
6311: my (@extension,@specifics,$do_default);
6312: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 6313: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 6314: if ($pack_type eq 'default') {
6315: $do_default=1;
6316: } elsif ($pack_type eq 'extension') {
6317: push(@extension,[$package,$pack_type,$pack_part]);
1.848 albertel 6318: } elsif ($pack_part eq $part) {
6319: # only look at packages defaults for packages that this id is
1.738 albertel 6320: push(@specifics,[$package,$pack_type,$pack_part]);
6321: }
6322: }
6323: # first look for a package that matches the requested part id
6324: foreach my $package (@specifics) {
6325: my (undef,$pack_type,$pack_part)=@{$package};
6326: next if ($pack_part ne $part);
6327: if (defined($packagetab{"$pack_type&$name&default"})) {
6328: return $packagetab{"$pack_type&$name&default"};
6329: }
6330: }
6331: # look for any possible matching non extension_ package
6332: foreach my $package (@specifics) {
6333: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 6334: if (defined($packagetab{"$pack_type&$name&default"})) {
6335: return $packagetab{"$pack_type&$name&default"};
6336: }
1.585 albertel 6337: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 6338: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
6339: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 6340: }
6341: }
1.738 albertel 6342: # look for any posible extension_ match
6343: foreach my $package (@extension) {
6344: my ($package,$pack_type)=@{$package};
6345: if (defined($packagetab{"$pack_type&$name&default"})) {
6346: return $packagetab{"$pack_type&$name&default"};
6347: }
6348: if (defined($packagetab{$package."&$name&default"})) {
6349: return $packagetab{$package."&$name&default"};
6350: }
6351: }
6352: # look for a global default setting
6353: if ($do_default && defined($packagetab{"default&$name&default"})) {
6354: return $packagetab{"default&$name&default"};
6355: }
1.395 albertel 6356: return undef;
6357: }
6358:
1.334 albertel 6359: sub add_prefix_and_part {
6360: my ($prefix,$part)=@_;
6361: my $keyroot;
6362: if (defined($prefix) && $prefix !~ /^__/) {
6363: # prefix that has a part already
6364: $keyroot=$prefix;
6365: } elsif (defined($prefix)) {
6366: # prefix that is missing a part
6367: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
6368: } else {
6369: # no prefix at all
6370: if (defined($part)) { $keyroot='_'.$part; }
6371: }
6372: return $keyroot;
6373: }
6374:
1.71 www 6375: # ---------------------------------------------------------------- Get metadata
6376:
1.599 albertel 6377: my %metaentry;
1.71 www 6378: sub metadata {
1.176 www 6379: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 6380: $uri=&declutter($uri);
1.288 albertel 6381: # if it is a non metadata possible uri return quickly
1.529 albertel 6382: if (($uri eq '') ||
6383: (($uri =~ m|^/*adm/|) &&
1.698 albertel 6384: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423 albertel 6385: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807 albertel 6386: ($uri =~ m|home/$match_username/public_html/|)) {
1.468 albertel 6387: return undef;
1.288 albertel 6388: }
1.73 www 6389: my $filename=$uri;
6390: $uri=~s/\.meta$//;
1.172 www 6391: #
6392: # Is the metadata already cached?
1.177 www 6393: # Look at timestamp of caching
1.172 www 6394: # Everything is cached by the main uri, libraries are never directly cached
6395: #
1.428 albertel 6396: if (!defined($liburi)) {
1.599 albertel 6397: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 6398: if (defined($cached)) { return $result->{':'.$what}; }
6399: }
6400: {
1.172 www 6401: #
6402: # Is this a recursive call for a library?
6403: #
1.599 albertel 6404: # if (! exists($metacache{$uri})) {
6405: # $metacache{$uri}={};
6406: # }
1.171 www 6407: if ($liburi) {
6408: $liburi=&declutter($liburi);
6409: $filename=$liburi;
1.401 bowersj2 6410: } else {
1.599 albertel 6411: &devalidate_cache_new('meta',$uri);
6412: undef(%metaentry);
1.401 bowersj2 6413: }
1.140 www 6414: my %metathesekeys=();
1.73 www 6415: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 6416: my $metastring;
1.768 albertel 6417: if ($uri !~ m -^(editupload)/-) {
1.543 albertel 6418: my $file=&filelocation('',&clutter($filename));
1.599 albertel 6419: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 6420: $metastring=&getfile($file);
1.489 albertel 6421: }
1.208 albertel 6422: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 6423: my $token;
1.140 www 6424: undef %metathesekeys;
1.71 www 6425: while ($token=$parser->get_token) {
1.339 albertel 6426: if ($token->[0] eq 'S') {
6427: if (defined($token->[2]->{'package'})) {
1.172 www 6428: #
6429: # This is a package - get package info
6430: #
1.339 albertel 6431: my $package=$token->[2]->{'package'};
6432: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6433: if (defined($token->[2]->{'id'})) {
6434: $keyroot.='_'.$token->[2]->{'id'};
6435: }
1.599 albertel 6436: if ($metaentry{':packages'}) {
6437: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 6438: } else {
1.599 albertel 6439: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 6440: }
1.736 albertel 6441: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 6442: my $part=$keyroot;
6443: $part=~s/^\_//;
1.736 albertel 6444: if ($pack_entry=~/^\Q$package\E\&/ ||
6445: $pack_entry=~/^\Q$package\E_0\&/) {
6446: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 6447: # ignore package.tab specified default values
6448: # here &package_tab_default() will fetch those
6449: if ($subp eq 'default') { next; }
1.736 albertel 6450: my $value=$packagetab{$pack_entry};
1.432 albertel 6451: my $unikey;
6452: if ($pack =~ /_0$/) {
6453: $unikey='parameter_0_'.$name;
6454: $part=0;
6455: } else {
6456: $unikey='parameter'.$keyroot.'_'.$name;
6457: }
1.339 albertel 6458: if ($subp eq 'display') {
6459: $value.=' [Part: '.$part.']';
6460: }
1.599 albertel 6461: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 6462: $metathesekeys{$unikey}=1;
1.599 albertel 6463: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6464: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 6465: }
1.599 albertel 6466: if (defined($metaentry{':'.$unikey.'.default'})) {
6467: $metaentry{':'.$unikey}=
6468: $metaentry{':'.$unikey.'.default'};
1.356 albertel 6469: }
1.339 albertel 6470: }
6471: }
6472: } else {
1.172 www 6473: #
6474: # This is not a package - some other kind of start tag
1.339 albertel 6475: #
6476: my $entry=$token->[1];
6477: my $unikey;
6478: if ($entry eq 'import') {
6479: $unikey='';
6480: } else {
6481: $unikey=$entry;
6482: }
6483: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6484:
6485: if (defined($token->[2]->{'id'})) {
6486: $unikey.='_'.$token->[2]->{'id'};
6487: }
1.175 www 6488:
1.339 albertel 6489: if ($entry eq 'import') {
1.175 www 6490: #
6491: # Importing a library here
1.339 albertel 6492: #
6493: if ($depthcount<20) {
6494: my $location=$parser->get_text('/import');
6495: my $dir=$filename;
6496: $dir=~s|[^/]*$||;
6497: $location=&filelocation($dir,$location);
1.736 albertel 6498: my $metadata =
6499: &metadata($uri,'keys', $location,$unikey,
6500: $depthcount+1);
6501: foreach my $meta (split(',',$metadata)) {
6502: $metaentry{':'.$meta}=$metaentry{':'.$meta};
6503: $metathesekeys{$meta}=1;
1.339 albertel 6504: }
6505: }
6506: } else {
6507:
6508: if (defined($token->[2]->{'name'})) {
6509: $unikey.='_'.$token->[2]->{'name'};
6510: }
6511: $metathesekeys{$unikey}=1;
1.736 albertel 6512: foreach my $param (@{$token->[3]}) {
6513: $metaentry{':'.$unikey.'.'.$param} =
6514: $token->[2]->{$param};
1.339 albertel 6515: }
6516: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 6517: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 6518: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
6519: # only ws inside the tag, and not in default, so use default
6520: # as value
1.599 albertel 6521: $metaentry{':'.$unikey}=$default;
1.339 albertel 6522: } else {
1.321 albertel 6523: # either something interesting inside the tag or default
6524: # uninteresting
1.599 albertel 6525: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 6526: }
1.172 www 6527: # end of not-a-package not-a-library import
1.339 albertel 6528: }
1.172 www 6529: # end of not-a-package start tag
1.339 albertel 6530: }
1.172 www 6531: # the next is the end of "start tag"
1.339 albertel 6532: }
6533: }
1.483 albertel 6534: my ($extension) = ($uri =~ /\.(\w+)$/);
1.737 albertel 6535: foreach my $key (keys(%packagetab)) {
1.483 albertel 6536: #no specific packages #how's our extension
6537: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 6538: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 6539: \%metathesekeys);
6540: }
1.599 albertel 6541: if (!exists($metaentry{':packages'})) {
1.737 albertel 6542: foreach my $key (keys(%packagetab)) {
1.483 albertel 6543: #no specific packages well let's get default then
6544: if ($key!~/^default&/) { next; }
1.488 albertel 6545: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 6546: \%metathesekeys);
6547: }
6548: }
1.338 www 6549: # are there custom rights to evaluate
1.599 albertel 6550: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 6551:
1.338 www 6552: #
6553: # Importing a rights file here
1.339 albertel 6554: #
6555: unless ($depthcount) {
1.599 albertel 6556: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 6557: my $dir=$filename;
6558: $dir=~s|[^/]*$||;
6559: $location=&filelocation($dir,$location);
1.736 albertel 6560: my $rights_metadata =
6561: &metadata($uri,'keys',$location,'_rights',
6562: $depthcount+1);
6563: foreach my $rights (split(',',$rights_metadata)) {
6564: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
6565: $metathesekeys{$rights}=1;
1.339 albertel 6566: }
6567: }
6568: }
1.737 albertel 6569: # uniqifiy package listing
6570: my %seen;
6571: my @uniq_packages =
6572: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
6573: $metaentry{':packages'} = join(',',@uniq_packages);
6574:
6575: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 6576: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
6577: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699 albertel 6578: &do_cache_new('meta',$uri,\%metaentry,60*60);
1.177 www 6579: # this is the end of "was not already recently cached
1.71 www 6580: }
1.599 albertel 6581: return $metaentry{':'.$what};
1.261 albertel 6582: }
6583:
1.488 albertel 6584: sub metadata_create_package_def {
1.483 albertel 6585: my ($uri,$key,$package,$metathesekeys)=@_;
6586: my ($pack,$name,$subp)=split(/\&/,$key);
6587: if ($subp eq 'default') { next; }
6588:
1.599 albertel 6589: if (defined($metaentry{':packages'})) {
6590: $metaentry{':packages'}.=','.$package;
1.483 albertel 6591: } else {
1.599 albertel 6592: $metaentry{':packages'}=$package;
1.483 albertel 6593: }
6594: my $value=$packagetab{$key};
6595: my $unikey;
6596: $unikey='parameter_0_'.$name;
1.599 albertel 6597: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 6598: $$metathesekeys{$unikey}=1;
1.599 albertel 6599: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6600: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 6601: }
1.599 albertel 6602: if (defined($metaentry{':'.$unikey.'.default'})) {
6603: $metaentry{':'.$unikey}=
6604: $metaentry{':'.$unikey.'.default'};
1.483 albertel 6605: }
6606: }
6607:
1.261 albertel 6608: sub metadata_generate_part0 {
6609: my ($metadata,$metacache,$uri) = @_;
6610: my %allnames;
1.737 albertel 6611: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 6612: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 6613: my $part=$$metacache{':'.$metakey.'.part'};
6614: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 6615: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 6616: $allnames{$name}=$part;
6617: }
6618: }
6619: }
6620: foreach my $name (keys(%allnames)) {
6621: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 6622: my $key=":parameter_0_$name";
1.261 albertel 6623: $$metacache{"$key.part"}='0';
6624: $$metacache{"$key.name"}=$name;
1.428 albertel 6625: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 6626: $allnames{$name}.'_'.$name.
6627: '.type'};
1.428 albertel 6628: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 6629: '.display'};
1.644 www 6630: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 6631: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 6632: $$metacache{"$key.display"}=$olddis;
6633: }
1.71 www 6634: }
6635:
1.764 albertel 6636: # ------------------------------------------------------ Devalidate title cache
6637:
6638: sub devalidate_title_cache {
6639: my ($url)=@_;
6640: if (!$env{'request.course.id'}) { return; }
6641: my $symb=&symbread($url);
6642: if (!$symb) { return; }
6643: my $key=$env{'request.course.id'}."\0".$symb;
6644: &devalidate_cache_new('title',$key);
6645: }
6646:
1.301 www 6647: # ------------------------------------------------- Get the title of a resource
6648:
6649: sub gettitle {
6650: my $urlsymb=shift;
6651: my $symb=&symbread($urlsymb);
1.534 albertel 6652: if ($symb) {
1.620 albertel 6653: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 6654: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 6655: if (defined($cached)) {
6656: return $result;
6657: }
1.534 albertel 6658: my ($map,$resid,$url)=&decode_symb($symb);
6659: my $title='';
6660: my %bighash;
1.620 albertel 6661: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534 albertel 6662: &GDBM_READER(),0640)) {
6663: my $mapid=$bighash{'map_pc_'.&clutter($map)};
6664: $title=$bighash{'title_'.$mapid.'.'.$resid};
6665: untie %bighash;
6666: }
6667: $title=~s/\&colon\;/\:/gs;
6668: if ($title) {
1.599 albertel 6669: return &do_cache_new('title',$key,$title,600);
1.534 albertel 6670: }
6671: $urlsymb=$url;
6672: }
6673: my $title=&metadata($urlsymb,'title');
6674: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
6675: return $title;
1.301 www 6676: }
1.613 albertel 6677:
1.614 albertel 6678: sub get_slot {
6679: my ($which,$cnum,$cdom)=@_;
6680: if (!$cnum || !$cdom) {
1.790 albertel 6681: (undef,my $courseid)=&whichuser();
1.620 albertel 6682: $cdom=$env{'course.'.$courseid.'.domain'};
6683: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 6684: }
1.703 albertel 6685: my $key=join("\0",'slots',$cdom,$cnum,$which);
6686: my %slotinfo;
6687: if (exists($remembered{$key})) {
6688: $slotinfo{$which} = $remembered{$key};
6689: } else {
6690: %slotinfo=&get('slots',[$which],$cdom,$cnum);
6691: &Apache::lonhomework::showhash(%slotinfo);
6692: my ($tmp)=keys(%slotinfo);
6693: if ($tmp=~/^error:/) { return (); }
6694: $remembered{$key} = $slotinfo{$which};
6695: }
1.616 albertel 6696: if (ref($slotinfo{$which}) eq 'HASH') {
6697: return %{$slotinfo{$which}};
6698: }
6699: return $slotinfo{$which};
1.614 albertel 6700: }
1.31 www 6701: # ------------------------------------------------- Update symbolic store links
6702:
6703: sub symblist {
6704: my ($mapname,%newhash)=@_;
1.438 www 6705: $mapname=&deversion(&declutter($mapname));
1.31 www 6706: my %hash;
1.620 albertel 6707: if (($env{'request.course.fn'}) && (%newhash)) {
6708: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 6709: &GDBM_WRCREAT(),0640)) {
1.711 albertel 6710: foreach my $url (keys %newhash) {
6711: next if ($url eq 'last_known'
6712: && $env{'form.no_update_last_known'});
6713: $hash{declutter($url)}=&encode_symb($mapname,
6714: $newhash{$url}->[1],
6715: $newhash{$url}->[0]);
1.191 harris41 6716: }
1.31 www 6717: if (untie(%hash)) {
6718: return 'ok';
6719: }
6720: }
6721: }
6722: return 'error';
1.212 www 6723: }
6724:
6725: # --------------------------------------------------------------- Verify a symb
6726:
6727: sub symbverify {
1.510 www 6728: my ($symb,$thisurl)=@_;
6729: my $thisfn=$thisurl;
1.439 www 6730: $thisfn=&declutter($thisfn);
1.215 www 6731: # direct jump to resource in page or to a sequence - will construct own symbs
6732: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
6733: # check URL part
1.409 www 6734: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 6735:
1.431 www 6736: unless ($url eq $thisfn) { return 0; }
1.213 www 6737:
1.216 www 6738: $symb=&symbclean($symb);
1.510 www 6739: $thisurl=&deversion($thisurl);
1.439 www 6740: $thisfn=&deversion($thisfn);
1.213 www 6741:
6742: my %bighash;
6743: my $okay=0;
1.431 www 6744:
1.620 albertel 6745: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 6746: &GDBM_READER(),0640)) {
1.510 www 6747: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 6748: unless ($ids) {
1.510 www 6749: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 6750: }
6751: if ($ids) {
6752: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 6753: foreach my $id (split(/\,/,$ids)) {
6754: my ($mapid,$resid)=split(/\./,$id);
1.216 www 6755: if (
6756: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
6757: eq $symb) {
1.620 albertel 6758: if (($env{'request.role.adv'}) ||
1.800 albertel 6759: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 6760: $okay=1;
6761: }
6762: }
1.216 www 6763: }
6764: }
1.213 www 6765: untie(%bighash);
6766: }
6767: return $okay;
1.31 www 6768: }
6769:
1.210 www 6770: # --------------------------------------------------------------- Clean-up symb
6771:
6772: sub symbclean {
6773: my $symb=shift;
1.568 albertel 6774: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 6775: # remove version from map
6776: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 6777:
1.210 www 6778: # remove version from URL
6779: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 6780:
1.507 www 6781: # remove wrapper
6782:
1.510 www 6783: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 6784: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 6785: return $symb;
1.409 www 6786: }
6787:
6788: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 6789:
6790: sub encode_symb {
6791: my ($map,$resid,$url)=@_;
6792: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
6793: }
1.409 www 6794:
6795: sub decode_symb {
1.568 albertel 6796: my $symb=shift;
6797: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
6798: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 6799: return (&fixversion($map),$resid,&fixversion($url));
6800: }
6801:
6802: sub fixversion {
6803: my $fn=shift;
1.609 banghart 6804: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 6805: my %bighash;
6806: my $uri=&clutter($fn);
1.620 albertel 6807: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 6808: # is this cached?
1.599 albertel 6809: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 6810: if (defined($cached)) { return $result; }
6811: # unfortunately not cached, or expired
1.620 albertel 6812: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 6813: &GDBM_READER(),0640)) {
6814: if ($bighash{'version_'.$uri}) {
6815: my $version=$bighash{'version_'.$uri};
1.444 www 6816: unless (($version eq 'mostrecent') ||
6817: ($version==&getversion($uri))) {
1.440 www 6818: $uri=~s/\.(\w+)$/\.$version\.$1/;
6819: }
6820: }
6821: untie %bighash;
1.413 www 6822: }
1.599 albertel 6823: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 6824: }
6825:
6826: sub deversion {
6827: my $url=shift;
6828: $url=~s/\.\d+\.(\w+)$/\.$1/;
6829: return $url;
1.210 www 6830: }
6831:
1.31 www 6832: # ------------------------------------------------------ Return symb list entry
6833:
6834: sub symbread {
1.249 www 6835: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 6836: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 6837: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 6838: # no filename provided? try from environment
1.44 www 6839: unless ($thisfn) {
1.620 albertel 6840: if ($env{'request.symb'}) {
6841: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 6842: }
1.620 albertel 6843: $thisfn=$env{'request.filename'};
1.44 www 6844: }
1.569 albertel 6845: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 6846: # is that filename actually a symb? Verify, clean, and return
6847: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 6848: if (&symbverify($thisfn,$1)) {
1.620 albertel 6849: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 6850: }
1.242 www 6851: }
1.44 www 6852: $thisfn=declutter($thisfn);
1.31 www 6853: my %hash;
1.37 www 6854: my %bighash;
6855: my $syval='';
1.620 albertel 6856: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 6857: my $targetfn = $thisfn;
1.609 banghart 6858: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 6859: $targetfn = 'adm/wrapper/'.$thisfn;
6860: }
1.687 albertel 6861: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
6862: $targetfn=$1;
6863: }
1.620 albertel 6864: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 6865: &GDBM_READER(),0640)) {
1.481 raeburn 6866: $syval=$hash{$targetfn};
1.37 www 6867: untie(%hash);
6868: }
6869: # ---------------------------------------------------------- There was an entry
6870: if ($syval) {
1.601 albertel 6871: #unless ($syval=~/\_\d+$/) {
1.620 albertel 6872: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601 albertel 6873: #&appenv('request.ambiguous' => $thisfn);
1.620 albertel 6874: #return $env{$cache_str}='';
1.601 albertel 6875: #}
6876: #$syval.=$1;
6877: #}
1.37 www 6878: } else {
6879: # ------------------------------------------------------- Was not in symb table
1.620 albertel 6880: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 6881: &GDBM_READER(),0640)) {
1.37 www 6882: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 6883: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 6884: unless ($ids) {
6885: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 6886: }
6887: unless ($ids) {
6888: # alias?
6889: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 6890: }
1.37 www 6891: if ($ids) {
6892: # ------------------------------------------------------------------- Has ID(s)
6893: my @possibilities=split(/\,/,$ids);
1.39 www 6894: if ($#possibilities==0) {
6895: # ----------------------------------------------- There is only one possibility
1.37 www 6896: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 6897: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6898: $resid,$thisfn);
1.249 www 6899: } elsif (!$donotrecurse) {
1.39 www 6900: # ------------------------------------------ There is more than one possibility
6901: my $realpossible=0;
1.800 albertel 6902: foreach my $id (@possibilities) {
6903: my $file=$bighash{'src_'.$id};
1.39 www 6904: if (&allowed('bre',$file)) {
1.800 albertel 6905: my ($mapid,$resid)=split(/\./,$id);
1.39 www 6906: if ($bighash{'map_type_'.$mapid} ne 'page') {
6907: $realpossible++;
1.626 albertel 6908: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6909: $resid,$thisfn);
1.39 www 6910: }
6911: }
1.191 harris41 6912: }
1.39 www 6913: if ($realpossible!=1) { $syval=''; }
1.249 www 6914: } else {
6915: $syval='';
1.37 www 6916: }
6917: }
6918: untie(%bighash)
1.481 raeburn 6919: }
1.31 www 6920: }
1.62 www 6921: if ($syval) {
1.620 albertel 6922: return $env{$cache_str}=$syval;
1.62 www 6923: }
1.31 www 6924: }
1.44 www 6925: &appenv('request.ambiguous' => $thisfn);
1.620 albertel 6926: return $env{$cache_str}='';
1.31 www 6927: }
6928:
6929: # ---------------------------------------------------------- Return random seed
6930:
1.32 www 6931: sub numval {
6932: my $txt=shift;
6933: $txt=~tr/A-J/0-9/;
6934: $txt=~tr/a-j/0-9/;
6935: $txt=~tr/K-T/0-9/;
6936: $txt=~tr/k-t/0-9/;
6937: $txt=~tr/U-Z/0-5/;
6938: $txt=~tr/u-z/0-5/;
6939: $txt=~s/\D//g;
1.564 albertel 6940: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 6941: return int($txt);
1.368 albertel 6942: }
6943:
1.484 albertel 6944: sub numval2 {
6945: my $txt=shift;
6946: $txt=~tr/A-J/0-9/;
6947: $txt=~tr/a-j/0-9/;
6948: $txt=~tr/K-T/0-9/;
6949: $txt=~tr/k-t/0-9/;
6950: $txt=~tr/U-Z/0-5/;
6951: $txt=~tr/u-z/0-5/;
6952: $txt=~s/\D//g;
6953: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6954: my $total;
6955: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 6956: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 6957: return int($total);
6958: }
6959:
1.575 albertel 6960: sub numval3 {
6961: use integer;
6962: my $txt=shift;
6963: $txt=~tr/A-J/0-9/;
6964: $txt=~tr/a-j/0-9/;
6965: $txt=~tr/K-T/0-9/;
6966: $txt=~tr/k-t/0-9/;
6967: $txt=~tr/U-Z/0-5/;
6968: $txt=~tr/u-z/0-5/;
6969: $txt=~s/\D//g;
6970: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6971: my $total;
6972: foreach my $val (@txts) { $total+=$val; }
6973: if ($_64bit) { $total=(($total<<32)>>32); }
6974: return $total;
6975: }
6976:
1.675 albertel 6977: sub digest {
6978: my ($data)=@_;
6979: my $digest=&Digest::MD5::md5($data);
6980: my ($a,$b,$c,$d)=unpack("iiii",$digest);
6981: my ($e,$f);
6982: {
6983: use integer;
6984: $e=($a+$b);
6985: $f=($c+$d);
6986: if ($_64bit) {
6987: $e=(($e<<32)>>32);
6988: $f=(($f<<32)>>32);
6989: }
6990: }
6991: if (wantarray) {
6992: return ($e,$f);
6993: } else {
6994: my $g;
6995: {
6996: use integer;
6997: $g=($e+$f);
6998: if ($_64bit) {
6999: $g=(($g<<32)>>32);
7000: }
7001: }
7002: return $g;
7003: }
7004: }
7005:
1.368 albertel 7006: sub latest_rnd_algorithm_id {
1.675 albertel 7007: return '64bit5';
1.366 albertel 7008: }
1.32 www 7009:
1.503 albertel 7010: sub get_rand_alg {
7011: my ($courseid)=@_;
1.790 albertel 7012: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 7013: if ($courseid) {
1.620 albertel 7014: return $env{"course.$courseid.rndseed"};
1.503 albertel 7015: }
7016: return &latest_rnd_algorithm_id();
7017: }
7018:
1.562 albertel 7019: sub validCODE {
7020: my ($CODE)=@_;
7021: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
7022: return 0;
7023: }
7024:
1.491 albertel 7025: sub getCODE {
1.620 albertel 7026: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 7027: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
7028: defined($Apache::lonhomework::parsing_a_task) ) &&
7029: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 7030: return $Apache::lonhomework::history{'resource.CODE'};
7031: }
7032: return undef;
7033: }
7034:
1.31 www 7035: sub rndseed {
1.155 albertel 7036: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 7037: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155 albertel 7038: if (!$symb) {
1.366 albertel 7039: unless ($symb=$wsymb) { return time; }
7040: }
7041: if (!$courseid) { $courseid=$wcourseid; }
7042: if (!$domain) { $domain=$wdomain; }
7043: if (!$username) { $username=$wusername }
1.503 albertel 7044: my $which=&get_rand_alg();
1.803 albertel 7045:
1.491 albertel 7046: if (defined(&getCODE())) {
1.675 albertel 7047: if ($which eq '64bit5') {
7048: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
7049: } elsif ($which eq '64bit4') {
1.575 albertel 7050: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
7051: } else {
7052: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
7053: }
1.675 albertel 7054: } elsif ($which eq '64bit5') {
7055: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 7056: } elsif ($which eq '64bit4') {
7057: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 7058: } elsif ($which eq '64bit3') {
7059: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 7060: } elsif ($which eq '64bit2') {
7061: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 7062: } elsif ($which eq '64bit') {
7063: return &rndseed_64bit($symb,$courseid,$domain,$username);
7064: }
7065: return &rndseed_32bit($symb,$courseid,$domain,$username);
7066: }
7067:
7068: sub rndseed_32bit {
7069: my ($symb,$courseid,$domain,$username)=@_;
7070: {
7071: use integer;
7072: my $symbchck=unpack("%32C*",$symb) << 27;
7073: my $symbseed=numval($symb) << 22;
7074: my $namechck=unpack("%32C*",$username) << 17;
7075: my $nameseed=numval($username) << 12;
7076: my $domainseed=unpack("%32C*",$domain) << 7;
7077: my $courseseed=unpack("%32C*",$courseid);
7078: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 7079: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7080: #&logthis("rndseed :$num:$symb");
1.564 albertel 7081: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 7082: return $num;
7083: }
7084: }
7085:
7086: sub rndseed_64bit {
7087: my ($symb,$courseid,$domain,$username)=@_;
7088: {
7089: use integer;
7090: my $symbchck=unpack("%32S*",$symb) << 21;
7091: my $symbseed=numval($symb) << 10;
7092: my $namechck=unpack("%32S*",$username);
7093:
7094: my $nameseed=numval($username) << 21;
7095: my $domainseed=unpack("%32S*",$domain) << 10;
7096: my $courseseed=unpack("%32S*",$courseid);
7097:
7098: my $num1=$symbchck+$symbseed+$namechck;
7099: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7100: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7101: #&logthis("rndseed :$num:$symb");
1.564 albertel 7102: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 7103: return "$num1,$num2";
1.155 albertel 7104: }
1.366 albertel 7105: }
7106:
1.443 albertel 7107: sub rndseed_64bit2 {
7108: my ($symb,$courseid,$domain,$username)=@_;
7109: {
7110: use integer;
7111: # strings need to be an even # of cahracters long, it it is odd the
7112: # last characters gets thrown away
7113: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7114: my $symbseed=numval($symb) << 10;
7115: my $namechck=unpack("%32S*",$username.' ');
7116:
7117: my $nameseed=numval($username) << 21;
1.501 albertel 7118: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7119: my $courseseed=unpack("%32S*",$courseid.' ');
7120:
7121: my $num1=$symbchck+$symbseed+$namechck;
7122: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7123: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7124: #&logthis("rndseed :$num:$symb");
1.803 albertel 7125: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 7126: return "$num1,$num2";
7127: }
7128: }
7129:
7130: sub rndseed_64bit3 {
7131: my ($symb,$courseid,$domain,$username)=@_;
7132: {
7133: use integer;
7134: # strings need to be an even # of cahracters long, it it is odd the
7135: # last characters gets thrown away
7136: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7137: my $symbseed=numval2($symb) << 10;
7138: my $namechck=unpack("%32S*",$username.' ');
7139:
7140: my $nameseed=numval2($username) << 21;
1.443 albertel 7141: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7142: my $courseseed=unpack("%32S*",$courseid.' ');
7143:
7144: my $num1=$symbchck+$symbseed+$namechck;
7145: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7146: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7147: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 7148: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7149:
1.503 albertel 7150: return "$num1:$num2";
1.443 albertel 7151: }
7152: }
7153:
1.575 albertel 7154: sub rndseed_64bit4 {
7155: my ($symb,$courseid,$domain,$username)=@_;
7156: {
7157: use integer;
7158: # strings need to be an even # of cahracters long, it it is odd the
7159: # last characters gets thrown away
7160: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7161: my $symbseed=numval3($symb) << 10;
7162: my $namechck=unpack("%32S*",$username.' ');
7163:
7164: my $nameseed=numval3($username) << 21;
7165: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7166: my $courseseed=unpack("%32S*",$courseid.' ');
7167:
7168: my $num1=$symbchck+$symbseed+$namechck;
7169: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7170: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7171: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 7172: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7173:
7174: return "$num1:$num2";
7175: }
7176: }
7177:
1.675 albertel 7178: sub rndseed_64bit5 {
7179: my ($symb,$courseid,$domain,$username)=@_;
7180: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
7181: return "$num1:$num2";
7182: }
7183:
1.366 albertel 7184: sub rndseed_CODE_64bit {
7185: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 7186: {
1.366 albertel 7187: use integer;
1.443 albertel 7188: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 7189: my $symbseed=numval2($symb);
1.491 albertel 7190: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7191: my $CODEseed=numval(&getCODE());
1.443 albertel 7192: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 7193: my $num1=$symbseed+$CODEchck;
7194: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7195: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7196: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 7197: if ($_64bit) { $num1=(($num1<<32)>>32); }
7198: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 7199: return "$num1:$num2";
1.366 albertel 7200: }
7201: }
7202:
1.575 albertel 7203: sub rndseed_CODE_64bit4 {
7204: my ($symb,$courseid,$domain,$username)=@_;
7205: {
7206: use integer;
7207: my $symbchck=unpack("%32S*",$symb.' ') << 16;
7208: my $symbseed=numval3($symb);
7209: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7210: my $CODEseed=numval3(&getCODE());
7211: my $courseseed=unpack("%32S*",$courseid.' ');
7212: my $num1=$symbseed+$CODEchck;
7213: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7214: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7215: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 7216: if ($_64bit) { $num1=(($num1<<32)>>32); }
7217: if ($_64bit) { $num2=(($num2<<32)>>32); }
7218: return "$num1:$num2";
7219: }
7220: }
7221:
1.675 albertel 7222: sub rndseed_CODE_64bit5 {
7223: my ($symb,$courseid,$domain,$username)=@_;
7224: my $code = &getCODE();
7225: my ($num1,$num2)=&digest("$symb,$courseid,$code");
7226: return "$num1:$num2";
7227: }
7228:
1.366 albertel 7229: sub setup_random_from_rndseed {
7230: my ($rndseed)=@_;
1.503 albertel 7231: if ($rndseed =~/([,:])/) {
7232: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 7233: &Math::Random::random_set_seed(abs($num1),abs($num2));
7234: } else {
7235: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 7236: }
1.36 albertel 7237: }
7238:
1.474 albertel 7239: sub latest_receipt_algorithm_id {
1.835 albertel 7240: return 'receipt3';
1.474 albertel 7241: }
7242:
1.480 www 7243: sub recunique {
7244: my $fucourseid=shift;
7245: my $unique;
1.835 albertel 7246: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
7247: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7248: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 7249: } else {
7250: $unique=$perlvar{'lonReceipt'};
7251: }
7252: return unpack("%32C*",$unique);
7253: }
7254:
7255: sub recprefix {
7256: my $fucourseid=shift;
7257: my $prefix;
1.835 albertel 7258: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
7259: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7260: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 7261: } else {
7262: $prefix=$perlvar{'lonHostID'};
7263: }
7264: return unpack("%32C*",$prefix);
7265: }
7266:
1.76 www 7267: sub ireceipt {
1.474 albertel 7268: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 7269:
7270: my $return =&recprefix($fucourseid).'-';
7271:
7272: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
7273: $env{'request.state'} eq 'construct') {
7274: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
7275: return $return;
7276: }
7277:
1.76 www 7278: my $cuname=unpack("%32C*",$funame);
7279: my $cudom=unpack("%32C*",$fudom);
7280: my $cucourseid=unpack("%32C*",$fucourseid);
7281: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 7282: my $cunique=&recunique($fucourseid);
1.474 albertel 7283: my $cpart=unpack("%32S*",$part);
1.835 albertel 7284: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
7285:
1.790 albertel 7286: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 7287:
7288: $return.= ($cunique%$cuname+
7289: $cunique%$cudom+
7290: $cusymb%$cuname+
7291: $cusymb%$cudom+
7292: $cucourseid%$cuname+
7293: $cucourseid%$cudom+
7294: $cpart%$cuname+
7295: $cpart%$cudom);
7296: } else {
7297: $return.= ($cunique%$cuname+
7298: $cunique%$cudom+
7299: $cusymb%$cuname+
7300: $cusymb%$cudom+
7301: $cucourseid%$cuname+
7302: $cucourseid%$cudom);
7303: }
7304: return $return;
1.76 www 7305: }
7306:
7307: sub receipt {
1.474 albertel 7308: my ($part)=@_;
1.790 albertel 7309: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 7310: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 7311: }
1.260 ng 7312:
1.790 albertel 7313: sub whichuser {
7314: my ($passedsymb)=@_;
7315: my ($symb,$courseid,$domain,$name,$publicuser);
7316: if (defined($env{'form.grade_symb'})) {
7317: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
7318: my $allowed=&allowed('vgr',$tmp_courseid);
7319: if (!$allowed &&
7320: exists($env{'request.course.sec'}) &&
7321: $env{'request.course.sec'} !~ /^\s*$/) {
7322: $allowed=&allowed('vgr',$tmp_courseid.
7323: '/'.$env{'request.course.sec'});
7324: }
7325: if ($allowed) {
7326: ($symb)=&get_env_multiple('form.grade_symb');
7327: $courseid=$tmp_courseid;
7328: ($domain)=&get_env_multiple('form.grade_domain');
7329: ($name)=&get_env_multiple('form.grade_username');
7330: return ($symb,$courseid,$domain,$name,$publicuser);
7331: }
7332: }
7333: if (!$passedsymb) {
7334: $symb=&symbread();
7335: } else {
7336: $symb=$passedsymb;
7337: }
7338: $courseid=$env{'request.course.id'};
7339: $domain=$env{'user.domain'};
7340: $name=$env{'user.name'};
7341: if ($name eq 'public' && $domain eq 'public') {
7342: if (!defined($env{'form.username'})) {
7343: $env{'form.username'}.=time.rand(10000000);
7344: }
7345: $name.=$env{'form.username'};
7346: }
7347: return ($symb,$courseid,$domain,$name,$publicuser);
7348:
7349: }
7350:
1.36 albertel 7351: # ------------------------------------------------------------ Serves up a file
1.472 albertel 7352: # returns either the contents of the file or
7353: # -1 if the file doesn't exist
1.481 raeburn 7354: #
7355: # if the target is a file that was uploaded via DOCS,
7356: # a check will be made to see if a current copy exists on the local server,
7357: # if it does this will be served, otherwise a copy will be retrieved from
7358: # the home server for the course and stored in /home/httpd/html/userfiles on
7359: # the local server.
1.472 albertel 7360:
1.36 albertel 7361: sub getfile {
1.538 albertel 7362: my ($file) = @_;
1.609 banghart 7363: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 7364: &repcopy($file);
7365: return &readfile($file);
7366: }
7367:
7368: sub repcopy_userfile {
7369: my ($file)=@_;
1.609 banghart 7370: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 7371: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 7372: my ($cdom,$cnum,$filename) =
1.811 albertel 7373: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 7374: my $uri="/uploaded/$cdom/$cnum/$filename";
7375: if (-e "$file") {
1.828 www 7376: # we already have a local copy, check it out
1.538 albertel 7377: my @fileinfo = stat($file);
1.828 www 7378: my $rtncode;
7379: my $info;
1.538 albertel 7380: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 7381: if ($lwpresp ne 'ok') {
1.828 www 7382: # there is no such file anymore, even though we had a local copy
1.482 albertel 7383: if ($rtncode eq '404') {
1.538 albertel 7384: unlink($file);
1.482 albertel 7385: }
7386: return -1;
7387: }
7388: if ($info < $fileinfo[9]) {
1.828 www 7389: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 7390: return 'ok';
1.828 www 7391: } else {
7392: # the file is outdated, get rid of it
7393: unlink($file);
1.482 albertel 7394: }
1.828 www 7395: }
7396: # one way or the other, at this point, we don't have the file
7397: # construct the correct path for the file
7398: my @parts = ($cdom,$cnum);
7399: if ($filename =~ m|^(.+)/[^/]+$|) {
7400: push @parts, split(/\//,$1);
7401: }
7402: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
7403: foreach my $part (@parts) {
7404: $path .= '/'.$part;
7405: if (!-e $path) {
7406: mkdir($path,0770);
1.482 albertel 7407: }
7408: }
1.828 www 7409: # now the path exists for sure
7410: # get a user agent
7411: my $ua=new LWP::UserAgent;
7412: my $transferfile=$file.'.in.transfer';
7413: # FIXME: this should flock
7414: if (-e $transferfile) { return 'ok'; }
7415: my $request;
7416: $uri=~s/^\///;
1.838 albertel 7417: $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828 www 7418: my $response=$ua->request($request,$transferfile);
7419: # did it work?
7420: if ($response->is_error()) {
7421: unlink($transferfile);
7422: &logthis("Userfile repcopy failed for $uri");
7423: return -1;
7424: }
7425: # worked, rename the transfer file
7426: rename($transferfile,$file);
1.607 raeburn 7427: return 'ok';
1.481 raeburn 7428: }
7429:
1.517 albertel 7430: sub tokenwrapper {
7431: my $uri=shift;
1.552 albertel 7432: $uri=~s|^http\://([^/]+)||;
7433: $uri=~s|^/||;
1.620 albertel 7434: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 7435: my $token=$1;
1.552 albertel 7436: my (undef,$udom,$uname,$file)=split('/',$uri,4);
7437: if ($udom && $uname && $file) {
7438: $file=~s|(\?\.*)*$||;
1.620 albertel 7439: &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838 albertel 7440: return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517 albertel 7441: (($uri=~/\?/)?'&':'?').'token='.$token.
7442: '&tokenissued='.$perlvar{'lonHostID'};
7443: } else {
7444: return '/adm/notfound.html';
7445: }
7446: }
7447:
1.828 www 7448: # call with reqtype HEAD: get last modification time
7449: # call with reqtype GET: get the file contents
7450: # Do not call this with reqtype GET for large files! It loads everything into memory
7451: #
1.481 raeburn 7452: sub getuploaded {
7453: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
7454: $uri=~s/^\///;
1.838 albertel 7455: $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481 raeburn 7456: my $ua=new LWP::UserAgent;
7457: my $request=new HTTP::Request($reqtype,$uri);
7458: my $response=$ua->request($request);
7459: $$rtncode = $response->code;
1.482 albertel 7460: if (! $response->is_success()) {
7461: return 'failed';
7462: }
7463: if ($reqtype eq 'HEAD') {
1.486 www 7464: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 7465: } elsif ($reqtype eq 'GET') {
7466: $$info = $response->content;
1.472 albertel 7467: }
1.482 albertel 7468: return 'ok';
1.36 albertel 7469: }
7470:
1.481 raeburn 7471: sub readfile {
7472: my $file = shift;
7473: if ( (! -e $file ) || ($file eq '') ) { return -1; };
7474: my $fh;
7475: open($fh,"<$file");
7476: my $a='';
1.800 albertel 7477: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 7478: return $a;
7479: }
7480:
1.36 albertel 7481: sub filelocation {
1.590 banghart 7482: my ($dir,$file) = @_;
7483: my $location;
7484: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 7485:
7486: if ($file =~ m-^/adm/-) {
7487: $file=~s-^/adm/wrapper/-/-;
7488: $file=~s-^/adm/coursedocs/showdoc/-/-;
7489: }
1.590 banghart 7490: if ($file=~m:^/~:) { # is a contruction space reference
7491: $location = $file;
7492: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 7493: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 7494: # is a correct contruction space reference
7495: $location = $file;
1.609 banghart 7496: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 7497: my ($udom,$uname,$filename)=
1.811 albertel 7498: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 7499: my $home=&homeserver($uname,$udom);
7500: my $is_me=0;
7501: my @ids=¤t_machine_ids();
7502: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
7503: if ($is_me) {
1.740 www 7504: $location=&propath($udom,$uname).
1.590 banghart 7505: '/userfiles/'.$filename;
7506: } else {
7507: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
7508: $udom.'/'.$uname.'/'.$filename;
7509: }
7510: } else {
7511: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
7512: $file=~s:^/res/:/:;
7513: if ( !( $file =~ m:^/:) ) {
7514: $location = $dir. '/'.$file;
7515: } else {
7516: $location = '/home/httpd/html/res'.$file;
7517: }
1.59 albertel 7518: }
1.590 banghart 7519: $location=~s://+:/:g; # remove duplicate /
7520: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
7521: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
7522: return $location;
1.46 www 7523: }
1.36 albertel 7524:
1.46 www 7525: sub hreflocation {
7526: my ($dir,$file)=@_;
1.460 albertel 7527: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666 albertel 7528: $file=filelocation($dir,$file);
1.700 albertel 7529: } elsif ($file=~m-^/adm/-) {
7530: $file=~s-^/adm/wrapper/-/-;
7531: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 7532: }
7533: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
7534: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 7535: } elsif ($file=~m-/home/($match_username)/public_html/-) {
7536: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 7537: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 7538: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 7539: -/uploaded/$1/$2/-x;
1.46 www 7540: }
1.462 albertel 7541: return $file;
1.465 albertel 7542: }
7543:
7544: sub current_machine_domains {
1.853 albertel 7545: return &machine_domains(&hostname($perlvar{'lonHostID'}));
7546: }
7547:
7548: sub machine_domains {
7549: my ($hostname) = @_;
1.465 albertel 7550: my @domains;
1.838 albertel 7551: my %hostname = &all_hostnames();
1.465 albertel 7552: while( my($id, $name) = each(%hostname)) {
1.467 matthew 7553: # &logthis("-$id-$name-$hostname-");
1.465 albertel 7554: if ($hostname eq $name) {
1.844 albertel 7555: push(@domains,&host_domain($id));
1.465 albertel 7556: }
7557: }
7558: return @domains;
7559: }
7560:
7561: sub current_machine_ids {
1.853 albertel 7562: return &machine_ids(&hostname($perlvar{'lonHostID'}));
7563: }
7564:
7565: sub machine_ids {
7566: my ($hostname) = @_;
7567: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 7568: my @ids;
1.838 albertel 7569: my %hostname = &all_hostnames();
1.465 albertel 7570: while( my($id, $name) = each(%hostname)) {
1.467 matthew 7571: # &logthis("-$id-$name-$hostname-");
1.465 albertel 7572: if ($hostname eq $name) {
7573: push(@ids,$id);
7574: }
7575: }
7576: return @ids;
1.31 www 7577: }
7578:
1.824 raeburn 7579: sub additional_machine_domains {
7580: my @domains;
7581: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
7582: while( my $line = <$fh>) {
7583: $line =~ s/\s//g;
7584: push(@domains,$line);
7585: }
7586: return @domains;
7587: }
7588:
7589: sub default_login_domain {
7590: my $domain = $perlvar{'lonDefDomain'};
7591: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
7592: foreach my $posdom (¤t_machine_domains(),
7593: &additional_machine_domains()) {
7594: if (lc($posdom) eq lc($testdomain)) {
7595: $domain=$posdom;
7596: last;
7597: }
7598: }
7599: return $domain;
7600: }
7601:
1.31 www 7602: # ------------------------------------------------------------- Declutters URLs
7603:
7604: sub declutter {
7605: my $thisfn=shift;
1.569 albertel 7606: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 7607: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 7608: $thisfn=~s/^\///;
1.697 albertel 7609: $thisfn=~s|^adm/wrapper/||;
7610: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 7611: $thisfn=~s/^res\///;
1.235 www 7612: $thisfn=~s/\?.+$//;
1.268 www 7613: return $thisfn;
7614: }
7615:
7616: # ------------------------------------------------------------- Clutter up URLs
7617:
7618: sub clutter {
7619: my $thisfn='/'.&declutter(shift);
1.609 banghart 7620: unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) {
1.270 www 7621: $thisfn='/res'.$thisfn;
7622: }
1.694 albertel 7623: if ($thisfn !~m|/adm|) {
1.695 albertel 7624: if ($thisfn =~ m|/ext/|) {
1.694 albertel 7625: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 7626: } else {
7627: my ($ext) = ($thisfn =~ /\.(\w+)$/);
7628: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 7629: if ($embstyle eq 'ssi'
7630: || ($embstyle eq 'hdn')
7631: || ($embstyle eq 'rat')
7632: || ($embstyle eq 'prv')
7633: || ($embstyle eq 'ign')) {
7634: #do nothing with these
7635: } elsif (($embstyle eq 'img')
1.695 albertel 7636: || ($embstyle eq 'emb')
7637: || ($embstyle eq 'wrp')) {
7638: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 7639: } elsif ($embstyle eq 'unk'
7640: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 7641: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 7642: } else {
1.718 www 7643: # &logthis("Got a blank emb style");
1.695 albertel 7644: }
1.694 albertel 7645: }
7646: }
1.31 www 7647: return $thisfn;
1.12 www 7648: }
7649:
1.787 albertel 7650: sub clutter_with_no_wrapper {
7651: my $uri = &clutter(shift);
7652: if ($uri =~ m-^/adm/-) {
7653: $uri =~ s-^/adm/wrapper/-/-;
7654: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
7655: }
7656: return $uri;
7657: }
7658:
1.557 albertel 7659: sub freeze_escape {
7660: my ($value)=@_;
7661: if (ref($value)) {
7662: $value=&nfreeze($value);
7663: return '__FROZEN__'.&escape($value);
7664: }
7665: return &escape($value);
7666: }
7667:
1.11 www 7668:
1.557 albertel 7669: sub thaw_unescape {
7670: my ($value)=@_;
7671: if ($value =~ /^__FROZEN__/) {
7672: substr($value,0,10,undef);
7673: $value=&unescape($value);
7674: return &thaw($value);
7675: }
7676: return &unescape($value);
7677: }
7678:
1.436 albertel 7679: sub correct_line_ends {
7680: my ($result)=@_;
7681: $$result =~s/\r\n/\n/mg;
7682: $$result =~s/\r/\n/mg;
1.415 albertel 7683: }
1.1 albertel 7684: # ================================================================ Main Program
7685:
1.184 www 7686: sub goodbye {
1.204 albertel 7687: &logthis("Starting Shut down");
1.443 albertel 7688: #not converted to using infrastruture and probably shouldn't be
1.599 albertel 7689: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443 albertel 7690: #converted
1.599 albertel 7691: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
7692: &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
7693: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
7694: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425 albertel 7695: #1.1 only
1.599 albertel 7696: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
7697: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
7698: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
7699: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
7700: &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
7701: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
7702: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 7703: &flushcourselogs();
7704: &logthis("Shutting down");
7705: }
7706:
1.179 www 7707: BEGIN {
1.856 albertel 7708:
1.228 harris41 7709: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195 www 7710: unless ($readit) {
1.217 harris41 7711: {
1.781 raeburn 7712: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
7713: %perlvar = (%perlvar,%{$configvars});
1.227 harris41 7714: }
1.1 albertel 7715:
1.852 albertel 7716: sub get_dns {
7717: my ($url,$func) = @_;
7718: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
7719: foreach my $dns (<$config>) {
7720: next if ($dns !~ /^\^(\S*)/x);
7721: $dns = $1;
7722: my $ua=new LWP::UserAgent;
7723: my $request=new HTTP::Request('GET',"http://$dns$url");
7724: my $response=$ua->request($request);
7725: next if ($response->is_error());
7726: my @content = split("\n",$response->content);
7727: &$func(\@content);
7728: }
7729: close($config);
7730: }
1.327 albertel 7731: # ------------------------------------------------------------ Read domain file
7732: {
1.852 albertel 7733: my $loaded;
1.846 albertel 7734: my %domain;
7735:
1.852 albertel 7736: sub parse_domain_tab {
7737: my ($lines) = @_;
7738: foreach my $line (@$lines) {
7739: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 7740:
1.846 albertel 7741: chomp($line);
1.852 albertel 7742: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 7743: my %this_domain;
7744: foreach my $field ('description', 'auth_def', 'auth_arg_def',
7745: 'lang_def', 'city', 'longi', 'lati',
7746: 'primary') {
7747: $this_domain{$field} = shift(@elements);
7748: }
7749: $domain{$name} = \%this_domain;
1.852 albertel 7750: }
7751: }
7752:
7753: sub load_domain_tab {
7754: &get_dns('/adm/dns/domain',\&parse_domain_tab);
7755: my $fh;
7756: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
7757: my @lines = <$fh>;
7758: &parse_domain_tab(\@lines);
1.448 albertel 7759: }
1.852 albertel 7760: close($fh);
7761: $loaded = 1;
1.327 albertel 7762: }
1.846 albertel 7763:
7764: sub domain {
1.852 albertel 7765: &load_domain_tab() if (!$loaded);
7766:
1.846 albertel 7767: my ($name,$what) = @_;
7768: return if ( !exists($domain{$name}) );
7769:
7770: if (!$what) {
7771: return $domain{$name}{'description'};
7772: }
7773: return $domain{$name}{$what};
7774: }
1.327 albertel 7775: }
7776:
7777:
1.1 albertel 7778: # ------------------------------------------------------------- Read hosts file
7779: {
1.838 albertel 7780: my %hostname;
1.844 albertel 7781: my %hostdom;
1.845 albertel 7782: my %libserv;
1.852 albertel 7783: my $loaded;
7784:
7785: sub parse_hosts_tab {
7786: my ($file) = @_;
7787: foreach my $configline (@$file) {
7788: next if ($configline =~ /^(\#|\s*$ )/x);
7789: next if ($configline =~ /^\^/);
7790: chomp($configline);
7791: my ($id,$domain,$role,$name)=split(/:/,$configline);
7792: $name=~s/\s//g;
7793: if ($id && $domain && $role && $name) {
7794: $hostname{$id}=$name;
7795: $hostdom{$id}=$domain;
7796: if ($role eq 'library') { $libserv{$id}=$name; }
7797: }
7798: }
7799: }
1.1 albertel 7800:
1.852 albertel 7801: sub load_hosts_tab {
7802: &get_dns('/adm/dns/hosts',\&parse_hosts_tab);
7803: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
7804: my @config = <$config>;
7805: &parse_hosts_tab(\@config);
7806: close($config);
7807: $loaded=1;
1.1 albertel 7808: }
1.852 albertel 7809:
1.619 albertel 7810: # FIXME: dev server don't want this, production servers _do_ want this
1.654 albertel 7811: #&get_iphost();
1.838 albertel 7812:
7813: sub hostname {
1.852 albertel 7814: &load_hosts_tab() if (!$loaded);
7815:
1.838 albertel 7816: my ($lonid) = @_;
7817: return $hostname{$lonid};
7818: }
1.845 albertel 7819:
1.838 albertel 7820: sub all_hostnames {
1.852 albertel 7821: &load_hosts_tab() if (!$loaded);
7822:
1.838 albertel 7823: return %hostname;
7824: }
1.845 albertel 7825:
7826: sub is_library {
1.852 albertel 7827: &load_hosts_tab() if (!$loaded);
7828:
1.845 albertel 7829: return exists($libserv{$_[0]});
7830: }
7831:
7832: sub all_library {
1.852 albertel 7833: &load_hosts_tab() if (!$loaded);
7834:
1.845 albertel 7835: return %libserv;
7836: }
7837:
1.841 albertel 7838: sub get_servers {
1.852 albertel 7839: &load_hosts_tab() if (!$loaded);
7840:
1.841 albertel 7841: my ($domain,$type) = @_;
7842: my %possible_hosts = ($type eq 'library') ? %libserv
7843: : %hostname;
7844: my %result;
1.842 albertel 7845: if (ref($domain) eq 'ARRAY') {
7846: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 7847: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 7848: $result{$host} = $hostname;
7849: }
7850: }
7851: } else {
7852: while ( my ($host,$hostname) = each(%possible_hosts)) {
7853: if ($hostdom{$host} eq $domain) {
7854: $result{$host} = $hostname;
7855: }
1.841 albertel 7856: }
7857: }
7858: return %result;
7859: }
1.845 albertel 7860:
1.844 albertel 7861: sub host_domain {
1.852 albertel 7862: &load_hosts_tab() if (!$loaded);
7863:
1.844 albertel 7864: my ($lonid) = @_;
7865: return $hostdom{$lonid};
7866: }
7867:
1.841 albertel 7868: sub all_domains {
1.852 albertel 7869: &load_hosts_tab() if (!$loaded);
7870:
1.841 albertel 7871: my %seen;
7872: my @uniq = grep(!$seen{$_}++, values(%hostdom));
7873: return @uniq;
7874: }
1.1 albertel 7875: }
7876:
1.847 albertel 7877: {
7878: my %iphost;
1.856 albertel 7879: my %name_to_ip;
7880: my %lonid_to_ip;
1.847 albertel 7881: sub get_hosts_from_ip {
7882: my ($ip) = @_;
7883: my %iphosts = &get_iphost();
7884: if (ref($iphosts{$ip})) {
7885: return @{$iphosts{$ip}};
7886: }
7887: return;
1.839 albertel 7888: }
1.856 albertel 7889:
7890: sub get_host_ip {
7891: my ($lonid) = @_;
7892: if (exists($lonid_to_ip{$lonid})) {
7893: return $lonid_to_ip{$lonid};
7894: }
7895: my $name=&hostname($lonid);
7896: my $ip = gethostbyname($name);
7897: return if (!$ip || length($ip) ne 4);
7898: $ip=inet_ntoa($ip);
7899: $name_to_ip{$name} = $ip;
7900: $lonid_to_ip{$lonid} = $ip;
7901: return $ip;
7902: }
1.847 albertel 7903:
7904: sub get_iphost {
7905: if (%iphost) { return %iphost; }
7906: my %hostname = &all_hostnames();
7907: foreach my $id (keys(%hostname)) {
7908: my $name=$hostname{$id};
7909: my $ip;
7910: if (!exists($name_to_ip{$name})) {
7911: $ip = gethostbyname($name);
7912: if (!$ip || length($ip) ne 4) {
7913: &logthis("Skipping host $id name $name no IP found");
7914: next;
7915: }
7916: $ip=inet_ntoa($ip);
7917: $name_to_ip{$name} = $ip;
7918: } else {
7919: $ip = $name_to_ip{$name};
1.653 albertel 7920: }
1.856 albertel 7921: $lonid_to_ip{$id} = $ip;
1.847 albertel 7922: push(@{$iphost{$ip}},$id);
1.598 albertel 7923: }
1.847 albertel 7924: return %iphost;
1.598 albertel 7925: }
7926: }
7927:
1.1 albertel 7928: # ------------------------------------------------------ Read spare server file
7929: {
1.448 albertel 7930: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 7931:
7932: while (my $configline=<$config>) {
7933: chomp($configline);
1.284 matthew 7934: if ($configline) {
1.784 albertel 7935: my ($host,$type) = split(':',$configline,2);
1.785 albertel 7936: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 7937: push(@{ $spareid{$type} }, $host);
1.1 albertel 7938: }
7939: }
1.448 albertel 7940: close($config);
1.1 albertel 7941: }
1.11 www 7942: # ------------------------------------------------------------ Read permissions
7943: {
1.448 albertel 7944: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 7945:
7946: while (my $configline=<$config>) {
1.448 albertel 7947: chomp($configline);
7948: if ($configline) {
7949: my ($role,$perm)=split(/ /,$configline);
7950: if ($perm ne '') { $pr{$role}=$perm; }
7951: }
1.11 www 7952: }
1.448 albertel 7953: close($config);
1.11 www 7954: }
7955:
7956: # -------------------------------------------- Read plain texts for permissions
7957: {
1.448 albertel 7958: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 7959:
7960: while (my $configline=<$config>) {
1.448 albertel 7961: chomp($configline);
7962: if ($configline) {
1.742 raeburn 7963: my ($short,@plain)=split(/:/,$configline);
7964: %{$prp{$short}} = ();
7965: if (@plain > 0) {
7966: $prp{$short}{'std'} = $plain[0];
7967: for (my $i=1; $i<@plain; $i++) {
7968: $prp{$short}{'alt'.$i} = $plain[$i];
7969: }
7970: }
1.448 albertel 7971: }
1.135 www 7972: }
1.448 albertel 7973: close($config);
1.135 www 7974: }
7975:
7976: # ---------------------------------------------------------- Read package table
7977: {
1.448 albertel 7978: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 7979:
7980: while (my $configline=<$config>) {
1.483 albertel 7981: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 7982: chomp($configline);
7983: my ($short,$plain)=split(/:/,$configline);
7984: my ($pack,$name)=split(/\&/,$short);
7985: if ($plain ne '') {
7986: $packagetab{$pack.'&'.$name.'&name'}=$name;
7987: $packagetab{$short}=$plain;
7988: }
1.11 www 7989: }
1.448 albertel 7990: close($config);
1.329 matthew 7991: }
7992:
7993: # ------------- set up temporary directory
7994: {
7995: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
7996:
1.11 www 7997: }
7998:
1.794 albertel 7999: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
8000: 'compress_threshold'=> 20_000,
8001: });
1.185 www 8002:
1.281 www 8003: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 8004: $dumpcount=0;
1.22 www 8005:
1.163 harris41 8006: &logtouch();
1.672 albertel 8007: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 8008: $readit=1;
1.564 albertel 8009: {
8010: use integer;
8011: my $test=(2**32)+1;
1.568 albertel 8012: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 8013: &logthis(" Detected 64bit platform ($_64bit)");
8014: }
1.195 www 8015: }
1.1 albertel 8016: }
1.179 www 8017:
1.1 albertel 8018: 1;
1.191 harris41 8019: __END__
8020:
1.243 albertel 8021: =pod
8022:
1.191 harris41 8023: =head1 NAME
8024:
1.243 albertel 8025: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 8026:
8027: =head1 SYNOPSIS
8028:
1.243 albertel 8029: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 8030:
8031: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
8032:
1.243 albertel 8033: Common parameters:
8034:
8035: =over 4
8036:
8037: =item *
8038:
8039: $uname : an internal username (if $cname expecting a course Id specifically)
8040:
8041: =item *
8042:
8043: $udom : a domain (if $cdom expecting a course's domain specifically)
8044:
8045: =item *
8046:
8047: $symb : a resource instance identifier
8048:
8049: =item *
8050:
8051: $namespace : the name of a .db file that contains the data needed or
8052: being set.
8053:
8054: =back
8055:
1.394 bowersj2 8056: =head1 OVERVIEW
1.191 harris41 8057:
1.394 bowersj2 8058: lonnet provides subroutines which interact with the
8059: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
8060: about classes, users, and resources.
1.243 albertel 8061:
8062: For many of these objects you can also use this to store data about
8063: them or modify them in various ways.
1.191 harris41 8064:
1.394 bowersj2 8065: =head2 Symbs
1.191 harris41 8066:
1.394 bowersj2 8067: To identify a specific instance of a resource, LON-CAPA uses symbols
8068: or "symbs"X<symb>. These identifiers are built from the URL of the
8069: map, the resource number of the resource in the map, and the URL of
8070: the resource itself. The latter is somewhat redundant, but might help
8071: if maps change.
8072:
8073: An example is
8074:
8075: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
8076:
8077: The respective map entry is
8078:
8079: <resource id="19" src="/res/msu/korte/tests/part12.problem"
8080: title="Problem 2">
8081: </resource>
8082:
8083: Symbs are used by the random number generator, as well as to store and
8084: restore data specific to a certain instance of for example a problem.
8085:
8086: =head2 Storing And Retrieving Data
8087:
8088: X<store()>X<cstore()>X<restore()>Three of the most important functions
8089: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
8090: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
8091: is is the non-critical message twin of cstore. These functions are for
8092: handlers to store a perl hash to a user's permanent data space in an
8093: easy manner, and to retrieve it again on another call. It is expected
8094: that a handler would use this once at the beginning to retrieve data,
8095: and then again once at the end to send only the new data back.
8096:
8097: The data is stored in the user's data directory on the user's
8098: homeserver under the ID of the course.
8099:
8100: The hash that is returned by restore will have all of the previous
8101: value for all of the elements of the hash.
8102:
8103: Example:
8104:
8105: #creating a hash
8106: my %hash;
8107: $hash{'foo'}='bar';
8108:
8109: #storing it
8110: &Apache::lonnet::cstore(\%hash);
8111:
8112: #changing a value
8113: $hash{'foo'}='notbar';
8114:
8115: #adding a new value
8116: $hash{'bar'}='foo';
8117: &Apache::lonnet::cstore(\%hash);
8118:
8119: #retrieving the hash
8120: my %history=&Apache::lonnet::restore();
8121:
8122: #print the hash
8123: foreach my $key (sort(keys(%history))) {
8124: print("\%history{$key} = $history{$key}");
8125: }
8126:
8127: Will print out:
1.191 harris41 8128:
1.394 bowersj2 8129: %history{1:foo} = bar
8130: %history{1:keys} = foo:timestamp
8131: %history{1:timestamp} = 990455579
8132: %history{2:bar} = foo
8133: %history{2:foo} = notbar
8134: %history{2:keys} = foo:bar:timestamp
8135: %history{2:timestamp} = 990455580
8136: %history{bar} = foo
8137: %history{foo} = notbar
8138: %history{timestamp} = 990455580
8139: %history{version} = 2
8140:
8141: Note that the special hash entries C<keys>, C<version> and
8142: C<timestamp> were added to the hash. C<version> will be equal to the
8143: total number of versions of the data that have been stored. The
8144: C<timestamp> attribute will be the UNIX time the hash was
8145: stored. C<keys> is available in every historical section to list which
8146: keys were added or changed at a specific historical revision of a
8147: hash.
8148:
8149: B<Warning>: do not store the hash that restore returns directly. This
8150: will cause a mess since it will restore the historical keys as if the
8151: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 8152:
1.394 bowersj2 8153: Calling convention:
1.191 harris41 8154:
1.394 bowersj2 8155: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
8156: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 8157:
1.394 bowersj2 8158: For more detailed information, see lonnet specific documentation.
1.191 harris41 8159:
1.394 bowersj2 8160: =head1 RETURN MESSAGES
1.191 harris41 8161:
1.394 bowersj2 8162: =over 4
1.191 harris41 8163:
1.394 bowersj2 8164: =item * B<con_lost>: unable to contact remote host
1.191 harris41 8165:
1.394 bowersj2 8166: =item * B<con_delayed>: unable to contact remote host, message will be delivered
8167: when the connection is brought back up
1.191 harris41 8168:
1.394 bowersj2 8169: =item * B<con_failed>: unable to contact remote host and unable to save message
8170: for later delivery
1.191 harris41 8171:
1.394 bowersj2 8172: =item * B<error:>: an error a occured, a description of the error follows the :
1.191 harris41 8173:
1.394 bowersj2 8174: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 8175: that was requested
1.191 harris41 8176:
1.243 albertel 8177: =back
1.191 harris41 8178:
1.243 albertel 8179: =head1 PUBLIC SUBROUTINES
1.191 harris41 8180:
1.243 albertel 8181: =head2 Session Environment Functions
1.191 harris41 8182:
1.243 albertel 8183: =over 4
1.191 harris41 8184:
1.394 bowersj2 8185: =item *
8186: X<appenv()>
8187: B<appenv(%hash)>: the value of %hash is written to
8188: the user envirnoment file, and will be restored for each access this
1.620 albertel 8189: user makes during this session, also modifies the %env for the current
1.394 bowersj2 8190: process
1.191 harris41 8191:
8192: =item *
1.394 bowersj2 8193: X<delenv()>
8194: B<delenv($regexp)>: removes all items from the session
8195: environment file that matches the regular expression in $regexp. The
1.620 albertel 8196: values are also delted from the current processes %env.
1.191 harris41 8197:
1.795 albertel 8198: =item * get_env_multiple($name)
8199:
8200: gets $name from the %env hash, it seemlessly handles the cases where multiple
8201: values may be defined and end up as an array ref.
8202:
8203: returns an array of values
8204:
1.243 albertel 8205: =back
8206:
8207: =head2 User Information
1.191 harris41 8208:
1.243 albertel 8209: =over 4
1.191 harris41 8210:
8211: =item *
1.394 bowersj2 8212: X<queryauthenticate()>
8213: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 8214: authentication scheme
8215:
8216: =item *
1.394 bowersj2 8217: X<authenticate()>
8218: B<authenticate($uname,$upass,$udom)>: try to
8219: authenticate user from domain's lib servers (first use the current
8220: one). C<$upass> should be the users password.
1.191 harris41 8221:
8222: =item *
1.394 bowersj2 8223: X<homeserver()>
8224: B<homeserver($uname,$udom)>: find the server which has
8225: the user's directory and files (there must be only one), this caches
8226: the answer, and also caches if there is a borken connection.
1.191 harris41 8227:
8228: =item *
1.394 bowersj2 8229: X<idget()>
8230: B<idget($udom,@ids)>: find the usernames behind a list of IDs
8231: (IDs are a unique resource in a domain, there must be only 1 ID per
8232: username, and only 1 username per ID in a specific domain) (returns
8233: hash: id=>name,id=>name)
1.191 harris41 8234:
8235: =item *
1.394 bowersj2 8236: X<idrget()>
8237: B<idrget($udom,@unames)>: find the IDs behind a list of
8238: usernames (returns hash: name=>id,name=>id)
1.191 harris41 8239:
8240: =item *
1.394 bowersj2 8241: X<idput()>
8242: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 8243:
8244: =item *
1.394 bowersj2 8245: X<rolesinit()>
8246: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 8247:
8248: =item *
1.551 albertel 8249: X<getsection()>
8250: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 8251: course $cname, return section name/number or '' for "not in course"
8252: and '-1' for "no section"
8253:
8254: =item *
1.394 bowersj2 8255: X<userenvironment()>
8256: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 8257: passed in @what from the requested user's environment, returns a hash
8258:
1.858 raeburn 8259: =item *
8260: X<userlog_query()>
1.859 albertel 8261: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
8262: activity.log file. %filters defines filters applied when parsing the
8263: log file. These can be start or end timestamps, or the type of action
8264: - log to look for Login or Logout events, check for Checkin or
8265: Checkout, role for role selection. The response is in the form
8266: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
8267: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 8268:
1.243 albertel 8269: =back
8270:
8271: =head2 User Roles
8272:
8273: =over 4
8274:
8275: =item *
8276:
1.810 raeburn 8277: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 8278: F: full access
8279: U,I,K: authentication modes (cxx only)
8280: '': forbidden
8281: 1: user needs to choose course
8282: 2: browse allowed
1.766 albertel 8283: A: passphrase authentication needed
1.243 albertel 8284:
8285: =item *
8286:
8287: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
8288: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
8289: and course level
8290:
8291: =item *
8292:
8293: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
8294: explanation of a user role term
8295:
1.832 raeburn 8296: =item *
8297:
1.858 raeburn 8298: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
8299: All arguments are optional. Returns a hash of a roles, either for
8300: co-author/assistant author roles for a user's Construction Space
8301: (default), or if $context is 'user', roles for the user himself,
8302: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
8303: and value is set to colon-separated start and end times for the role.
8304: If no username and domain are specified, will default to current
8305: user/domain. Types, roles, and roledoms are references to arrays,
8306: of role statuses (active, future or previous), roles
8307: (e.g., cc,in, st etc.) and domains of the roles which can be used
8308: to restrict the list of roles reported. If no array ref is
8309: provided for types, will default to return only active roles.
1.834 albertel 8310:
1.243 albertel 8311: =back
8312:
8313: =head2 User Modification
8314:
8315: =over 4
8316:
8317: =item *
8318:
8319: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
8320: user for the level given by URL. Optional start and end dates (leave empty
8321: string or zero for "no date")
1.191 harris41 8322:
8323: =item *
8324:
1.243 albertel 8325: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
8326: change a users, password, possible return values are: ok,
8327: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
8328: refused
1.191 harris41 8329:
8330: =item *
8331:
1.243 albertel 8332: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 8333:
8334: =item *
8335:
1.243 albertel 8336: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
8337: modify user
1.191 harris41 8338:
8339: =item *
8340:
1.286 matthew 8341: modifystudent
8342:
8343: modify a students enrollment and identification information.
8344: The course id is resolved based on the current users environment.
8345: This means the envoking user must be a course coordinator or otherwise
8346: associated with a course.
8347:
1.297 matthew 8348: This call is essentially a wrapper for lonnet::modifyuser and
8349: lonnet::modify_student_enrollment
1.286 matthew 8350:
8351: Inputs:
8352:
8353: =over 4
8354:
8355: =item B<$udom> Students loncapa domain
8356:
8357: =item B<$uname> Students loncapa login name
8358:
8359: =item B<$uid> Students id/student number
8360:
8361: =item B<$umode> Students authentication mode
8362:
8363: =item B<$upass> Students password
8364:
8365: =item B<$first> Students first name
8366:
8367: =item B<$middle> Students middle name
8368:
8369: =item B<$last> Students last name
8370:
8371: =item B<$gene> Students generation
8372:
8373: =item B<$usec> Students section in course
8374:
8375: =item B<$end> Unix time of the roles expiration
8376:
8377: =item B<$start> Unix time of the roles start date
8378:
8379: =item B<$forceid> If defined, allow $uid to be changed
8380:
8381: =item B<$desiredhome> server to use as home server for student
8382:
8383: =back
1.297 matthew 8384:
8385: =item *
8386:
8387: modify_student_enrollment
8388:
8389: Change a students enrollment status in a class. The environment variable
8390: 'role.request.course' must be defined for this function to proceed.
8391:
8392: Inputs:
8393:
8394: =over 4
8395:
8396: =item $udom, students domain
8397:
8398: =item $uname, students name
8399:
8400: =item $uid, students user id
8401:
8402: =item $first, students first name
8403:
8404: =item $middle
8405:
8406: =item $last
8407:
8408: =item $gene
8409:
8410: =item $usec
8411:
8412: =item $end
8413:
8414: =item $start
8415:
8416: =back
8417:
1.191 harris41 8418:
8419: =item *
8420:
1.243 albertel 8421: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
8422: custom role; give a custom role to a user for the level given by URL. Specify
8423: name and domain of role author, and role name
1.191 harris41 8424:
8425: =item *
8426:
1.243 albertel 8427: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 8428:
8429: =item *
8430:
1.243 albertel 8431: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
8432:
8433: =back
8434:
8435: =head2 Course Infomation
8436:
8437: =over 4
1.191 harris41 8438:
8439: =item *
8440:
1.631 albertel 8441: coursedescription($courseid) : returns a hash of information about the
8442: specified course id, including all environment settings for the
8443: course, the description of the course will be in the hash under the
8444: key 'description'
1.191 harris41 8445:
8446: =item *
8447:
1.624 albertel 8448: resdata($name,$domain,$type,@which) : request for current parameter
8449: setting for a specific $type, where $type is either 'course' or 'user',
8450: @what should be a list of parameters to ask about. This routine caches
8451: answers for 5 minutes.
1.243 albertel 8452:
8453: =back
8454:
8455: =head2 Course Modification
8456:
8457: =over 4
1.191 harris41 8458:
8459: =item *
8460:
1.243 albertel 8461: writecoursepref($courseid,%prefs) : write preferences (environment
8462: database) for a course
1.191 harris41 8463:
8464: =item *
8465:
1.243 albertel 8466: createcourse($udom,$description,$url) : make/modify course
8467:
8468: =back
8469:
8470: =head2 Resource Subroutines
8471:
8472: =over 4
1.191 harris41 8473:
8474: =item *
8475:
1.243 albertel 8476: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 8477:
8478: =item *
8479:
1.243 albertel 8480: repcopy($filename) : subscribes to the requested file, and attempts to
8481: replicate from the owning library server, Might return
1.607 raeburn 8482: 'unavailable', 'not_found', 'forbidden', 'ok', or
8483: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 8484: resource. Expects the local filesystem pathname
8485: (/home/httpd/html/res/....)
8486:
8487: =back
8488:
8489: =head2 Resource Information
8490:
8491: =over 4
1.191 harris41 8492:
8493: =item *
8494:
1.243 albertel 8495: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
8496: a vairety of different possible values, $varname should be a request
8497: string, and the other parameters can be used to specify who and what
8498: one is asking about.
8499:
8500: Possible values for $varname are environment.lastname (or other item
8501: from the envirnment hash), user.name (or someother aspect about the
8502: user), resource.0.maxtries (or some other part and parameter of a
8503: resource)
1.204 albertel 8504:
8505: =item *
8506:
1.243 albertel 8507: directcondval($number) : get current value of a condition; reads from a state
8508: string
1.204 albertel 8509:
8510: =item *
8511:
1.243 albertel 8512: condval($condidx) : value of condition index based on state
1.204 albertel 8513:
8514: =item *
8515:
1.243 albertel 8516: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
8517: resource's metadata, $what should be either a specific key, or either
8518: 'keys' (to get a list of possible keys) or 'packages' to get a list of
8519: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
8520:
8521: this function automatically caches all requests
1.191 harris41 8522:
8523: =item *
8524:
1.243 albertel 8525: metadata_query($query,$custom,$customshow) : make a metadata query against the
8526: network of library servers; returns file handle of where SQL and regex results
8527: will be stored for query
1.191 harris41 8528:
8529: =item *
8530:
1.243 albertel 8531: symbread($filename) : return symbolic list entry (filename argument optional);
8532: returns the data handle
1.191 harris41 8533:
8534: =item *
8535:
1.243 albertel 8536: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 8537: a possible symb for the URL in $thisfn, and if is an encryypted
8538: resource that the user accessed using /enc/ returns a 1 on success, 0
8539: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 8540: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 8541:
1.191 harris41 8542:
8543: =item *
8544:
1.243 albertel 8545: symbclean($symb) : removes versions numbers from a symb, returns the
8546: cleaned symb
1.191 harris41 8547:
8548: =item *
8549:
1.243 albertel 8550: is_on_map($uri) : checks if the $uri is somewhere on the current
8551: course map, user must be in a course for it to work.
1.191 harris41 8552:
8553: =item *
8554:
1.243 albertel 8555: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 8556:
8557: =item *
8558:
1.243 albertel 8559: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
8560: a random seed, all arguments are optional, if they aren't sent it uses the
8561: environment to derive them. Note: if symb isn't sent and it can't get one
8562: from &symbread it will use the current time as its return value
1.191 harris41 8563:
8564: =item *
8565:
1.243 albertel 8566: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
8567: unfakeable, receipt
1.191 harris41 8568:
8569: =item *
8570:
1.620 albertel 8571: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 8572:
8573: =item *
8574:
1.243 albertel 8575: countacc($url) : count the number of accesses to a given URL
1.191 harris41 8576:
8577: =item *
8578:
1.243 albertel 8579: 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 8580:
8581: =item *
8582:
1.243 albertel 8583: 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 8584:
8585: =item *
8586:
1.243 albertel 8587: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 8588:
8589: =item *
8590:
1.243 albertel 8591: devalidate($symb) : devalidate temporary spreadsheet calculations,
8592: forcing spreadsheet to reevaluate the resource scores next time.
8593:
8594: =back
8595:
8596: =head2 Storing/Retreiving Data
8597:
8598: =over 4
1.191 harris41 8599:
8600: =item *
8601:
1.243 albertel 8602: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
8603: for this url; hashref needs to be given and should be a \%hashname; the
8604: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 8605: be derived from the env
1.191 harris41 8606:
8607: =item *
8608:
1.243 albertel 8609: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
8610: uses critical subroutine
1.191 harris41 8611:
8612: =item *
8613:
1.243 albertel 8614: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
8615: all args are optional
1.191 harris41 8616:
8617: =item *
8618:
1.717 albertel 8619: dumpstore($namespace,$udom,$uname,$regexp,$range) :
8620: dumps the complete (or key matching regexp) namespace into a hash
8621: ($udom, $uname, $regexp, $range are optional) for a namespace that is
8622: normally &store()ed into
8623:
8624: $range should be either an integer '100' (give me the first 100
8625: matching records)
8626: or be two integers sperated by a - with no spaces
8627: '30-50' (give me the 30th through the 50th matching
8628: records)
8629:
8630:
8631: =item *
8632:
8633: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
8634: replaces a &store() version of data with a replacement set of data
8635: for a particular resource in a namespace passed in the $storehash hash
8636: reference
8637:
8638: =item *
8639:
1.243 albertel 8640: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
8641: works very similar to store/cstore, but all data is stored in a
8642: temporary location and can be reset using tmpreset, $storehash should
8643: be a hash reference, returns nothing on success
1.191 harris41 8644:
8645: =item *
8646:
1.243 albertel 8647: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
8648: similar to restore, but all data is stored in a temporary location and
8649: can be reset using tmpreset. Returns a hash of values on success,
8650: error string otherwise.
1.191 harris41 8651:
8652: =item *
8653:
1.243 albertel 8654: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
8655: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 8656:
8657: =item *
8658:
1.243 albertel 8659: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8660: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 8661:
8662: =item *
8663:
1.243 albertel 8664: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
8665: namesp ($udom and $uname are optional)
1.191 harris41 8666:
8667: =item *
8668:
1.702 albertel 8669: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 8670: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 8671: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 8672:
1.702 albertel 8673: $range should be either an integer '100' (give me the first 100
8674: matching records)
8675: or be two integers sperated by a - with no spaces
8676: '30-50' (give me the 30th through the 50th matching
8677: records)
1.449 matthew 8678: =item *
8679:
8680: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
8681: $store can be a scalar, an array reference, or if the amount to be
8682: incremented is > 1, a hash reference.
8683:
8684: ($udom and $uname are optional)
1.191 harris41 8685:
8686: =item *
8687:
1.243 albertel 8688: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
8689: ($udom and $uname are optional)
1.191 harris41 8690:
8691: =item *
8692:
1.243 albertel 8693: cput($namespace,$storehash,$udom,$uname) : critical put
8694: ($udom and $uname are optional)
1.191 harris41 8695:
8696: =item *
8697:
1.748 albertel 8698: newput($namespace,$storehash,$udom,$uname) :
8699:
8700: Attempts to store the items in the $storehash, but only if they don't
8701: currently exist, if this succeeds you can be certain that you have
8702: successfully created a new key value pair in the $namespace db.
8703:
8704:
8705: Args:
8706: $namespace: name of database to store values to
8707: $storehash: hashref to store to the db
8708: $udom: (optional) domain of user containing the db
8709: $uname: (optional) name of user caontaining the db
8710:
8711: Returns:
8712: 'ok' -> succeeded in storing all keys of $storehash
8713: 'key_exists: <key>' -> failed to anything out of $storehash, as at
8714: least <key> already existed in the db (other
8715: requested keys may also already exist)
8716: 'error: <msg>' -> unable to tie the DB or other erorr occured
8717: 'con_lost' -> unable to contact request server
8718: 'refused' -> action was not allowed by remote machine
8719:
8720:
8721: =item *
8722:
1.243 albertel 8723: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8724: reference filled in from namesp (encrypts the return communication)
8725: ($udom and $uname are optional)
1.191 harris41 8726:
8727: =item *
8728:
1.243 albertel 8729: log($udom,$name,$home,$message) : write to permanent log for user; use
8730: critical subroutine
8731:
1.806 raeburn 8732: =item *
8733:
1.860 raeburn 8734: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
8735: array reference filled in from namespace found in domain level on either
8736: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 8737:
8738: =item *
8739:
1.860 raeburn 8740: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
8741: domain level either on specified domain server ($uhome) or primary domain
8742: server ($udom and $uhome are optional)
1.806 raeburn 8743:
1.243 albertel 8744: =back
8745:
8746: =head2 Network Status Functions
8747:
8748: =over 4
1.191 harris41 8749:
8750: =item *
8751:
8752: dirlist($uri) : return directory list based on URI
8753:
8754: =item *
8755:
1.243 albertel 8756: spareserver() : find server with least workload from spare.tab
8757:
8758: =back
8759:
8760: =head2 Apache Request
8761:
8762: =over 4
1.191 harris41 8763:
8764: =item *
8765:
1.243 albertel 8766: ssi($url,%hash) : server side include, does a complete request cycle on url to
8767: localhost, posts hash
8768:
8769: =back
8770:
8771: =head2 Data to String to Data
8772:
8773: =over 4
1.191 harris41 8774:
8775: =item *
8776:
1.243 albertel 8777: hash2str(%hash) : convert a hash into a string complete with escaping and '='
8778: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 8779:
8780: =item *
8781:
1.243 albertel 8782: hashref2str($hashref) : convert a hashref into a string complete with
8783: escaping and '=' and '&' separators, supports elements that are
8784: arrayrefs and hashrefs
1.191 harris41 8785:
8786: =item *
8787:
1.243 albertel 8788: arrayref2str($arrayref) : convert an arrayref into a string complete
8789: with escaping and '&' separators, supports elements that are arrayrefs
8790: and hashrefs
1.191 harris41 8791:
8792: =item *
8793:
1.243 albertel 8794: str2hash($string) : convert string to hash using unescaping and
8795: splitting on '=' and '&', supports elements that are arrayrefs and
8796: hashrefs
1.191 harris41 8797:
8798: =item *
8799:
1.243 albertel 8800: str2array($string) : convert string to hash using unescaping and
8801: splitting on '&', supports elements that are arrayrefs and hashrefs
8802:
8803: =back
8804:
8805: =head2 Logging Routines
8806:
8807: =over 4
8808:
8809: These routines allow one to make log messages in the lonnet.log and
8810: lonnet.perm logfiles.
1.191 harris41 8811:
8812: =item *
8813:
1.243 albertel 8814: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 8815:
8816: =item *
8817:
1.243 albertel 8818: logthis() : append message to the normal lonnet.log file, it gets
8819: preiodically rolled over and deleted.
1.191 harris41 8820:
8821: =item *
8822:
1.243 albertel 8823: logperm() : append a permanent message to lonnet.perm.log, this log
8824: file never gets deleted by any automated portion of the system, only
8825: messages of critical importance should go in here.
8826:
8827: =back
8828:
8829: =head2 General File Helper Routines
8830:
8831: =over 4
1.191 harris41 8832:
8833: =item *
8834:
1.481 raeburn 8835: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
8836: (a) files in /uploaded
8837: (i) If a local copy of the file exists -
8838: compares modification date of local copy with last-modified date for
8839: definitive version stored on home server for course. If local copy is
8840: stale, requests a new version from the home server and stores it.
8841: If the original has been removed from the home server, then local copy
8842: is unlinked.
8843: (ii) If local copy does not exist -
8844: requests the file from the home server and stores it.
8845:
8846: If $caller is 'uploadrep':
8847: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
8848: for request for files originally uploaded via DOCS.
8849: - returns 'ok' if fresh local copy now available, -1 otherwise.
8850:
8851: Otherwise:
8852: This indicates a call from the content generation phase of the request.
8853: - returns the entire contents of the file or -1.
8854:
8855: (b) files in /res
8856: - returns the entire contents of a file or -1;
8857: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 8858:
1.712 albertel 8859:
8860: =item *
8861:
8862: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
8863: reference
8864:
8865: returns either a stat() list of data about the file or an empty list
8866: if the file doesn't exist or couldn't find out about it (connection
8867: problems or user unknown)
8868:
1.191 harris41 8869: =item *
8870:
1.243 albertel 8871: filelocation($dir,$file) : returns file system location of a file
8872: based on URI; meant to be "fairly clean" absolute reference, $dir is a
8873: directory that relative $file lookups are to looked in ($dir of /a/dir
8874: and a file of ../bob will become /a/bob)
1.191 harris41 8875:
8876: =item *
8877:
8878: hreflocation($dir,$file) : returns file system location or a URL; same as
8879: filelocation except for hrefs
8880:
8881: =item *
8882:
8883: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
8884:
1.243 albertel 8885: =back
8886:
1.608 albertel 8887: =head2 Usererfile file routines (/uploaded*)
8888:
8889: =over 4
8890:
8891: =item *
8892:
8893: userfileupload(): main rotine for putting a file in a user or course's
8894: filespace, arguments are,
8895:
1.620 albertel 8896: formname - required - this is the name of the element in $env where the
1.608 albertel 8897: filename, and the contents of the file to create/modifed exist
1.620 albertel 8898: the filename is in $env{'form.'.$formname.'.filename'} and the
8899: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 8900: coursedoc - if true, store the file in the course of the active role
8901: of the current user
8902: subdir - required - subdirectory to put the file in under ../userfiles/
8903: if undefined, it will be placed in "unknown"
8904:
8905: (This routine calls clean_filename() to remove any dangerous
8906: characters from the filename, and then calls finuserfileupload() to
8907: complete the transaction)
8908:
8909: returns either the url of the uploaded file (/uploaded/....) if successful
8910: and /adm/notfound.html if unsuccessful
8911:
8912: =item *
8913:
8914: clean_filename(): routine for cleaing a filename up for storage in
8915: userfile space, argument is:
8916:
8917: filename - proposed filename
8918:
8919: returns: the new clean filename
8920:
8921: =item *
8922:
8923: finishuserfileupload(): routine that creaes and sends the file to
8924: userspace, probably shouldn't be called directly
8925:
8926: docuname: username or courseid of destination for the file
8927: docudom: domain of user/course of destination for the file
8928: formname: same as for userfileupload()
8929: fname: filename (inculding subdirectories) for the file
8930:
8931: returns either the url of the uploaded file (/uploaded/....) if successful
8932: and /adm/notfound.html if unsuccessful
8933:
8934: =item *
8935:
8936: renameuserfile(): renames an existing userfile to a new name
8937:
8938: Args:
8939: docuname: username or courseid of destination for the file
8940: docudom: domain of user/course of destination for the file
8941: old: current file name (including any subdirs under userfiles)
8942: new: desired file name (including any subdirs under userfiles)
8943:
8944: =item *
8945:
8946: mkdiruserfile(): creates a directory is a userfiles dir
8947:
8948: Args:
8949: docuname: username or courseid of destination for the file
8950: docudom: domain of user/course of destination for the file
8951: dir: dir to create (including any subdirs under userfiles)
8952:
8953: =item *
8954:
8955: removeuserfile(): removes a file that exists in userfiles
8956:
8957: Args:
8958: docuname: username or courseid of destination for the file
8959: docudom: domain of user/course of destination for the file
8960: fname: filname to delete (including any subdirs under userfiles)
8961:
8962: =item *
8963:
8964: removeuploadedurl(): convience function for removeuserfile()
8965:
8966: Args:
8967: url: a full /uploaded/... url to delete
8968:
1.747 albertel 8969: =item *
8970:
8971: get_portfile_permissions():
8972: Args:
8973: domain: domain of user or course contain the portfolio files
8974: user: name of user or num of course contain the portfolio files
8975: Returns:
8976: hashref of a dump of the proper file_permissions.db
8977:
8978:
8979: =item *
8980:
8981: get_access_controls():
8982:
8983: Args:
8984: current_permissions: the hash ref returned from get_portfile_permissions()
8985: group: (optional) the group you want the files associated with
8986: file: (optional) the file you want access info on
8987:
8988: Returns:
1.749 raeburn 8989: a hash (keys are file names) of hashes containing
8990: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
8991: values are XML containing access control settings (see below)
1.747 albertel 8992:
8993: Internal notes:
8994:
1.749 raeburn 8995: access controls are stored in file_permissions.db as key=value pairs.
8996: key -> path to file/file_name\0uniqueID:scope_end_start
8997: where scope -> public,guest,course,group,domains or users.
8998: end -> UNIX time for end of access (0 -> no end date)
8999: start -> UNIX time for start of access
9000:
9001: value -> XML description of access control
9002: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
9003: <start></start>
9004: <end></end>
9005:
9006: <password></password> for scope type = guest
9007:
9008: <domain></domain> for scope type = course or group
9009: <number></number>
9010: <roles id="">
9011: <role></role>
9012: <access></access>
9013: <section></section>
9014: <group></group>
9015: </roles>
9016:
9017: <dom></dom> for scope type = domains
9018:
9019: <users> for scope type = users
9020: <user>
9021: <uname></uname>
9022: <udom></udom>
9023: </user>
9024: </users>
9025: </scope>
9026:
9027: Access data is also aggregated for each file in an additional key=value pair:
9028: key -> path to file/file_name\0accesscontrol
9029: value -> reference to hash
9030: hash contains key = value pairs
9031: where key = uniqueID:scope_end_start
9032: value = UNIX time record was last updated
9033:
9034: Used to improve speed of look-ups of access controls for each file.
9035:
9036: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
9037:
9038: modify_access_controls():
9039:
9040: Modifies access controls for a portfolio file
9041: Args
9042: 1. file name
9043: 2. reference to hash of required changes,
9044: 3. domain
9045: 4. username
9046: where domain,username are the domain of the portfolio owner
9047: (either a user or a course)
9048:
9049: Returns:
9050: 1. result of additions or updates ('ok' or 'error', with error message).
9051: 2. result of deletions ('ok' or 'error', with error message).
9052: 3. reference to hash of any new or updated access controls.
9053: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
9054: key = integer (inbound ID)
9055: value = uniqueID
1.747 albertel 9056:
1.608 albertel 9057: =back
9058:
1.243 albertel 9059: =head2 HTTP Helper Routines
9060:
9061: =over 4
9062:
1.191 harris41 9063: =item *
9064:
9065: escape() : unpack non-word characters into CGI-compatible hex codes
9066:
9067: =item *
9068:
9069: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
9070:
1.243 albertel 9071: =back
9072:
9073: =head1 PRIVATE SUBROUTINES
9074:
9075: =head2 Underlying communication routines (Shouldn't call)
9076:
9077: =over 4
9078:
9079: =item *
9080:
9081: subreply() : tries to pass a message to lonc, returns con_lost if incapable
9082:
9083: =item *
9084:
9085: reply() : uses subreply to send a message to remote machine, logs all failures
9086:
9087: =item *
9088:
9089: critical() : passes a critical message to another server; if cannot
9090: get through then place message in connection buffer directory and
9091: returns con_delayed, if incapable of saving message, returns
9092: con_failed
9093:
9094: =item *
9095:
9096: reconlonc() : tries to reconnect lonc client processes.
9097:
9098: =back
9099:
9100: =head2 Resource Access Logging
9101:
9102: =over 4
9103:
9104: =item *
9105:
9106: flushcourselogs() : flush (save) buffer logs and access logs
9107:
9108: =item *
9109:
9110: courselog($what) : save message for course in hash
9111:
9112: =item *
9113:
9114: courseacclog($what) : save message for course using &courselog(). Perform
9115: special processing for specific resource types (problems, exams, quizzes, etc).
9116:
1.191 harris41 9117: =item *
9118:
9119: goodbye() : flush course logs and log shutting down; it is called in srm.conf
9120: as a PerlChildExitHandler
1.243 albertel 9121:
9122: =back
9123:
9124: =head2 Other
9125:
9126: =over 4
9127:
9128: =item *
9129:
9130: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 9131:
9132: =back
9133:
9134: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>