Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.867
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.867 ! raeburn 4: # $Id: lonnet.pm,v 1.866 2007/04/05 22:04:49 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:
674: # ------------------------------------- Find the usernames behind a list of IDs
675:
676: sub idget {
677: my ($udom,@ids)=@_;
678: my %returnhash=();
679:
1.841 albertel 680: my %servers = &get_servers($udom,'library');
681: foreach my $tryserver (keys(%servers)) {
682: my $idlist=join('&',@ids);
683: $idlist=~tr/A-Z/a-z/;
684: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
685: my @answer=();
686: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
687: @answer=split(/\&/,$reply);
688: } ;
689: my $i;
690: for ($i=0;$i<=$#ids;$i++) {
691: if ($answer[$i]) {
692: $returnhash{$ids[$i]}=$answer[$i];
693: }
694: }
695: }
1.70 www 696: return %returnhash;
697: }
698:
699: # ------------------------------------- Find the IDs behind a list of usernames
700:
701: sub idrget {
702: my ($udom,@unames)=@_;
703: my %returnhash=();
1.800 albertel 704: foreach my $uname (@unames) {
705: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 706: }
1.70 www 707: return %returnhash;
708: }
709:
710: # ------------------------------- Store away a list of names and associated IDs
711:
712: sub idput {
713: my ($udom,%ids)=@_;
714: my %servers=();
1.800 albertel 715: foreach my $uname (keys(%ids)) {
716: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
717: my $uhom=&homeserver($uname,$udom);
1.70 www 718: if ($uhom ne 'no_host') {
1.800 albertel 719: my $id=&escape($ids{$uname});
1.70 www 720: $id=~tr/A-Z/a-z/;
1.800 albertel 721: my $esc_unam=&escape($uname);
1.70 www 722: if ($servers{$uhom}) {
1.800 albertel 723: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 724: } else {
1.800 albertel 725: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 726: }
727: }
1.191 harris41 728: }
1.800 albertel 729: foreach my $server (keys(%servers)) {
730: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 731: }
1.344 www 732: }
733:
1.806 raeburn 734: # ------------------------------------------- get items from domain db files
735:
736: sub get_dom {
1.860 raeburn 737: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 738: my $items='';
739: foreach my $item (@$storearr) {
740: $items.=&escape($item).'&';
741: }
742: $items=~s/\&$//;
1.860 raeburn 743: if (!$udom) {
744: $udom=$env{'user.domain'};
745: if (defined(&domain($udom,'primary'))) {
746: $uhome=&domain($udom,'primary');
747: } else {
748: $uhome eq '';
749: }
750: } else {
751: if (!$uhome) {
752: if (defined(&domain($udom,'primary'))) {
753: $uhome=&domain($udom,'primary');
754: }
755: }
756: }
757: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 758: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 759: my %returnhash;
760: if ($rep =~ /^error: 2 /) {
761: return %returnhash;
762: }
1.806 raeburn 763: my @pairs=split(/\&/,$rep);
764: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
765: return @pairs;
766: }
767: my %returnhash=();
768: my $i=0;
769: foreach my $item (@$storearr) {
770: $returnhash{$item}=&thaw_unescape($pairs[$i]);
771: $i++;
772: }
773: return %returnhash;
774: } else {
1.860 raeburn 775: &logthis("get_dom failed - no homeserver and/or domain");
1.806 raeburn 776: }
777: }
778:
779: # -------------------------------------------- put items in domain db files
780:
781: sub put_dom {
1.860 raeburn 782: my ($namespace,$storehash,$udom,$uhome)=@_;
783: if (!$udom) {
784: $udom=$env{'user.domain'};
785: if (defined(&domain($udom,'primary'))) {
786: $uhome=&domain($udom,'primary');
787: } else {
788: $uhome eq '';
789: }
790: } else {
791: if (!$uhome) {
792: if (defined(&domain($udom,'primary'))) {
793: $uhome=&domain($udom,'primary');
794: }
795: }
796: }
797: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 798: my $items='';
799: foreach my $item (keys(%$storehash)) {
800: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
801: }
802: $items=~s/\&$//;
803: return &reply("putdom:$udom:$namespace:$items",$uhome);
804: } else {
1.860 raeburn 805: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 806: }
807: }
808:
1.837 raeburn 809: sub retrieve_inst_usertypes {
810: my ($udom) = @_;
811: my (%returnhash,@order);
1.846 albertel 812: if (defined(&domain($udom,'primary'))) {
813: my $uhome=&domain($udom,'primary');
1.837 raeburn 814: my $rep=&reply("inst_usertypes:$udom",$uhome);
815: my ($hashitems,$orderitems) = split(/:/,$rep);
816: my @pairs=split(/\&/,$hashitems);
817: foreach my $item (@pairs) {
818: my ($key,$value)=split(/=/,$item,2);
819: $key = &unescape($key);
820: next if ($key =~ /^error: 2 /);
821: $returnhash{$key}=&thaw_unescape($value);
822: }
823: my @esc_order = split(/\&/,$orderitems);
824: foreach my $item (@esc_order) {
825: push(@order,&unescape($item));
826: }
827: } else {
828: &logthis("get_dom failed - no primary domain server for $udom");
829: }
830: return (\%returnhash,\@order);
831: }
832:
1.344 www 833: # --------------------------------------------------- Assign a key to a student
834:
835: sub assign_access_key {
1.364 www 836: #
837: # a valid key looks like uname:udom#comments
838: # comments are being appended
839: #
1.498 www 840: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
841: $kdom=
1.620 albertel 842: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 843: $knum=
1.620 albertel 844: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 845: $cdom=
1.620 albertel 846: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 847: $cnum=
1.620 albertel 848: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
849: $udom=$env{'user.name'} unless (defined($udom));
850: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 851: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 852: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 853: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 854: # assigned to this person
855: # - this should not happen,
1.345 www 856: # unless something went wrong
857: # the first time around
858: # ready to assign
1.364 www 859: $logentry=$1.'; '.$logentry;
1.496 www 860: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 861: $kdom,$knum) eq 'ok') {
1.345 www 862: # key now belongs to user
1.346 www 863: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 864: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
865: &appenv('environment.'.$envkey => $ckey);
866: return 'ok';
867: } else {
868: return
869: 'error: Count not permanently assign key, will need to be re-entered later.';
870: }
871: } else {
872: return 'error: Could not assign key, try again later.';
873: }
1.364 www 874: } elsif (!$existing{$ckey}) {
1.345 www 875: # the key does not exist
876: return 'error: The key does not exist';
877: } else {
878: # the key is somebody else's
879: return 'error: The key is already in use';
880: }
1.344 www 881: }
882:
1.364 www 883: # ------------------------------------------ put an additional comment on a key
884:
885: sub comment_access_key {
886: #
887: # a valid key looks like uname:udom#comments
888: # comments are being appended
889: #
890: my ($ckey,$cdom,$cnum,$logentry)=@_;
891: $cdom=
1.620 albertel 892: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 893: $cnum=
1.620 albertel 894: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 895: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
896: if ($existing{$ckey}) {
897: $existing{$ckey}.='; '.$logentry;
898: # ready to assign
1.367 www 899: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 900: $cdom,$cnum) eq 'ok') {
901: return 'ok';
902: } else {
903: return 'error: Count not store comment.';
904: }
905: } else {
906: # the key does not exist
907: return 'error: The key does not exist';
908: }
909: }
910:
1.344 www 911: # ------------------------------------------------------ Generate a set of keys
912:
913: sub generate_access_keys {
1.364 www 914: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 915: $cdom=
1.620 albertel 916: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 917: $cnum=
1.620 albertel 918: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 919: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 920: unless (($cdom) && ($cnum)) { return 0; }
921: if ($number>10000) { return 0; }
922: sleep(2); # make sure don't get same seed twice
923: srand(time()^($$+($$<<15))); # from "Programming Perl"
924: my $total=0;
925: for (my $i=1;$i<=$number;$i++) {
926: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
927: sprintf("%lx",int(100000*rand)).'-'.
928: sprintf("%lx",int(100000*rand));
929: $newkey=~s/1/g/g; # folks mix up 1 and l
930: $newkey=~s/0/h/g; # and also 0 and O
931: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
932: if ($existing{$newkey}) {
933: $i--;
934: } else {
1.364 www 935: if (&put('accesskeys',
936: { $newkey => '# generated '.localtime().
1.620 albertel 937: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 938: '; '.$logentry },
939: $cdom,$cnum) eq 'ok') {
1.344 www 940: $total++;
941: }
942: }
943: }
1.620 albertel 944: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 945: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
946: return $total;
947: }
948:
949: # ------------------------------------------------------- Validate an accesskey
950:
951: sub validate_access_key {
952: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
953: $cdom=
1.620 albertel 954: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 955: $cnum=
1.620 albertel 956: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
957: $udom=$env{'user.domain'} unless (defined($udom));
958: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 959: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 960: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 961: }
962:
963: # ------------------------------------- Find the section of student in a course
1.652 albertel 964: sub devalidate_getsection_cache {
965: my ($udom,$unam,$courseid)=@_;
966: my $hashid="$udom:$unam:$courseid";
967: &devalidate_cache_new('getsection',$hashid);
968: }
1.298 matthew 969:
1.815 albertel 970: sub courseid_to_courseurl {
971: my ($courseid) = @_;
972: #already url style courseid
973: return $courseid if ($courseid =~ m{^/});
974:
975: if (exists($env{'course.'.$courseid.'.num'})) {
976: my $cnum = $env{'course.'.$courseid.'.num'};
977: my $cdom = $env{'course.'.$courseid.'.domain'};
978: return "/$cdom/$cnum";
979: }
980:
981: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
982: if (exists($courseinfo{'num'})) {
983: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
984: }
985:
986: return undef;
987: }
988:
1.298 matthew 989: sub getsection {
990: my ($udom,$unam,$courseid)=@_;
1.599 albertel 991: my $cachetime=1800;
1.551 albertel 992:
993: my $hashid="$udom:$unam:$courseid";
1.599 albertel 994: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 995: if (defined($cached)) { return $result; }
996:
1.298 matthew 997: my %Pending;
998: my %Expired;
999: #
1000: # Each role can either have not started yet (pending), be active,
1001: # or have expired.
1002: #
1003: # If there is an active role, we are done.
1004: #
1005: # If there is more than one role which has not started yet,
1006: # choose the one which will start sooner
1007: # If there is one role which has not started yet, return it.
1008: #
1009: # If there is more than one expired role, choose the one which ended last.
1010: # If there is a role which has expired, return it.
1011: #
1.815 albertel 1012: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1013: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1014: foreach my $key (keys(%roleshash)) {
1.479 albertel 1015: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1016: my $section=$1;
1017: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1018: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1019: my $now=time;
1.548 albertel 1020: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1021: $Expired{$end}=$section;
1022: next;
1023: }
1.548 albertel 1024: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1025: $Pending{$start}=$section;
1026: next;
1027: }
1.599 albertel 1028: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1029: }
1030: #
1031: # Presumedly there will be few matching roles from the above
1032: # loop and the sorting time will be negligible.
1033: if (scalar(keys(%Pending))) {
1034: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1035: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1036: }
1037: if (scalar(keys(%Expired))) {
1038: my @sorted = sort {$a <=> $b} keys(%Expired);
1039: my $time = pop(@sorted);
1.599 albertel 1040: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1041: }
1.599 albertel 1042: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1043: }
1.70 www 1044:
1.599 albertel 1045: sub save_cache {
1046: &purge_remembered();
1.722 albertel 1047: #&Apache::loncommon::validate_page();
1.620 albertel 1048: undef(%env);
1.780 albertel 1049: undef($env_loaded);
1.599 albertel 1050: }
1.452 albertel 1051:
1.599 albertel 1052: my $to_remember=-1;
1053: my %remembered;
1054: my %accessed;
1055: my $kicks=0;
1056: my $hits=0;
1.849 albertel 1057: sub make_key {
1058: my ($name,$id) = @_;
1059: if (length($id) > 200) { $id=length($id).':'.&Digest::MD5::md5_hex($id); }
1060: return &escape($name.':'.$id);
1061: }
1062:
1.599 albertel 1063: sub devalidate_cache_new {
1064: my ($name,$id,$debug) = @_;
1065: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1066: $id=&make_key($name,$id);
1.599 albertel 1067: $memcache->delete($id);
1068: delete($remembered{$id});
1069: delete($accessed{$id});
1070: }
1071:
1072: sub is_cached_new {
1073: my ($name,$id,$debug) = @_;
1.849 albertel 1074: $id=&make_key($name,$id);
1.599 albertel 1075: if (exists($remembered{$id})) {
1076: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1077: $accessed{$id}=[&gettimeofday()];
1078: $hits++;
1079: return ($remembered{$id},1);
1080: }
1081: my $value = $memcache->get($id);
1082: if (!(defined($value))) {
1083: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1084: return (undef,undef);
1.416 albertel 1085: }
1.599 albertel 1086: if ($value eq '__undef__') {
1087: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1088: $value=undef;
1089: }
1090: &make_room($id,$value,$debug);
1091: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1092: return ($value,1);
1093: }
1094:
1095: sub do_cache_new {
1096: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1097: $id=&make_key($name,$id);
1.599 albertel 1098: my $setvalue=$value;
1099: if (!defined($setvalue)) {
1100: $setvalue='__undef__';
1101: }
1.623 albertel 1102: if (!defined($time) ) {
1103: $time=600;
1104: }
1.599 albertel 1105: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600 albertel 1106: $memcache->set($id,$setvalue,$time);
1107: # need to make a copy of $value
1108: #&make_room($id,$value,$debug);
1.599 albertel 1109: return $value;
1110: }
1111:
1112: sub make_room {
1113: my ($id,$value,$debug)=@_;
1114: $remembered{$id}=$value;
1115: if ($to_remember<0) { return; }
1116: $accessed{$id}=[&gettimeofday()];
1117: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1118: my $to_kick;
1119: my $max_time=0;
1120: foreach my $other (keys(%accessed)) {
1121: if (&tv_interval($accessed{$other}) > $max_time) {
1122: $to_kick=$other;
1123: $max_time=&tv_interval($accessed{$other});
1124: }
1125: }
1126: delete($remembered{$to_kick});
1127: delete($accessed{$to_kick});
1128: $kicks++;
1129: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1130: return;
1131: }
1132:
1.599 albertel 1133: sub purge_remembered {
1.604 albertel 1134: #&logthis("Tossing ".scalar(keys(%remembered)));
1135: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1136: undef(%remembered);
1137: undef(%accessed);
1.428 albertel 1138: }
1.70 www 1139: # ------------------------------------- Read an entry from a user's environment
1140:
1141: sub userenvironment {
1142: my ($udom,$unam,@what)=@_;
1143: my %returnhash=();
1144: my @answer=split(/\&/,
1145: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
1146: &homeserver($unam,$udom)));
1147: my $i;
1148: for ($i=0;$i<=$#what;$i++) {
1149: $returnhash{$what[$i]}=&unescape($answer[$i]);
1150: }
1151: return %returnhash;
1.1 albertel 1152: }
1153:
1.617 albertel 1154: # ---------------------------------------------------------- Get a studentphoto
1155: sub studentphoto {
1156: my ($udom,$unam,$ext) = @_;
1157: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1158: if (defined($env{'request.course.id'})) {
1.708 raeburn 1159: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1160: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1161: return(&retrievestudentphoto($udom,$unam,$ext));
1162: } else {
1163: my ($result,$perm_reqd)=
1.707 albertel 1164: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1165: if ($result eq 'ok') {
1166: if (!($perm_reqd eq 'yes')) {
1167: return(&retrievestudentphoto($udom,$unam,$ext));
1168: }
1169: }
1170: }
1171: }
1172: } else {
1173: my ($result,$perm_reqd) =
1.707 albertel 1174: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1175: if ($result eq 'ok') {
1176: if (!($perm_reqd eq 'yes')) {
1177: return(&retrievestudentphoto($udom,$unam,$ext));
1178: }
1179: }
1180: }
1181: return '/adm/lonKaputt/lonlogo_broken.gif';
1182: }
1183:
1184: sub retrievestudentphoto {
1185: my ($udom,$unam,$ext,$type) = @_;
1186: my $home=&Apache::lonnet::homeserver($unam,$udom);
1187: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1188: if ($ret eq 'ok') {
1189: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1190: if ($type eq 'thumbnail') {
1191: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1192: }
1193: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1194: return $tokenurl;
1195: } else {
1196: if ($type eq 'thumbnail') {
1197: return '/adm/lonKaputt/genericstudent_tn.gif';
1198: } else {
1199: return '/adm/lonKaputt/lonlogo_broken.gif';
1200: }
1.617 albertel 1201: }
1202: }
1203:
1.263 www 1204: # -------------------------------------------------------------------- New chat
1205:
1206: sub chatsend {
1.724 raeburn 1207: my ($newentry,$anon,$group)=@_;
1.620 albertel 1208: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1209: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1210: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1211: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1212: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1213: &escape($newentry)).':'.$group,$chome);
1.292 www 1214: }
1215:
1216: # ------------------------------------------ Find current version of a resource
1217:
1218: sub getversion {
1219: my $fname=&clutter(shift);
1220: unless ($fname=~/^\/res\//) { return -1; }
1221: return ¤tversion(&filelocation('',$fname));
1222: }
1223:
1224: sub currentversion {
1225: my $fname=shift;
1.599 albertel 1226: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1227: if (defined($cached)) { return $result; }
1.292 www 1228: my $author=$fname;
1229: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1230: my ($udom,$uname)=split(/\//,$author);
1231: my $home=homeserver($uname,$udom);
1232: if ($home eq 'no_host') {
1233: return -1;
1234: }
1235: my $answer=reply("currentversion:$fname",$home);
1236: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1237: return -1;
1238: }
1.599 albertel 1239: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1240: }
1241:
1.1 albertel 1242: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1243:
1.1 albertel 1244: sub subscribe {
1245: my $fname=shift;
1.761 raeburn 1246: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1247: $fname=~s/[\n\r]//g;
1.1 albertel 1248: my $author=$fname;
1249: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1250: my ($udom,$uname)=split(/\//,$author);
1251: my $home=homeserver($uname,$udom);
1.335 albertel 1252: if ($home eq 'no_host') {
1253: return 'not_found';
1.1 albertel 1254: }
1255: my $answer=reply("sub:$fname",$home);
1.64 www 1256: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1257: $answer.=' by '.$home;
1258: }
1.1 albertel 1259: return $answer;
1260: }
1261:
1.8 www 1262: # -------------------------------------------------------------- Replicate file
1263:
1264: sub repcopy {
1265: my $filename=shift;
1.23 www 1266: $filename=~s/\/+/\//g;
1.607 raeburn 1267: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1268: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1269: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1270: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1271: return &repcopy_userfile($filename);
1272: }
1.532 albertel 1273: $filename=~s/[\n\r]//g;
1.8 www 1274: my $transname="$filename.in.transfer";
1.828 www 1275: # FIXME: this should flock
1.607 raeburn 1276: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1277: my $remoteurl=subscribe($filename);
1.64 www 1278: if ($remoteurl =~ /^con_lost by/) {
1279: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1280: return 'unavailable';
1.8 www 1281: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1282: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1283: return 'not_found';
1.64 www 1284: } elsif ($remoteurl =~ /^rejected by/) {
1285: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1286: return 'forbidden';
1.20 www 1287: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1288: return 'ok';
1.8 www 1289: } else {
1.290 www 1290: my $author=$filename;
1291: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1292: my ($udom,$uname)=split(/\//,$author);
1293: my $home=homeserver($uname,$udom);
1294: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1295: my @parts=split(/\//,$filename);
1296: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1297: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1298: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1299: return 'bad_request';
1.8 www 1300: }
1301: my $count;
1302: for ($count=5;$count<$#parts;$count++) {
1303: $path.="/$parts[$count]";
1304: if ((-e $path)!=1) {
1305: mkdir($path,0777);
1306: }
1307: }
1308: my $ua=new LWP::UserAgent;
1309: my $request=new HTTP::Request('GET',"$remoteurl");
1310: my $response=$ua->request($request,$transname);
1311: if ($response->is_error()) {
1312: unlink($transname);
1313: my $message=$response->status_line;
1.672 albertel 1314: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1315: ." LWP get: $message: $filename</font>");
1.607 raeburn 1316: return 'unavailable';
1.8 www 1317: } else {
1.16 www 1318: if ($remoteurl!~/\.meta$/) {
1319: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1320: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1321: if ($mresponse->is_error()) {
1322: unlink($filename.'.meta');
1323: &logthis(
1.672 albertel 1324: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1325: }
1326: }
1.8 www 1327: rename($transname,$filename);
1.607 raeburn 1328: return 'ok';
1.8 www 1329: }
1.290 www 1330: }
1.8 www 1331: }
1.330 www 1332: }
1333:
1334: # ------------------------------------------------ Get server side include body
1335: sub ssi_body {
1.381 albertel 1336: my ($filelink,%form)=@_;
1.606 matthew 1337: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1338: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1339: }
1.330 www 1340: my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381 albertel 1341: &ssi($filelink,%form));
1.778 albertel 1342: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1343: $output=~s/^.*?\<body[^\>]*\>//si;
1344: $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330 www 1345: return $output;
1.8 www 1346: }
1347:
1.15 www 1348: # --------------------------------------------------------- Server Side Include
1349:
1.782 albertel 1350: sub absolute_url {
1351: my ($host_name) = @_;
1352: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1353: if ($host_name eq '') {
1354: $host_name = $ENV{'SERVER_NAME'};
1355: }
1356: return $protocol.$host_name;
1357: }
1358:
1.15 www 1359: sub ssi {
1360:
1.23 www 1361: my ($fn,%form)=@_;
1.15 www 1362:
1363: my $ua=new LWP::UserAgent;
1.23 www 1364:
1365: my $request;
1.711 albertel 1366:
1367: $form{'no_update_last_known'}=1;
1368:
1.23 www 1369: if (%form) {
1.782 albertel 1370: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201 albertel 1371: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23 www 1372: } else {
1.782 albertel 1373: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1374: }
1375:
1.15 www 1376: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1377: my $response=$ua->request($request);
1378:
1.324 www 1379: return $response->content;
1380: }
1381:
1382: sub externalssi {
1383: my ($url)=@_;
1384: my $ua=new LWP::UserAgent;
1385: my $request=new HTTP::Request('GET',$url);
1386: my $response=$ua->request($request);
1.15 www 1387: return $response->content;
1388: }
1.254 www 1389:
1.492 albertel 1390: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1391:
1392: sub allowuploaded {
1393: my ($srcurl,$url)=@_;
1394: $url=&clutter(&declutter($url));
1395: my $dir=$url;
1396: $dir=~s/\/[^\/]+$//;
1397: my %httpref=();
1398: my $httpurl=&hreflocation('',$url);
1399: $httpref{'httpref.'.$httpurl}=$srcurl;
1400: &Apache::lonnet::appenv(%httpref);
1.254 www 1401: }
1.477 raeburn 1402:
1.478 albertel 1403: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1404: # input: action, courseID, current domain, intended
1.637 raeburn 1405: # path to file, source of file, instruction to parse file for objects,
1406: # ref to hash for embedded objects,
1407: # ref to hash for codebase of java objects.
1408: #
1.485 raeburn 1409: # output: url to file (if action was uploaddoc),
1410: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 1411: #
1.478 albertel 1412: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1413: # course.
1.477 raeburn 1414: #
1.478 albertel 1415: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1416: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1417: # course's home server.
1.477 raeburn 1418: #
1.478 albertel 1419: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1420: # be copied from $source (current location) to
1421: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1422: # and will then be copied to
1423: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1424: # course's home server.
1.485 raeburn 1425: #
1.481 raeburn 1426: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 1427: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 1428: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1429: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1430: # in course's home server.
1.637 raeburn 1431: #
1.477 raeburn 1432:
1433: sub process_coursefile {
1.638 albertel 1434: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 1435: my $fetchresult;
1.638 albertel 1436: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 1437: if ($action eq 'propagate') {
1.638 albertel 1438: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1439: $home);
1.481 raeburn 1440: } else {
1.477 raeburn 1441: my $fpath = '';
1442: my $fname = $file;
1.478 albertel 1443: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 1444: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 1445: my $filepath = &build_filepath($fpath);
1.481 raeburn 1446: if ($action eq 'copy') {
1447: if ($source eq '') {
1448: $fetchresult = 'no source file';
1449: return $fetchresult;
1450: } else {
1451: my $destination = $filepath.'/'.$fname;
1452: rename($source,$destination);
1453: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1454: $home);
1.481 raeburn 1455: }
1456: } elsif ($action eq 'uploaddoc') {
1457: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 1458: print $fh $env{'form.'.$source};
1.481 raeburn 1459: close($fh);
1.637 raeburn 1460: if ($parser eq 'parse') {
1461: my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
1462: unless ($parse_result eq 'ok') {
1463: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1464: }
1465: }
1.477 raeburn 1466: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1467: $home);
1.481 raeburn 1468: if ($fetchresult eq 'ok') {
1469: return '/uploaded/'.$fpath.'/'.$fname;
1470: } else {
1471: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1472: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 1473: return '/adm/notfound.html';
1474: }
1.477 raeburn 1475: }
1476: }
1.485 raeburn 1477: unless ( $fetchresult eq 'ok') {
1.477 raeburn 1478: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1479: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 1480: }
1481: return $fetchresult;
1482: }
1483:
1.637 raeburn 1484: sub build_filepath {
1485: my ($fpath) = @_;
1486: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1487: unless ($fpath eq '') {
1488: my @parts=split('/',$fpath);
1489: foreach my $part (@parts) {
1490: $filepath.= '/'.$part;
1491: if ((-e $filepath)!=1) {
1492: mkdir($filepath,0777);
1493: }
1494: }
1495: }
1496: return $filepath;
1497: }
1498:
1499: sub store_edited_file {
1.638 albertel 1500: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 1501: my $file = $primary_url;
1502: $file =~ s#^/uploaded/$docudom/$docuname/##;
1503: my $fpath = '';
1504: my $fname = $file;
1505: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1506: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1507: my $filepath = &build_filepath($fpath);
1508: open(my $fh,'>'.$filepath.'/'.$fname);
1509: print $fh $content;
1510: close($fh);
1.638 albertel 1511: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 1512: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1513: $home);
1.637 raeburn 1514: if ($$fetchresult eq 'ok') {
1515: return '/uploaded/'.$fpath.'/'.$fname;
1516: } else {
1.638 albertel 1517: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1518: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 1519: return '/adm/notfound.html';
1520: }
1521: }
1522:
1.531 albertel 1523: sub clean_filename {
1.831 albertel 1524: my ($fname,$args)=@_;
1.315 www 1525: # Replace Windows backslashes by forward slashes
1.257 www 1526: $fname=~s/\\/\//g;
1.831 albertel 1527: if (!$args->{'keep_path'}) {
1528: # Get rid of everything but the actual filename
1529: $fname=~s/^.*\/([^\/]+)$/$1/;
1530: }
1.315 www 1531: # Replace spaces by underscores
1532: $fname=~s/\s+/\_/g;
1533: # Replace all other weird characters by nothing
1.831 albertel 1534: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 1535: # Replace all .\d. sequences with _\d. so they no longer look like version
1536: # numbers
1537: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 1538: return $fname;
1539: }
1540:
1.608 albertel 1541: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 1542: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 1543: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 1544: # $coursedoc - if true up to the current course
1545: # if false
1546: # $subdir - directory in userfile to store the file into
1.858 raeburn 1547: # $parser - instruction to parse file for objects ($parser = parse)
1548: # $allfiles - reference to hash for embedded objects
1549: # $codebase - reference to hash for codebase of java objects
1550: # $desuname - username for permanent storage of uploaded file
1551: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 1552: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
1553: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858 raeburn 1554: #
1.686 albertel 1555: # output: url of file in userspace, or error: <message>
1556: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 1557:
1558:
1.531 albertel 1559: sub userfileupload {
1.860 raeburn 1560: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1561: $destudom,$thumbwidth,$thumbheight)=@_;
1.531 albertel 1562: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 1563: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 1564: $fname=&clean_filename($fname);
1.315 www 1565: # See if there is anything left
1.257 www 1566: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 1567: chop($env{'form.'.$formname});
1.523 raeburn 1568: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
1569: my $now = time;
1570: my $filepath = 'tmp/helprequests/'.$now;
1571: my @parts=split(/\//,$filepath);
1572: my $fullpath = $perlvar{'lonDaemons'};
1573: for (my $i=0;$i<@parts;$i++) {
1574: $fullpath .= '/'.$parts[$i];
1575: if ((-e $fullpath)!=1) {
1576: mkdir($fullpath,0777);
1577: }
1578: }
1579: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 1580: print $fh $env{'form.'.$formname};
1.523 raeburn 1581: close($fh);
1.741 raeburn 1582: return $fullpath.'/'.$fname;
1583: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
1584: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
1585: '_'.$env{'user.domain'}.'/pending';
1586: my @parts=split(/\//,$filepath);
1587: my $fullpath = $perlvar{'lonDaemons'};
1588: for (my $i=0;$i<@parts;$i++) {
1589: $fullpath .= '/'.$parts[$i];
1590: if ((-e $fullpath)!=1) {
1591: mkdir($fullpath,0777);
1592: }
1593: }
1594: open(my $fh,'>'.$fullpath.'/'.$fname);
1595: print $fh $env{'form.'.$formname};
1596: close($fh);
1597: return $fullpath.'/'.$fname;
1.523 raeburn 1598: }
1.719 banghart 1599:
1.258 www 1600: # Create the directory if not present
1.493 albertel 1601: $fname="$subdir/$fname";
1.259 www 1602: if ($coursedoc) {
1.638 albertel 1603: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1604: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 1605: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 1606: return &finishuserfileupload($docuname,$docudom,
1607: $formname,$fname,$parser,$allfiles,
1.860 raeburn 1608: $codebase,$thumbwidth,$thumbheight);
1.481 raeburn 1609: } else {
1.620 albertel 1610: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 1611: return &process_coursefile('uploaddoc',$docuname,$docudom,
1612: $fname,$formname,$parser,
1613: $allfiles,$codebase);
1.481 raeburn 1614: }
1.719 banghart 1615: } elsif (defined($destuname)) {
1616: my $docuname=$destuname;
1617: my $docudom=$destudom;
1.860 raeburn 1618: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
1619: $parser,$allfiles,$codebase,
1620: $thumbwidth,$thumbheight);
1.719 banghart 1621:
1.259 www 1622: } else {
1.638 albertel 1623: my $docuname=$env{'user.name'};
1624: my $docudom=$env{'user.domain'};
1.714 raeburn 1625: if (exists($env{'form.group'})) {
1626: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1627: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1628: }
1.860 raeburn 1629: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
1630: $parser,$allfiles,$codebase,
1631: $thumbwidth,$thumbheight);
1.259 www 1632: }
1.271 www 1633: }
1634:
1635: sub finishuserfileupload {
1.860 raeburn 1636: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1637: $thumbwidth,$thumbheight) = @_;
1.477 raeburn 1638: my $path=$docudom.'/'.$docuname.'/';
1.258 www 1639: my $filepath=$perlvar{'lonDocRoot'};
1.860 raeburn 1640: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 1641: $file=$fname;
1642: if ($fname=~m|/|) {
1643: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
1644: $path.=$fnamepath.'/';
1645: }
1.259 www 1646: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 1647: my $count;
1648: for ($count=4;$count<=$#parts;$count++) {
1649: $filepath.="/$parts[$count]";
1650: if ((-e $filepath)!=1) {
1651: mkdir($filepath,0777);
1652: }
1653: }
1654: # Save the file
1655: {
1.701 albertel 1656: if (!open(FH,'>'.$filepath.'/'.$file)) {
1657: &logthis('Failed to create '.$filepath.'/'.$file);
1658: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
1659: return '/adm/notfound.html';
1660: }
1661: if (!print FH ($env{'form.'.$formname})) {
1662: &logthis('Failed to write to '.$filepath.'/'.$file);
1663: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
1664: return '/adm/notfound.html';
1665: }
1.570 albertel 1666: close(FH);
1.258 www 1667: }
1.637 raeburn 1668: if ($parser eq 'parse') {
1.638 albertel 1669: my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
1670: $codebase);
1.637 raeburn 1671: unless ($parse_result eq 'ok') {
1.638 albertel 1672: &logthis('Failed to parse '.$filepath.$file.
1673: ' for embedded media: '.$parse_result);
1.637 raeburn 1674: }
1675: }
1.860 raeburn 1676: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
1677: my $input = $filepath.'/'.$file;
1678: my $output = $filepath.'/'.'tn-'.$file;
1679: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1680: system("convert -sample $thumbsize $input $output");
1681: if (-e $filepath.'/'.'tn-'.$file) {
1682: $fetchthumb = 1;
1683: }
1684: }
1.858 raeburn 1685:
1.259 www 1686: # Notify homeserver to grep it
1687: #
1.638 albertel 1688: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 1689: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 1690: if ($fetchresult eq 'ok') {
1.860 raeburn 1691: if ($fetchthumb) {
1692: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
1693: if ($thumbresult ne 'ok') {
1694: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
1695: $docuhome.': '.$thumbresult);
1696: }
1697: }
1.259 www 1698: #
1.258 www 1699: # Return the URL to it
1.494 albertel 1700: return '/uploaded/'.$path.$file;
1.263 www 1701: } else {
1.494 albertel 1702: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
1703: ': '.$fetchresult);
1.263 www 1704: return '/adm/notfound.html';
1.858 raeburn 1705: }
1.493 albertel 1706: }
1707:
1.637 raeburn 1708: sub extract_embedded_items {
1.648 raeburn 1709: my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637 raeburn 1710: my @state = ();
1711: my %javafiles = (
1712: codebase => '',
1713: code => '',
1714: archive => ''
1715: );
1716: my %mediafiles = (
1717: src => '',
1718: movie => '',
1719: );
1.648 raeburn 1720: my $p;
1721: if ($content) {
1722: $p = HTML::LCParser->new($content);
1723: } else {
1724: $p = HTML::LCParser->new($filepath.'/'.$file);
1725: }
1.641 albertel 1726: while (my $t=$p->get_token()) {
1.640 albertel 1727: if ($t->[0] eq 'S') {
1728: my ($tagname, $attr) = ($t->[1],$t->[2]);
1729: push (@state, $tagname);
1.648 raeburn 1730: if (lc($tagname) eq 'allow') {
1731: &add_filetype($allfiles,$attr->{'src'},'src');
1732: }
1.640 albertel 1733: if (lc($tagname) eq 'img') {
1734: &add_filetype($allfiles,$attr->{'src'},'src');
1735: }
1.645 raeburn 1736: if (lc($tagname) eq 'script') {
1737: if ($attr->{'archive'} =~ /\.jar$/i) {
1738: &add_filetype($allfiles,$attr->{'archive'},'archive');
1739: } else {
1740: &add_filetype($allfiles,$attr->{'src'},'src');
1741: }
1742: }
1743: if (lc($tagname) eq 'link') {
1744: if (lc($attr->{'rel'}) eq 'stylesheet') {
1745: &add_filetype($allfiles,$attr->{'href'},'href');
1746: }
1747: }
1.640 albertel 1748: if (lc($tagname) eq 'object' ||
1749: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
1750: foreach my $item (keys(%javafiles)) {
1751: $javafiles{$item} = '';
1752: }
1753: }
1754: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
1755: my $name = lc($attr->{'name'});
1756: foreach my $item (keys(%javafiles)) {
1757: if ($name eq $item) {
1758: $javafiles{$item} = $attr->{'value'};
1759: last;
1760: }
1761: }
1762: foreach my $item (keys(%mediafiles)) {
1763: if ($name eq $item) {
1764: &add_filetype($allfiles, $attr->{'value'}, 'value');
1765: last;
1766: }
1767: }
1768: }
1769: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
1770: foreach my $item (keys(%javafiles)) {
1771: if ($attr->{$item}) {
1772: $javafiles{$item} = $attr->{$item};
1773: last;
1774: }
1775: }
1776: foreach my $item (keys(%mediafiles)) {
1777: if ($attr->{$item}) {
1778: &add_filetype($allfiles,$attr->{$item},$item);
1779: last;
1780: }
1781: }
1782: }
1783: } elsif ($t->[0] eq 'E') {
1784: my ($tagname) = ($t->[1]);
1785: if ($javafiles{'codebase'} ne '') {
1786: $javafiles{'codebase'} .= '/';
1787: }
1788: if (lc($tagname) eq 'applet' ||
1789: lc($tagname) eq 'object' ||
1790: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
1791: ) {
1792: foreach my $item (keys(%javafiles)) {
1793: if ($item ne 'codebase' && $javafiles{$item} ne '') {
1794: my $file=$javafiles{'codebase'}.$javafiles{$item};
1795: &add_filetype($allfiles,$file,$item);
1796: }
1797: }
1798: }
1799: pop @state;
1800: }
1801: }
1.637 raeburn 1802: return 'ok';
1803: }
1804:
1.639 albertel 1805: sub add_filetype {
1806: my ($allfiles,$file,$type)=@_;
1807: if (exists($allfiles->{$file})) {
1808: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
1809: push(@{$allfiles->{$file}}, &escape($type));
1810: }
1811: } else {
1812: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 1813: }
1814: }
1815:
1.493 albertel 1816: sub removeuploadedurl {
1817: my ($url)=@_;
1818: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 1819: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 1820: }
1821:
1822: sub removeuserfile {
1823: my ($docuname,$docudom,$fname)=@_;
1824: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 1825: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1826: if ($result eq 'ok') {
1827: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
1828: my $metafile = $fname.'.meta';
1829: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 1830: my $url = "/uploaded/$docudom/$docuname/$fname";
1831: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 1832: my $sqlresult =
1.823 albertel 1833: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 1834: 'portfolio_metadata',$group,
1835: 'delete');
1.798 raeburn 1836: }
1837: }
1838: return $result;
1.257 www 1839: }
1.15 www 1840:
1.530 albertel 1841: sub mkdiruserfile {
1842: my ($docuname,$docudom,$dir)=@_;
1843: my $home=&homeserver($docuname,$docudom);
1844: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
1845: }
1846:
1.531 albertel 1847: sub renameuserfile {
1848: my ($docuname,$docudom,$old,$new)=@_;
1849: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 1850: my $result = &reply("renameuserfile:$docudom:$docuname:".
1851: &escape("$old").':'.&escape("$new"),$home);
1852: if ($result eq 'ok') {
1853: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
1854: my $oldmeta = $old.'.meta';
1855: my $newmeta = $new.'.meta';
1856: my $metaresult =
1857: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 1858: my $url = "/uploaded/$docudom/$docuname/$old";
1859: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 1860: my $sqlresult =
1.823 albertel 1861: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 1862: 'portfolio_metadata',$group,
1863: 'delete');
1.798 raeburn 1864: }
1865: }
1866: return $result;
1.531 albertel 1867: }
1868:
1.14 www 1869: # ------------------------------------------------------------------------- Log
1870:
1871: sub log {
1872: my ($dom,$nam,$hom,$what)=@_;
1.47 www 1873: return critical("log:$dom:$nam:$what",$hom);
1.157 www 1874: }
1875:
1876: # ------------------------------------------------------------------ Course Log
1.352 www 1877: #
1878: # This routine flushes several buffers of non-mission-critical nature
1879: #
1.157 www 1880:
1881: sub flushcourselogs {
1.352 www 1882: &logthis('Flushing log buffers');
1883: #
1884: # course logs
1885: # This is a log of all transactions in a course, which can be used
1886: # for data mining purposes
1887: #
1888: # It also collects the courseid database, which lists last transaction
1889: # times and course titles for all courseids
1890: #
1891: my %courseidbuffer=();
1.800 albertel 1892: foreach my $crsid (keys %courselogs) {
1.352 www 1893: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 1894: &escape($courselogs{$crsid}),
1895: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 1896: delete $courselogs{$crsid};
1897: } else {
1898: &logthis('Failed to flush log buffer for '.$crsid);
1899: if (length($courselogs{$crsid})>40000) {
1.672 albertel 1900: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 1901: " exceeded maximum size, deleting.</font>");
1902: delete $courselogs{$crsid};
1903: }
1.352 www 1904: }
1905: if ($courseidbuffer{$coursehombuf{$crsid}}) {
1906: $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516 raeburn 1907: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741 raeburn 1908: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352 www 1909: } else {
1910: $courseidbuffer{$coursehombuf{$crsid}}=
1.516 raeburn 1911: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741 raeburn 1912: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571 raeburn 1913: }
1.191 harris41 1914: }
1.352 www 1915: #
1916: # Write course id database (reverse lookup) to homeserver of courses
1917: # Is used in pickcourse
1918: #
1.840 albertel 1919: foreach my $crs_home (keys(%courseidbuffer)) {
1.844 albertel 1920: &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840 albertel 1921: $crs_home);
1.352 www 1922: }
1923: #
1924: # File accesses
1925: # Writes to the dynamic metadata of resources to get hit counts, etc.
1926: #
1.449 matthew 1927: foreach my $entry (keys(%accesshash)) {
1.458 matthew 1928: if ($entry =~ /___count$/) {
1929: my ($dom,$name);
1.807 albertel 1930: ($dom,$name,undef)=
1.811 albertel 1931: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 1932: if (! defined($dom) || $dom eq '' ||
1933: ! defined($name) || $name eq '') {
1.620 albertel 1934: my $cid = $env{'request.course.id'};
1935: $dom = $env{'request.'.$cid.'.domain'};
1936: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 1937: }
1.450 matthew 1938: my $value = $accesshash{$entry};
1939: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
1940: my %temphash=($url => $value);
1.449 matthew 1941: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
1942: if ($result eq 'ok') {
1943: delete $accesshash{$entry};
1944: } elsif ($result eq 'unknown_cmd') {
1945: # Target server has old code running on it.
1.450 matthew 1946: my %temphash=($entry => $value);
1.449 matthew 1947: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1948: delete $accesshash{$entry};
1949: }
1950: }
1951: } else {
1.811 albertel 1952: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 1953: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 1954: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1955: delete $accesshash{$entry};
1956: }
1.185 www 1957: }
1.191 harris41 1958: }
1.352 www 1959: #
1960: # Roles
1961: # Reverse lookup of user roles for course faculty/staff and co-authorship
1962: #
1.800 albertel 1963: foreach my $entry (keys(%userrolehash)) {
1.351 www 1964: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 1965: split(/\:/,$entry);
1966: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 1967: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 1968: $rudom,$runame) eq 'ok') {
1969: delete $userrolehash{$entry};
1970: }
1971: }
1.662 raeburn 1972: #
1973: # Reverse lookup of domain roles (dc, ad, li, sc, au)
1974: #
1975: my %domrolebuffer = ();
1976: foreach my $entry (keys %domainrolehash) {
1977: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
1978: if ($domrolebuffer{$rudom}) {
1979: $domrolebuffer{$rudom}.='&'.&escape($entry).
1980: '='.&escape($domainrolehash{$entry});
1981: } else {
1982: $domrolebuffer{$rudom}.=&escape($entry).
1983: '='.&escape($domainrolehash{$entry});
1984: }
1985: delete $domainrolehash{$entry};
1986: }
1987: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 1988: my %servers = &get_servers($dom,'library');
1989: foreach my $tryserver (keys(%servers)) {
1990: unless (&reply('domroleput:'.$dom.':'.
1991: $domrolebuffer{$dom},$tryserver) eq 'ok') {
1992: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
1993: }
1.662 raeburn 1994: }
1995: }
1.186 www 1996: $dumpcount++;
1.157 www 1997: }
1998:
1999: sub courselog {
2000: my $what=shift;
1.158 www 2001: $what=time.':'.$what;
1.620 albertel 2002: unless ($env{'request.course.id'}) { return ''; }
2003: $coursedombuf{$env{'request.course.id'}}=
2004: $env{'course.'.$env{'request.course.id'}.'.domain'};
2005: $coursenumbuf{$env{'request.course.id'}}=
2006: $env{'course.'.$env{'request.course.id'}.'.num'};
2007: $coursehombuf{$env{'request.course.id'}}=
2008: $env{'course.'.$env{'request.course.id'}.'.home'};
2009: $coursedescrbuf{$env{'request.course.id'}}=
2010: $env{'course.'.$env{'request.course.id'}.'.description'};
2011: $courseinstcodebuf{$env{'request.course.id'}}=
2012: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2013: $courseownerbuf{$env{'request.course.id'}}=
2014: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2015: $coursetypebuf{$env{'request.course.id'}}=
2016: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2017: if (defined $courselogs{$env{'request.course.id'}}) {
2018: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2019: } else {
1.620 albertel 2020: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2021: }
1.620 albertel 2022: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2023: &flushcourselogs();
2024: }
1.158 www 2025: }
2026:
2027: sub courseacclog {
2028: my $fnsymb=shift;
1.620 albertel 2029: unless ($env{'request.course.id'}) { return ''; }
2030: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2031: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2032: $what.=':POST';
1.583 matthew 2033: # FIXME: Probably ought to escape things....
1.800 albertel 2034: foreach my $key (keys(%env)) {
2035: if ($key=~/^form\.(.*)/) {
2036: $what.=':'.$1.'='.$env{$key};
1.158 www 2037: }
1.191 harris41 2038: }
1.583 matthew 2039: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2040: # FIXME: We should not be depending on a form parameter that someone
2041: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2042: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2043: $what.= ':POST';
2044: # FIXME: Probably ought to escape things....
2045: foreach my $element ('courseexp','crsfulltext','crsrelated',
2046: 'crsdiscuss') {
1.620 albertel 2047: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2048: }
2049: }
1.158 www 2050: }
2051: &courselog($what);
1.149 www 2052: }
2053:
1.185 www 2054: sub countacc {
2055: my $url=&declutter(shift);
1.458 matthew 2056: return if (! defined($url) || $url eq '');
1.620 albertel 2057: unless ($env{'request.course.id'}) { return ''; }
2058: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2059: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2060: $accesshash{$key}++;
1.185 www 2061: }
1.349 www 2062:
1.361 www 2063: sub linklog {
2064: my ($from,$to)=@_;
2065: $from=&declutter($from);
2066: $to=&declutter($to);
2067: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2068: $accesshash{$to.'___'.$from.'___goto'}=1;
2069: }
2070:
1.349 www 2071: sub userrolelog {
2072: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2073: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2074: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2075: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2076: ($trole=~/^ta/)) {
1.350 www 2077: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2078: $userrolehash
2079: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2080: =$tend.':'.$tstart;
1.662 raeburn 2081: }
2082: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2083: ($trole=~/^li/) || ($trole=~/^li/) ||
2084: ($trole=~/^au/) || ($trole=~/^dg/) ||
2085: ($trole=~/^sc/)) {
2086: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2087: $domainrolehash
2088: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2089: = $tend.':'.$tstart;
2090: }
1.351 www 2091: }
2092:
2093: sub get_course_adv_roles {
2094: my $cid=shift;
1.620 albertel 2095: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2096: my %coursehash=&coursedescription($cid);
1.470 www 2097: my %nothide=();
1.800 albertel 2098: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2099: $nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470 www 2100: }
1.351 www 2101: my %returnhash=();
2102: my %dumphash=
2103: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2104: my $now=time;
1.800 albertel 2105: foreach my $entry (keys %dumphash) {
2106: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2107: if (($tstart) && ($tstart<0)) { next; }
2108: if (($tend) && ($tend<$now)) { next; }
2109: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2110: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2111: if ($username eq '' || $domain eq '') { next; }
1.470 www 2112: if ((&privileged($username,$domain)) &&
2113: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2114: if ($role eq 'cr') { next; }
1.351 www 2115: my $key=&plaintext($role);
2116: if ($section) { $key.=' (Sec/Grp '.$section.')'; }
2117: if ($returnhash{$key}) {
2118: $returnhash{$key}.=','.$username.':'.$domain;
2119: } else {
2120: $returnhash{$key}=$username.':'.$domain;
2121: }
1.400 www 2122: }
2123: return %returnhash;
2124: }
2125:
2126: sub get_my_roles {
1.858 raeburn 2127: my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620 albertel 2128: unless (defined($uname)) { $uname=$env{'user.name'}; }
2129: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858 raeburn 2130: my %dumphash;
2131: if ($context eq 'userroles') {
2132: %dumphash = &dump('roles',$udom,$uname);
2133: } else {
2134: %dumphash=
1.400 www 2135: &dump('nohist_userroles',$udom,$uname);
1.858 raeburn 2136: }
1.400 www 2137: my %returnhash=();
2138: my $now=time;
1.800 albertel 2139: foreach my $entry (keys(%dumphash)) {
1.867 ! raeburn 2140: my ($role,$tend,$tstart);
! 2141: if ($context eq 'userroles') {
! 2142: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
! 2143: } else {
! 2144: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
! 2145: }
1.400 www 2146: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2147: my $status = 'active';
2148: if (($tend) && ($tend<$now)) {
2149: $status = 'previous';
2150: }
2151: if (($tstart) && ($now<$tstart)) {
2152: $status = 'future';
2153: }
2154: if (ref($types) eq 'ARRAY') {
2155: if (!grep(/^\Q$status\E$/,@{$types})) {
2156: next;
2157: }
2158: } else {
2159: if ($status ne 'active') {
2160: next;
2161: }
2162: }
1.867 ! raeburn 2163: my ($rolecode,$username,$domain,$section,$area);
! 2164: if ($context eq 'userroles') {
! 2165: ($area,$rolecode) = split(/_/,$entry);
! 2166: (undef,$domain,$username,$section) = split(/\//,$area);
! 2167: } else {
! 2168: ($role,$username,$domain,$section) = split(/\:/,$entry);
! 2169: }
1.832 raeburn 2170: if (ref($roledoms) eq 'ARRAY') {
2171: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2172: next;
2173: }
2174: }
2175: if (ref($roles) eq 'ARRAY') {
2176: if (!grep(/^\Q$role\E$/,@{$roles})) {
2177: next;
2178: }
1.867 ! raeburn 2179: }
1.400 www 2180: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832 raeburn 2181: }
1.373 www 2182: return %returnhash;
1.399 www 2183: }
2184:
2185: # ----------------------------------------------------- Frontpage Announcements
2186: #
2187: #
2188:
2189: sub postannounce {
2190: my ($server,$text)=@_;
1.844 albertel 2191: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2192: unless ($text=~/\w/) { $text=''; }
2193: return &reply('setannounce:'.&escape($text),$server);
2194: }
2195:
2196: sub getannounce {
1.448 albertel 2197:
2198: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 2199: my $announcement='';
1.800 albertel 2200: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 2201: close($fh);
1.399 www 2202: if ($announcement=~/\w/) {
2203: return
2204: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 2205: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 2206: } else {
2207: return '';
2208: }
2209: } else {
2210: return '';
2211: }
1.351 www 2212: }
1.353 www 2213:
2214: # ---------------------------------------------------------- Course ID routines
2215: # Deal with domain's nohist_courseid.db files
2216: #
2217:
2218: sub courseidput {
2219: my ($domain,$what,$coursehome)=@_;
2220: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2221: }
2222:
2223: sub courseiddump {
1.791 raeburn 2224: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353 www 2225: my %returnhash=();
1.355 www 2226: unless ($domfilter) { $domfilter=''; }
1.845 albertel 2227: my %libserv = &all_library();
2228: foreach my $tryserver (keys(%libserv)) {
2229: if ( ( $hostidflag == 1
2230: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
2231: || (!defined($hostidflag)) ) {
2232:
2233: if ($domfilter eq ''
2234: || (&host_domain($tryserver) eq $domfilter)) {
1.800 albertel 2235: foreach my $line (
1.844 albertel 2236: split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571 raeburn 2237: $sincefilter.':'.&escape($descfilter).':'.
1.791 raeburn 2238: &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354 www 2239: $tryserver))) {
1.800 albertel 2240: my ($key,$value)=split(/\=/,$line,2);
1.506 raeburn 2241: if (($key) && ($value)) {
1.516 raeburn 2242: $returnhash{&unescape($key)}=$value;
1.506 raeburn 2243: }
1.353 www 2244: }
2245: }
2246: }
2247: }
2248: return %returnhash;
2249: }
2250:
1.658 raeburn 2251: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 2252:
2253: sub dcmailput {
1.685 raeburn 2254: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 2255: my $status = &Apache::lonnet::critical(
1.740 www 2256: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2257: &escape($message),$server);
1.662 raeburn 2258: return $status;
2259: }
2260:
1.658 raeburn 2261: sub dcmaildump {
2262: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 2263: my %returnhash=();
1.846 albertel 2264:
2265: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 2266: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2267: &escape($enddate).':';
2268: my @esc_senders=map { &escape($_)} @$senders;
2269: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 2270: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 2271: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 2272: if (($key) && ($value)) {
2273: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 2274: }
2275: }
2276: }
2277: return %returnhash;
2278: }
1.662 raeburn 2279: # ---------------------------------------------------------- Domain roles
2280:
2281: sub get_domain_roles {
2282: my ($dom,$roles,$startdate,$enddate)=@_;
2283: if (undef($startdate) || $startdate eq '') {
2284: $startdate = '.';
2285: }
2286: if (undef($enddate) || $enddate eq '') {
2287: $enddate = '.';
2288: }
2289: my $rolelist = join(':',@{$roles});
2290: my %personnel = ();
1.841 albertel 2291:
2292: my %servers = &get_servers($dom,'library');
2293: foreach my $tryserver (keys(%servers)) {
2294: %{$personnel{$tryserver}}=();
2295: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
2296: &escape($startdate).':'.
2297: &escape($enddate).':'.
2298: &escape($rolelist), $tryserver))) {
2299: my ($key,$value) = split(/\=/,$line,2);
2300: if (($key) && ($value)) {
2301: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2302: }
2303: }
1.662 raeburn 2304: }
2305: return %personnel;
2306: }
1.658 raeburn 2307:
1.149 www 2308: # ----------------------------------------------------------- Check out an item
2309:
1.504 albertel 2310: sub get_first_access {
2311: my ($type,$argsymb)=@_;
1.790 albertel 2312: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2313: if ($argsymb) { $symb=$argsymb; }
2314: my ($map,$id,$res)=&decode_symb($symb);
1.588 albertel 2315: if ($type eq 'map') {
2316: $res=&symbread($map);
2317: } else {
2318: $res=$symb;
2319: }
2320: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2321: return $times{"$courseid\0$res"};
1.504 albertel 2322: }
2323:
2324: sub set_first_access {
2325: my ($type)=@_;
1.790 albertel 2326: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2327: my ($map,$id,$res)=&decode_symb($symb);
1.588 albertel 2328: if ($type eq 'map') {
2329: $res=&symbread($map);
2330: } else {
2331: $res=$symb;
2332: }
2333: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 2334: if (!$firstaccess) {
1.588 albertel 2335: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 2336: }
2337: return 'already_set';
1.504 albertel 2338: }
2339:
1.149 www 2340: sub checkout {
2341: my ($symb,$tuname,$tudom,$tcrsid)=@_;
2342: my $now=time;
2343: my $lonhost=$perlvar{'lonHostID'};
2344: my $infostr=&escape(
1.234 www 2345: 'CHECKOUTTOKEN&'.
1.149 www 2346: $tuname.'&'.
2347: $tudom.'&'.
2348: $tcrsid.'&'.
2349: $symb.'&'.
2350: $now.'&'.$ENV{'REMOTE_ADDR'});
2351: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 2352: if ($token=~/^error\:/) {
1.672 albertel 2353: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2354: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
2355: "</font>");
2356: return '';
2357: }
2358:
1.149 www 2359: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
2360: $token=~tr/a-z/A-Z/;
2361:
1.153 www 2362: my %infohash=('resource.0.outtoken' => $token,
2363: 'resource.0.checkouttime' => $now,
2364: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 2365:
2366: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2367: return '';
1.151 www 2368: } else {
1.672 albertel 2369: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2370: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
2371: "</font>");
1.149 www 2372: }
2373:
2374: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2375: &escape('Checkout '.$infostr.' - '.
2376: $token)) ne 'ok') {
2377: return '';
1.151 www 2378: } else {
1.672 albertel 2379: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2380: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
2381: "</font>");
1.149 www 2382: }
1.151 www 2383: return $token;
1.149 www 2384: }
2385:
2386: # ------------------------------------------------------------ Check in an item
2387:
2388: sub checkin {
2389: my $token=shift;
1.150 www 2390: my $now=time;
2391: my ($ta,$tb,$lonhost)=split(/\*/,$token);
2392: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 2393: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 2394: $dtoken=~s/\W/\_/g;
1.234 www 2395: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 2396: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
2397:
1.154 www 2398: unless (($tuname) && ($tudom)) {
2399: &logthis('Check in '.$token.' ('.$dtoken.') failed');
2400: return '';
2401: }
2402:
2403: unless (&allowed('mgr',$tcrsid)) {
2404: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 2405: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 2406: return '';
2407: }
2408:
1.153 www 2409: my %infohash=('resource.0.intoken' => $token,
2410: 'resource.0.checkintime' => $now,
2411: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 2412:
2413: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2414: return '';
2415: }
2416:
2417: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2418: &escape('Checkin - '.$token)) ne 'ok') {
2419: return '';
2420: }
2421:
2422: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 2423: }
2424:
2425: # --------------------------------------------- Set Expire Date for Spreadsheet
2426:
2427: sub expirespread {
2428: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 2429: my $cid=$env{'request.course.id'};
1.110 www 2430: if ($cid) {
2431: my $now=time;
2432: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 2433: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
2434: $env{'course.'.$cid.'.num'}.
1.110 www 2435: ':nohist_expirationdates:'.
2436: &escape($key).'='.$now,
1.620 albertel 2437: $env{'course.'.$cid.'.home'})
1.110 www 2438: }
2439: return 'ok';
1.14 www 2440: }
2441:
1.109 www 2442: # ----------------------------------------------------- Devalidate Spreadsheets
2443:
2444: sub devalidate {
1.325 www 2445: my ($symb,$uname,$udom)=@_;
1.620 albertel 2446: my $cid=$env{'request.course.id'};
1.109 www 2447: if ($cid) {
1.391 matthew 2448: # delete the stored spreadsheets for
2449: # - the student level sheet of this user in course's homespace
2450: # - the assessment level sheet for this resource
2451: # for this user in user's homespace
1.553 albertel 2452: # - current conditional state info
1.325 www 2453: my $key=$uname.':'.$udom.':';
1.109 www 2454: my $status=
1.299 matthew 2455: &del('nohist_calculatedsheets',
1.391 matthew 2456: [$key.'studentcalc:'],
1.620 albertel 2457: $env{'course.'.$cid.'.domain'},
2458: $env{'course.'.$cid.'.num'})
1.133 albertel 2459: .' '.
2460: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 2461: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 2462: unless ($status eq 'ok ok') {
2463: &logthis('Could not devalidate spreadsheet '.
1.325 www 2464: $uname.' at '.$udom.' for '.
1.109 www 2465: $symb.': '.$status);
1.133 albertel 2466: }
1.553 albertel 2467: &delenv('user.state.'.$cid);
1.109 www 2468: }
2469: }
2470:
1.265 albertel 2471: sub get_scalar {
2472: my ($string,$end) = @_;
2473: my $value;
2474: if ($$string =~ s/^([^&]*?)($end)/$2/) {
2475: $value = $1;
2476: } elsif ($$string =~ s/^([^&]*?)&//) {
2477: $value = $1;
2478: }
2479: return &unescape($value);
2480: }
2481:
2482: sub array2str {
2483: my (@array) = @_;
2484: my $result=&arrayref2str(\@array);
2485: $result=~s/^__ARRAY_REF__//;
2486: $result=~s/__END_ARRAY_REF__$//;
2487: return $result;
2488: }
2489:
1.204 albertel 2490: sub arrayref2str {
2491: my ($arrayref) = @_;
1.265 albertel 2492: my $result='__ARRAY_REF__';
1.204 albertel 2493: foreach my $elem (@$arrayref) {
1.265 albertel 2494: if(ref($elem) eq 'ARRAY') {
2495: $result.=&arrayref2str($elem).'&';
2496: } elsif(ref($elem) eq 'HASH') {
2497: $result.=&hashref2str($elem).'&';
2498: } elsif(ref($elem)) {
2499: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 2500: } else {
2501: $result.=&escape($elem).'&';
2502: }
2503: }
2504: $result=~s/\&$//;
1.265 albertel 2505: $result .= '__END_ARRAY_REF__';
1.204 albertel 2506: return $result;
2507: }
2508:
1.168 albertel 2509: sub hash2str {
1.204 albertel 2510: my (%hash) = @_;
2511: my $result=&hashref2str(\%hash);
1.265 albertel 2512: $result=~s/^__HASH_REF__//;
2513: $result=~s/__END_HASH_REF__$//;
1.204 albertel 2514: return $result;
2515: }
2516:
2517: sub hashref2str {
2518: my ($hashref)=@_;
1.265 albertel 2519: my $result='__HASH_REF__';
1.800 albertel 2520: foreach my $key (sort(keys(%$hashref))) {
2521: if (ref($key) eq 'ARRAY') {
2522: $result.=&arrayref2str($key).'=';
2523: } elsif (ref($key) eq 'HASH') {
2524: $result.=&hashref2str($key).'=';
2525: } elsif (ref($key)) {
1.265 albertel 2526: $result.='=';
1.800 albertel 2527: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 2528: } else {
1.800 albertel 2529: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 2530: }
2531:
1.800 albertel 2532: if(ref($hashref->{$key}) eq 'ARRAY') {
2533: $result.=&arrayref2str($hashref->{$key}).'&';
2534: } elsif(ref($hashref->{$key}) eq 'HASH') {
2535: $result.=&hashref2str($hashref->{$key}).'&';
2536: } elsif(ref($hashref->{$key})) {
1.265 albertel 2537: $result.='&';
1.800 albertel 2538: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 2539: } else {
1.800 albertel 2540: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 2541: }
2542: }
1.168 albertel 2543: $result=~s/\&$//;
1.265 albertel 2544: $result .= '__END_HASH_REF__';
1.168 albertel 2545: return $result;
2546: }
2547:
2548: sub str2hash {
1.265 albertel 2549: my ($string)=@_;
2550: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
2551: return %$hash;
2552: }
2553:
2554: sub str2hashref {
1.168 albertel 2555: my ($string) = @_;
1.265 albertel 2556:
2557: my %hash;
2558:
2559: if($string !~ /^__HASH_REF__/) {
2560: if (! ($string eq '' || !defined($string))) {
2561: $hash{'error'}='Not hash reference';
2562: }
2563: return (\%hash, $string);
2564: }
2565:
2566: $string =~ s/^__HASH_REF__//;
2567:
2568: while($string !~ /^__END_HASH_REF__/) {
2569: #key
2570: my $key='';
2571: if($string =~ /^__HASH_REF__/) {
2572: ($key, $string)=&str2hashref($string);
2573: if(defined($key->{'error'})) {
2574: $hash{'error'}='Bad data';
2575: return (\%hash, $string);
2576: }
2577: } elsif($string =~ /^__ARRAY_REF__/) {
2578: ($key, $string)=&str2arrayref($string);
2579: if($key->[0] eq 'Array reference error') {
2580: $hash{'error'}='Bad data';
2581: return (\%hash, $string);
2582: }
2583: } else {
2584: $string =~ s/^(.*?)=//;
1.267 albertel 2585: $key=&unescape($1);
1.265 albertel 2586: }
2587: $string =~ s/^=//;
2588:
2589: #value
2590: my $value='';
2591: if($string =~ /^__HASH_REF__/) {
2592: ($value, $string)=&str2hashref($string);
2593: if(defined($value->{'error'})) {
2594: $hash{'error'}='Bad data';
2595: return (\%hash, $string);
2596: }
2597: } elsif($string =~ /^__ARRAY_REF__/) {
2598: ($value, $string)=&str2arrayref($string);
2599: if($value->[0] eq 'Array reference error') {
2600: $hash{'error'}='Bad data';
2601: return (\%hash, $string);
2602: }
2603: } else {
2604: $value=&get_scalar(\$string,'__END_HASH_REF__');
2605: }
2606: $string =~ s/^&//;
2607:
2608: $hash{$key}=$value;
1.204 albertel 2609: }
1.265 albertel 2610:
2611: $string =~ s/^__END_HASH_REF__//;
2612:
2613: return (\%hash, $string);
1.204 albertel 2614: }
2615:
2616: sub str2array {
1.265 albertel 2617: my ($string)=@_;
2618: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
2619: return @$array;
2620: }
2621:
2622: sub str2arrayref {
1.204 albertel 2623: my ($string) = @_;
1.265 albertel 2624: my @array;
2625:
2626: if($string !~ /^__ARRAY_REF__/) {
2627: if (! ($string eq '' || !defined($string))) {
2628: $array[0]='Array reference error';
2629: }
2630: return (\@array, $string);
2631: }
2632:
2633: $string =~ s/^__ARRAY_REF__//;
2634:
2635: while($string !~ /^__END_ARRAY_REF__/) {
2636: my $value='';
2637: if($string =~ /^__HASH_REF__/) {
2638: ($value, $string)=&str2hashref($string);
2639: if(defined($value->{'error'})) {
2640: $array[0] ='Array reference error';
2641: return (\@array, $string);
2642: }
2643: } elsif($string =~ /^__ARRAY_REF__/) {
2644: ($value, $string)=&str2arrayref($string);
2645: if($value->[0] eq 'Array reference error') {
2646: $array[0] ='Array reference error';
2647: return (\@array, $string);
2648: }
2649: } else {
2650: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
2651: }
2652: $string =~ s/^&//;
2653:
2654: push(@array, $value);
1.191 harris41 2655: }
1.265 albertel 2656:
2657: $string =~ s/^__END_ARRAY_REF__//;
2658:
2659: return (\@array, $string);
1.168 albertel 2660: }
2661:
1.167 albertel 2662: # -------------------------------------------------------------------Temp Store
2663:
1.168 albertel 2664: sub tmpreset {
2665: my ($symb,$namespace,$domain,$stuname) = @_;
2666: if (!$symb) {
2667: $symb=&symbread();
1.620 albertel 2668: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2669: }
2670: $symb=escape($symb);
2671:
1.620 albertel 2672: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 2673: $namespace=~s/\//\_/g;
2674: $namespace=~s/\W//g;
2675:
1.620 albertel 2676: if (!$domain) { $domain=$env{'user.domain'}; }
2677: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2678: if ($domain eq 'public' && $stuname eq 'public') {
2679: $stuname=$ENV{'REMOTE_ADDR'};
2680: }
1.168 albertel 2681: my $path=$perlvar{'lonDaemons'}.'/tmp';
2682: my %hash;
2683: if (tie(%hash,'GDBM_File',
2684: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2685: &GDBM_WRCREAT(),0640)) {
1.168 albertel 2686: foreach my $key (keys %hash) {
1.180 albertel 2687: if ($key=~ /:$symb/) {
1.168 albertel 2688: delete($hash{$key});
2689: }
2690: }
2691: }
2692: }
2693:
1.167 albertel 2694: sub tmpstore {
1.168 albertel 2695: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2696:
2697: if (!$symb) {
2698: $symb=&symbread();
1.620 albertel 2699: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2700: }
2701: $symb=escape($symb);
2702:
2703: if (!$namespace) {
2704: # I don't think we would ever want to store this for a course.
2705: # it seems this will only be used if we don't have a course.
1.620 albertel 2706: #$namespace=$env{'request.course.id'};
1.168 albertel 2707: #if (!$namespace) {
1.620 albertel 2708: $namespace=$env{'request.state'};
1.168 albertel 2709: #}
2710: }
2711: $namespace=~s/\//\_/g;
2712: $namespace=~s/\W//g;
1.620 albertel 2713: if (!$domain) { $domain=$env{'user.domain'}; }
2714: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2715: if ($domain eq 'public' && $stuname eq 'public') {
2716: $stuname=$ENV{'REMOTE_ADDR'};
2717: }
1.168 albertel 2718: my $now=time;
2719: my %hash;
2720: my $path=$perlvar{'lonDaemons'}.'/tmp';
2721: if (tie(%hash,'GDBM_File',
2722: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2723: &GDBM_WRCREAT(),0640)) {
1.168 albertel 2724: $hash{"version:$symb"}++;
2725: my $version=$hash{"version:$symb"};
2726: my $allkeys='';
2727: foreach my $key (keys(%$storehash)) {
2728: $allkeys.=$key.':';
1.591 albertel 2729: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 2730: }
2731: $hash{"$version:$symb:timestamp"}=$now;
2732: $allkeys.='timestamp';
2733: $hash{"$version:keys:$symb"}=$allkeys;
2734: if (untie(%hash)) {
2735: return 'ok';
2736: } else {
2737: return "error:$!";
2738: }
2739: } else {
2740: return "error:$!";
2741: }
2742: }
1.167 albertel 2743:
1.168 albertel 2744: # -----------------------------------------------------------------Temp Restore
1.167 albertel 2745:
1.168 albertel 2746: sub tmprestore {
2747: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 2748:
1.168 albertel 2749: if (!$symb) {
2750: $symb=&symbread();
1.620 albertel 2751: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2752: }
2753: $symb=escape($symb);
2754:
1.620 albertel 2755: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 2756:
1.620 albertel 2757: if (!$domain) { $domain=$env{'user.domain'}; }
2758: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2759: if ($domain eq 'public' && $stuname eq 'public') {
2760: $stuname=$ENV{'REMOTE_ADDR'};
2761: }
1.168 albertel 2762: my %returnhash;
2763: $namespace=~s/\//\_/g;
2764: $namespace=~s/\W//g;
2765: my %hash;
2766: my $path=$perlvar{'lonDaemons'}.'/tmp';
2767: if (tie(%hash,'GDBM_File',
2768: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2769: &GDBM_READER(),0640)) {
1.168 albertel 2770: my $version=$hash{"version:$symb"};
2771: $returnhash{'version'}=$version;
2772: my $scope;
2773: for ($scope=1;$scope<=$version;$scope++) {
2774: my $vkeys=$hash{"$scope:keys:$symb"};
2775: my @keys=split(/:/,$vkeys);
2776: my $key;
2777: $returnhash{"$scope:keys"}=$vkeys;
2778: foreach $key (@keys) {
1.591 albertel 2779: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
2780: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 2781: }
2782: }
1.168 albertel 2783: if (!(untie(%hash))) {
2784: return "error:$!";
2785: }
2786: } else {
2787: return "error:$!";
2788: }
2789: return %returnhash;
1.167 albertel 2790: }
2791:
1.9 www 2792: # ----------------------------------------------------------------------- Store
2793:
2794: sub store {
1.124 www 2795: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2796: my $home='';
2797:
1.168 albertel 2798: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2799:
1.213 www 2800: $symb=&symbclean($symb);
1.122 albertel 2801: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 2802:
1.620 albertel 2803: if (!$domain) { $domain=$env{'user.domain'}; }
2804: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 2805:
2806: &devalidate($symb,$stuname,$domain);
1.109 www 2807:
2808: $symb=escape($symb);
1.187 www 2809: if (!$namespace) {
1.620 albertel 2810: unless ($namespace=$env{'request.course.id'}) {
1.187 www 2811: return '';
2812: }
2813: }
1.620 albertel 2814: if (!$home) { $home=$env{'user.home'}; }
1.447 www 2815:
2816: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2817: $$storehash{'host'}=$perlvar{'lonHostID'};
2818:
1.12 www 2819: my $namevalue='';
1.800 albertel 2820: foreach my $key (keys(%$storehash)) {
2821: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 2822: }
1.12 www 2823: $namevalue=~s/\&$//;
1.187 www 2824: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 2825: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 2826: }
2827:
1.47 www 2828: # -------------------------------------------------------------- Critical Store
2829:
2830: sub cstore {
1.124 www 2831: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2832: my $home='';
2833:
1.168 albertel 2834: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2835:
1.213 www 2836: $symb=&symbclean($symb);
1.122 albertel 2837: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 2838:
1.620 albertel 2839: if (!$domain) { $domain=$env{'user.domain'}; }
2840: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 2841:
2842: &devalidate($symb,$stuname,$domain);
1.109 www 2843:
2844: $symb=escape($symb);
1.187 www 2845: if (!$namespace) {
1.620 albertel 2846: unless ($namespace=$env{'request.course.id'}) {
1.187 www 2847: return '';
2848: }
2849: }
1.620 albertel 2850: if (!$home) { $home=$env{'user.home'}; }
1.447 www 2851:
2852: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2853: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 2854:
1.47 www 2855: my $namevalue='';
1.800 albertel 2856: foreach my $key (keys(%$storehash)) {
2857: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 2858: }
1.47 www 2859: $namevalue=~s/\&$//;
1.187 www 2860: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 2861: return critical
2862: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 2863: }
2864:
1.9 www 2865: # --------------------------------------------------------------------- Restore
2866:
2867: sub restore {
1.124 www 2868: my ($symb,$namespace,$domain,$stuname) = @_;
2869: my $home='';
2870:
1.168 albertel 2871: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2872:
1.122 albertel 2873: if (!$symb) {
2874: unless ($symb=escape(&symbread())) { return ''; }
2875: } else {
1.213 www 2876: $symb=&escape(&symbclean($symb));
1.122 albertel 2877: }
1.188 www 2878: if (!$namespace) {
1.620 albertel 2879: unless ($namespace=$env{'request.course.id'}) {
1.188 www 2880: return '';
2881: }
2882: }
1.620 albertel 2883: if (!$domain) { $domain=$env{'user.domain'}; }
2884: if (!$stuname) { $stuname=$env{'user.name'}; }
2885: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 2886: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
2887:
1.12 www 2888: my %returnhash=();
1.800 albertel 2889: foreach my $line (split(/\&/,$answer)) {
2890: my ($name,$value)=split(/\=/,$line);
1.591 albertel 2891: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 2892: }
1.75 www 2893: my $version;
2894: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 2895: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
2896: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 2897: }
1.75 www 2898: }
1.13 www 2899: return %returnhash;
1.34 www 2900: }
2901:
2902: # ---------------------------------------------------------- Course Description
2903:
2904: sub coursedescription {
1.731 albertel 2905: my ($courseid,$args)=@_;
1.34 www 2906: $courseid=~s/^\///;
1.49 www 2907: $courseid=~s/\_/\//g;
1.34 www 2908: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 2909: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 2910: my $normalid=$cdomain.'_'.$cnum;
2911: # need to always cache even if we get errors otherwise we keep
2912: # trying and trying and trying to get the course description.
2913: my %envhash=();
2914: my %returnhash=();
1.731 albertel 2915:
2916: my $expiretime=600;
2917: if ($env{'request.course.id'} eq $normalid) {
2918: $expiretime=120;
2919: }
2920:
2921: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
2922: if (!$args->{'freshen_cache'}
2923: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
2924: foreach my $key (keys(%env)) {
2925: next if ($key !~ /^\Q$prefix\E(.*)/);
2926: my ($setting) = $1;
2927: $returnhash{$setting} = $env{$key};
2928: }
2929: return %returnhash;
2930: }
2931:
2932: # get the data agin
2933: if (!$args->{'one_time'}) {
2934: $envhash{'course.'.$normalid.'.last_cache'}=time;
2935: }
1.811 albertel 2936:
1.34 www 2937: if ($chome ne 'no_host') {
1.302 albertel 2938: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 2939: if (!exists($returnhash{'con_lost'})) {
2940: $returnhash{'home'}= $chome;
2941: $returnhash{'domain'} = $cdomain;
2942: $returnhash{'num'} = $cnum;
1.741 raeburn 2943: if (!defined($returnhash{'type'})) {
2944: $returnhash{'type'} = 'Course';
2945: }
1.130 albertel 2946: while (my ($name,$value) = each %returnhash) {
1.53 www 2947: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 2948: }
1.270 www 2949: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 2950: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 2951: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 2952: $envhash{'course.'.$normalid.'.home'}=$chome;
2953: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
2954: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 2955: }
2956: }
1.731 albertel 2957: if (!$args->{'one_time'}) {
2958: &appenv(%envhash);
2959: }
1.302 albertel 2960: return %returnhash;
1.461 www 2961: }
2962:
2963: # -------------------------------------------------See if a user is privileged
2964:
2965: sub privileged {
2966: my ($username,$domain)=@_;
2967: my $rolesdump=&reply("dump:$domain:$username:roles",
2968: &homeserver($username,$domain));
2969: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
2970: my $now=time;
2971: if ($rolesdump ne '') {
1.800 albertel 2972: foreach my $entry (split(/&/,$rolesdump)) {
2973: if ($entry!~/^rolesdef_/) {
2974: my ($area,$role)=split(/=/,$entry);
1.461 www 2975: $area=~s/\_\w\w$//;
2976: my ($trole,$tend,$tstart)=split(/_/,$role);
2977: if (($trole eq 'dc') || ($trole eq 'su')) {
2978: my $active=1;
2979: if ($tend) {
2980: if ($tend<$now) { $active=0; }
2981: }
2982: if ($tstart) {
2983: if ($tstart>$now) { $active=0; }
2984: }
2985: if ($active) { return 1; }
2986: }
2987: }
2988: }
2989: }
2990: return 0;
1.9 www 2991: }
1.1 albertel 2992:
1.103 harris41 2993: # -------------------------------------------------------- Get user privileges
1.11 www 2994:
2995: sub rolesinit {
2996: my ($domain,$username,$authhost)=@_;
2997: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12 www 2998: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11 www 2999: my %allroles=();
1.678 raeburn 3000: my %allgroups=();
1.11 www 3001: my $now=time;
1.743 albertel 3002: my %userroles = ('user.login.time' => $now);
1.678 raeburn 3003: my $group_privs;
1.11 www 3004:
3005: if ($rolesdump ne '') {
1.800 albertel 3006: foreach my $entry (split(/&/,$rolesdump)) {
3007: if ($entry!~/^rolesdef_/) {
3008: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3009: $area=~s/\_\w\w$//;
1.678 raeburn 3010: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3011: if ($role=~/^cr/) {
1.807 albertel 3012: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3013: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3014: ($tend,$tstart)=split('_',$trest);
3015: } else {
3016: $trole=$role;
3017: }
1.678 raeburn 3018: } elsif ($role =~ m|^gr/|) {
3019: ($trole,$tend,$tstart) = split(/_/,$role);
3020: ($trole,$group_privs) = split(/\//,$trole);
3021: $group_privs = &unescape($group_privs);
1.587 albertel 3022: } else {
3023: ($trole,$tend,$tstart)=split(/_/,$role);
3024: }
1.743 albertel 3025: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3026: $username);
3027: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3028: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3029: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3030: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3031: my $spec=$trole.'.'.$area;
3032: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3033: if ($trole =~ /^cr\//) {
1.567 raeburn 3034: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3035: } elsif ($trole eq 'gr') {
3036: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3037: } else {
1.567 raeburn 3038: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3039: }
1.12 www 3040: }
1.662 raeburn 3041: }
1.191 harris41 3042: }
1.743 albertel 3043: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3044: $userroles{'user.adv'} = $adv;
3045: $userroles{'user.author'} = $author;
1.620 albertel 3046: $env{'user.adv'}=$adv;
1.11 www 3047: }
1.743 albertel 3048: return \%userroles;
1.11 www 3049: }
3050:
1.567 raeburn 3051: sub set_arearole {
3052: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3053: # log the associated role with the area
3054: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3055: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3056: }
3057:
3058: sub custom_roleprivs {
3059: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3060: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3061: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3062: if (&hostname($homsvr) ne '') {
1.567 raeburn 3063: my ($rdummy,$roledef)=
3064: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3065: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3066: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3067: if (defined($syspriv)) {
3068: $$allroles{'cm./'}.=':'.$syspriv;
3069: $$allroles{$spec.'./'}.=':'.$syspriv;
3070: }
3071: if ($tdomain ne '') {
3072: if (defined($dompriv)) {
3073: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3074: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3075: }
3076: if (($trest ne '') && (defined($coursepriv))) {
3077: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3078: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3079: }
3080: }
3081: }
3082: }
3083: }
3084:
1.678 raeburn 3085: sub group_roleprivs {
3086: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3087: my $access = 1;
3088: my $now = time;
3089: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3090: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3091: if ($access) {
1.811 albertel 3092: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3093: $$allgroups{$course}{$group} .=':'.$group_privs;
3094: }
3095: }
1.567 raeburn 3096:
3097: sub standard_roleprivs {
3098: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3099: if (defined($pr{$trole.':s'})) {
3100: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3101: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3102: }
3103: if ($tdomain ne '') {
3104: if (defined($pr{$trole.':d'})) {
3105: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3106: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3107: }
3108: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3109: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3110: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3111: }
3112: }
3113: }
3114:
3115: sub set_userprivs {
1.678 raeburn 3116: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 3117: my $author=0;
3118: my $adv=0;
1.678 raeburn 3119: my %grouproles = ();
3120: if (keys(%{$allgroups}) > 0) {
3121: foreach my $role (keys %{$allroles}) {
1.681 raeburn 3122: my ($trole,$area,$sec,$extendedarea);
1.811 albertel 3123: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678 raeburn 3124: $trole = $1;
3125: $area = $2;
1.681 raeburn 3126: $sec = $3;
3127: $extendedarea = $area.$sec;
3128: if (exists($$allgroups{$area})) {
3129: foreach my $group (keys(%{$$allgroups{$area}})) {
3130: my $spec = $trole.'.'.$extendedarea;
3131: $grouproles{$spec.'.'.$area.'/'.$group} =
3132: $$allgroups{$area}{$group};
1.678 raeburn 3133: }
3134: }
3135: }
3136: }
3137: }
1.800 albertel 3138: foreach my $group (keys(%grouproles)) {
3139: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3140: }
1.800 albertel 3141: foreach my $role (keys(%{$allroles})) {
3142: my %thesepriv;
3143: if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
3144: foreach my $item (split(/:/,$$allroles{$role})) {
3145: if ($item ne '') {
3146: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3147: if ($restrictions eq '') {
3148: $thesepriv{$privilege}='F';
3149: } elsif ($thesepriv{$privilege} ne 'F') {
3150: $thesepriv{$privilege}.=$restrictions;
3151: }
3152: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3153: }
3154: }
3155: my $thesestr='';
1.800 albertel 3156: foreach my $priv (keys(%thesepriv)) {
3157: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3158: }
3159: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3160: }
3161: return ($author,$adv);
3162: }
3163:
1.12 www 3164: # --------------------------------------------------------------- get interface
3165:
3166: sub get {
1.131 albertel 3167: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3168: my $items='';
1.800 albertel 3169: foreach my $item (@$storearr) {
3170: $items.=&escape($item).'&';
1.191 harris41 3171: }
1.12 www 3172: $items=~s/\&$//;
1.620 albertel 3173: if (!$udomain) { $udomain=$env{'user.domain'}; }
3174: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 3175: my $uhome=&homeserver($uname,$udomain);
3176:
1.133 albertel 3177: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3178: my @pairs=split(/\&/,$rep);
1.273 albertel 3179: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
3180: return @pairs;
3181: }
1.15 www 3182: my %returnhash=();
1.42 www 3183: my $i=0;
1.800 albertel 3184: foreach my $item (@$storearr) {
3185: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3186: $i++;
1.191 harris41 3187: }
1.15 www 3188: return %returnhash;
1.27 www 3189: }
3190:
3191: # --------------------------------------------------------------- del interface
3192:
3193: sub del {
1.133 albertel 3194: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 3195: my $items='';
1.800 albertel 3196: foreach my $item (@$storearr) {
3197: $items.=&escape($item).'&';
1.191 harris41 3198: }
1.27 www 3199: $items=~s/\&$//;
1.620 albertel 3200: if (!$udomain) { $udomain=$env{'user.domain'}; }
3201: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3202: my $uhome=&homeserver($uname,$udomain);
3203:
3204: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3205: }
3206:
3207: # -------------------------------------------------------------- dump interface
3208:
3209: sub dump {
1.755 albertel 3210: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3211: if (!$udomain) { $udomain=$env{'user.domain'}; }
3212: if (!$uname) { $uname=$env{'user.name'}; }
3213: my $uhome=&homeserver($uname,$udomain);
3214: if ($regexp) {
3215: $regexp=&escape($regexp);
3216: } else {
3217: $regexp='.';
3218: }
3219: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3220: my @pairs=split(/\&/,$rep);
3221: my %returnhash=();
3222: foreach my $item (@pairs) {
3223: my ($key,$value)=split(/=/,$item,2);
3224: $key = &unescape($key);
3225: next if ($key =~ /^error: 2 /);
3226: $returnhash{$key}=&thaw_unescape($value);
3227: }
3228: return %returnhash;
1.407 www 3229: }
3230:
1.717 albertel 3231: # --------------------------------------------------------- dumpstore interface
3232:
3233: sub dumpstore {
3234: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 3235: if (!$udomain) { $udomain=$env{'user.domain'}; }
3236: if (!$uname) { $uname=$env{'user.name'}; }
3237: my $uhome=&homeserver($uname,$udomain);
3238: if ($regexp) {
3239: $regexp=&escape($regexp);
3240: } else {
3241: $regexp='.';
3242: }
3243: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3244: my @pairs=split(/\&/,$rep);
3245: my %returnhash=();
3246: foreach my $item (@pairs) {
3247: my ($key,$value)=split(/=/,$item,2);
3248: next if ($key =~ /^error: 2 /);
3249: $returnhash{$key}=&thaw_unescape($value);
3250: }
3251: return %returnhash;
1.717 albertel 3252: }
3253:
1.407 www 3254: # -------------------------------------------------------------- keys interface
3255:
3256: sub getkeys {
3257: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 3258: if (!$udomain) { $udomain=$env{'user.domain'}; }
3259: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 3260: my $uhome=&homeserver($uname,$udomain);
3261: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3262: my @keyarray=();
1.800 albertel 3263: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 3264: next if ($key =~ /^error: 2 /);
1.800 albertel 3265: push(@keyarray,&unescape($key));
1.407 www 3266: }
3267: return @keyarray;
1.318 matthew 3268: }
3269:
1.319 matthew 3270: # --------------------------------------------------------------- currentdump
3271: sub currentdump {
1.328 matthew 3272: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 3273: $courseid = $env{'request.course.id'} if (! defined($courseid));
3274: $sdom = $env{'user.domain'} if (! defined($sdom));
3275: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 3276: my $uhome = &homeserver($sname,$sdom);
3277: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 3278: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 3279: #
1.318 matthew 3280: my %returnhash=();
1.319 matthew 3281: #
3282: if ($rep eq "unknown_cmd") {
3283: # an old lond will not know currentdump
3284: # Do a dump and make it look like a currentdump
1.822 albertel 3285: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 3286: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3287: my %hash = @tmp;
3288: @tmp=();
1.424 matthew 3289: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 3290: } else {
3291: my @pairs=split(/\&/,$rep);
1.800 albertel 3292: foreach my $pair (@pairs) {
3293: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 3294: my ($symb,$param) = split(/:/,$key);
3295: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 3296: &thaw_unescape($value);
1.319 matthew 3297: }
1.191 harris41 3298: }
1.12 www 3299: return %returnhash;
1.424 matthew 3300: }
3301:
3302: sub convert_dump_to_currentdump{
3303: my %hash = %{shift()};
3304: my %returnhash;
3305: # Code ripped from lond, essentially. The only difference
3306: # here is the unescaping done by lonnet::dump(). Conceivably
3307: # we might run in to problems with parameter names =~ /^v\./
3308: while (my ($key,$value) = each(%hash)) {
3309: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 3310: $symb = &unescape($symb);
3311: $param = &unescape($param);
1.424 matthew 3312: next if ($v eq 'version' || $symb eq 'keys');
3313: next if (exists($returnhash{$symb}) &&
3314: exists($returnhash{$symb}->{$param}) &&
3315: $returnhash{$symb}->{'v.'.$param} > $v);
3316: $returnhash{$symb}->{$param}=$value;
3317: $returnhash{$symb}->{'v.'.$param}=$v;
3318: }
3319: #
3320: # Remove all of the keys in the hashes which keep track of
3321: # the version of the parameter.
3322: while (my ($symb,$param_hash) = each(%returnhash)) {
3323: # use a foreach because we are going to delete from the hash.
3324: foreach my $key (keys(%$param_hash)) {
3325: delete($param_hash->{$key}) if ($key =~ /^v\./);
3326: }
3327: }
3328: return \%returnhash;
1.12 www 3329: }
3330:
1.627 albertel 3331: # ------------------------------------------------------ critical inc interface
3332:
3333: sub cinc {
3334: return &inc(@_,'critical');
3335: }
3336:
1.449 matthew 3337: # --------------------------------------------------------------- inc interface
3338:
3339: sub inc {
1.627 albertel 3340: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 3341: if (!$udomain) { $udomain=$env{'user.domain'}; }
3342: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 3343: my $uhome=&homeserver($uname,$udomain);
3344: my $items='';
3345: if (! ref($store)) {
3346: # got a single value, so use that instead
3347: $items = &escape($store).'=&';
3348: } elsif (ref($store) eq 'SCALAR') {
3349: $items = &escape($$store).'=&';
3350: } elsif (ref($store) eq 'ARRAY') {
3351: $items = join('=&',map {&escape($_);} @{$store});
3352: } elsif (ref($store) eq 'HASH') {
3353: while (my($key,$value) = each(%{$store})) {
3354: $items.= &escape($key).'='.&escape($value).'&';
3355: }
3356: }
3357: $items=~s/\&$//;
1.627 albertel 3358: if ($critical) {
3359: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
3360: } else {
3361: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
3362: }
1.449 matthew 3363: }
3364:
1.12 www 3365: # --------------------------------------------------------------- put interface
3366:
3367: sub put {
1.134 albertel 3368: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3369: if (!$udomain) { $udomain=$env{'user.domain'}; }
3370: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3371: my $uhome=&homeserver($uname,$udomain);
1.12 www 3372: my $items='';
1.800 albertel 3373: foreach my $item (keys(%$storehash)) {
3374: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3375: }
1.12 www 3376: $items=~s/\&$//;
1.134 albertel 3377: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 3378: }
3379:
1.631 albertel 3380: # ------------------------------------------------------------ newput interface
3381:
3382: sub newput {
3383: my ($namespace,$storehash,$udomain,$uname)=@_;
3384: if (!$udomain) { $udomain=$env{'user.domain'}; }
3385: if (!$uname) { $uname=$env{'user.name'}; }
3386: my $uhome=&homeserver($uname,$udomain);
3387: my $items='';
3388: foreach my $key (keys(%$storehash)) {
3389: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3390: }
3391: $items=~s/\&$//;
3392: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
3393: }
3394:
3395: # --------------------------------------------------------- putstore interface
3396:
1.524 raeburn 3397: sub putstore {
1.715 albertel 3398: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 3399: if (!$udomain) { $udomain=$env{'user.domain'}; }
3400: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 3401: my $uhome=&homeserver($uname,$udomain);
3402: my $items='';
1.715 albertel 3403: foreach my $key (keys(%$storehash)) {
3404: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 3405: }
1.715 albertel 3406: $items=~s/\&$//;
1.716 albertel 3407: my $esc_symb=&escape($symb);
3408: my $esc_v=&escape($version);
1.715 albertel 3409: my $reply =
1.716 albertel 3410: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 3411: $uhome);
3412: if ($reply eq 'unknown_cmd') {
1.716 albertel 3413: # gfall back to way things use to be done
1.715 albertel 3414: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
3415: $uname);
1.524 raeburn 3416: }
1.715 albertel 3417: return $reply;
3418: }
3419:
3420: sub old_putstore {
1.716 albertel 3421: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3422: if (!$udomain) { $udomain=$env{'user.domain'}; }
3423: if (!$uname) { $uname=$env{'user.name'}; }
3424: my $uhome=&homeserver($uname,$udomain);
3425: my %newstorehash;
1.800 albertel 3426: foreach my $item (keys(%$storehash)) {
3427: my $key = $version.':'.&escape($symb).':'.$item;
3428: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 3429: }
3430: my $items='';
3431: my %allitems = ();
1.800 albertel 3432: foreach my $item (keys(%newstorehash)) {
3433: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 3434: my $key = $1.':keys:'.$2;
3435: $allitems{$key} .= $3.':';
3436: }
1.800 albertel 3437: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 3438: }
1.800 albertel 3439: foreach my $item (keys(%allitems)) {
3440: $allitems{$item} =~ s/\:$//;
3441: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 3442: }
3443: $items=~s/\&$//;
3444: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 3445: }
3446:
1.47 www 3447: # ------------------------------------------------------ critical put interface
3448:
3449: sub cput {
1.134 albertel 3450: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3451: if (!$udomain) { $udomain=$env{'user.domain'}; }
3452: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3453: my $uhome=&homeserver($uname,$udomain);
1.47 www 3454: my $items='';
1.800 albertel 3455: foreach my $item (keys(%$storehash)) {
3456: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3457: }
1.47 www 3458: $items=~s/\&$//;
1.134 albertel 3459: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3460: }
3461:
3462: # -------------------------------------------------------------- eget interface
3463:
3464: sub eget {
1.133 albertel 3465: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3466: my $items='';
1.800 albertel 3467: foreach my $item (@$storearr) {
3468: $items.=&escape($item).'&';
1.191 harris41 3469: }
1.12 www 3470: $items=~s/\&$//;
1.620 albertel 3471: if (!$udomain) { $udomain=$env{'user.domain'}; }
3472: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3473: my $uhome=&homeserver($uname,$udomain);
3474: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3475: my @pairs=split(/\&/,$rep);
3476: my %returnhash=();
1.42 www 3477: my $i=0;
1.800 albertel 3478: foreach my $item (@$storearr) {
3479: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3480: $i++;
1.191 harris41 3481: }
1.12 www 3482: return %returnhash;
3483: }
3484:
1.667 albertel 3485: # ------------------------------------------------------------ tmpput interface
3486: sub tmpput {
1.802 raeburn 3487: my ($storehash,$server,$context)=@_;
1.667 albertel 3488: my $items='';
1.800 albertel 3489: foreach my $item (keys(%$storehash)) {
3490: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 3491: }
3492: $items=~s/\&$//;
1.802 raeburn 3493: if (defined($context)) {
3494: $items .= ':'.&escape($context);
3495: }
1.667 albertel 3496: return &reply("tmpput:$items",$server);
3497: }
3498:
3499: # ------------------------------------------------------------ tmpget interface
3500: sub tmpget {
1.688 albertel 3501: my ($token,$server)=@_;
3502: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3503: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 3504: my %returnhash;
3505: foreach my $item (split(/\&/,$rep)) {
3506: my ($key,$value)=split(/=/,$item);
3507: $returnhash{&unescape($key)}=&thaw_unescape($value);
3508: }
3509: return %returnhash;
3510: }
3511:
1.688 albertel 3512: # ------------------------------------------------------------ tmpget interface
3513: sub tmpdel {
3514: my ($token,$server)=@_;
3515: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3516: return &reply("tmpdel:$token",$server);
3517: }
3518:
1.765 albertel 3519: # -------------------------------------------------- portfolio access checking
3520:
3521: sub portfolio_access {
1.766 albertel 3522: my ($requrl) = @_;
1.765 albertel 3523: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
3524: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 3525: if ($result) {
3526: my %setters;
3527: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3528: my ($startblock,$endblock) =
3529: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
3530: if ($startblock && $endblock) {
3531: return 'B';
3532: }
3533: } else {
3534: my ($startblock,$endblock) =
3535: &Apache::loncommon::blockcheck(\%setters,'port');
3536: if ($startblock && $endblock) {
3537: return 'B';
3538: }
3539: }
3540: }
1.765 albertel 3541: if ($result eq 'ok') {
1.766 albertel 3542: return 'F';
1.765 albertel 3543: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 3544: return 'A';
1.765 albertel 3545: }
1.766 albertel 3546: return '';
1.765 albertel 3547: }
3548:
3549: sub get_portfolio_access {
1.767 albertel 3550: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
3551:
3552: if (!ref($access_hash)) {
3553: my $current_perms = &get_portfile_permissions($udom,$unum);
3554: my %access_controls = &get_access_controls($current_perms,$group,
3555: $file_name);
3556: $access_hash = $access_controls{$file_name};
3557: }
3558:
1.765 albertel 3559: my ($public,$guest,@domains,@users,@courses,@groups);
3560: my $now = time;
3561: if (ref($access_hash) eq 'HASH') {
3562: foreach my $key (keys(%{$access_hash})) {
3563: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
3564: if ($start > $now) {
3565: next;
3566: }
3567: if ($end && $end<$now) {
3568: next;
3569: }
3570: if ($scope eq 'public') {
3571: $public = $key;
3572: last;
3573: } elsif ($scope eq 'guest') {
3574: $guest = $key;
3575: } elsif ($scope eq 'domains') {
3576: push(@domains,$key);
3577: } elsif ($scope eq 'users') {
3578: push(@users,$key);
3579: } elsif ($scope eq 'course') {
3580: push(@courses,$key);
3581: } elsif ($scope eq 'group') {
3582: push(@groups,$key);
3583: }
3584: }
3585: if ($public) {
3586: return 'ok';
3587: }
3588: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3589: if ($guest) {
3590: return $guest;
3591: }
3592: } else {
3593: if (@domains > 0) {
3594: foreach my $domkey (@domains) {
3595: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
3596: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
3597: return 'ok';
3598: }
3599: }
3600: }
3601: }
3602: if (@users > 0) {
3603: foreach my $userkey (@users) {
1.865 raeburn 3604: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
3605: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
3606: if (ref($item) eq 'HASH') {
3607: if (($item->{'uname'} eq $env{'user.name'}) &&
3608: ($item->{'udom'} eq $env{'user.domain'})) {
3609: return 'ok';
3610: }
3611: }
3612: }
3613: }
1.765 albertel 3614: }
3615: }
3616: my %roleshash;
3617: my @courses_and_groups = @courses;
3618: push(@courses_and_groups,@groups);
3619: if (@courses_and_groups > 0) {
3620: my (%allgroups,%allroles);
3621: my ($start,$end,$role,$sec,$group);
3622: foreach my $envkey (%env) {
1.811 albertel 3623: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 3624: my $cid = $2.'_'.$3;
3625: if ($1 eq 'gr') {
3626: $group = $4;
3627: $allgroups{$cid}{$group} = $env{$envkey};
3628: } else {
3629: if ($4 eq '') {
3630: $sec = 'none';
3631: } else {
3632: $sec = $4;
3633: }
3634: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3635: }
1.811 albertel 3636: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 3637: my $cid = $2.'_'.$3;
3638: if ($4 eq '') {
3639: $sec = 'none';
3640: } else {
3641: $sec = $4;
3642: }
3643: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3644: }
3645: }
3646: if (keys(%allroles) == 0) {
3647: return;
3648: }
3649: foreach my $key (@courses_and_groups) {
3650: my %content = %{$$access_hash{$key}};
3651: my $cnum = $content{'number'};
3652: my $cdom = $content{'domain'};
3653: my $cid = $cdom.'_'.$cnum;
3654: if (!exists($allroles{$cid})) {
3655: next;
3656: }
3657: foreach my $role_id (keys(%{$content{'roles'}})) {
3658: my @sections = @{$content{'roles'}{$role_id}{'section'}};
3659: my @groups = @{$content{'roles'}{$role_id}{'group'}};
3660: my @status = @{$content{'roles'}{$role_id}{'access'}};
3661: my @roles = @{$content{'roles'}{$role_id}{'role'}};
3662: foreach my $role (keys(%{$allroles{$cid}})) {
3663: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
3664: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
3665: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
3666: if (grep/^all$/,@sections) {
3667: return 'ok';
3668: } else {
3669: if (grep/^$sec$/,@sections) {
3670: return 'ok';
3671: }
3672: }
3673: }
3674: }
3675: if (keys(%{$allgroups{$cid}}) == 0) {
3676: if (grep/^none$/,@groups) {
3677: return 'ok';
3678: }
3679: } else {
3680: if (grep/^all$/,@groups) {
3681: return 'ok';
3682: }
3683: foreach my $group (keys(%{$allgroups{$cid}})) {
3684: if (grep/^$group$/,@groups) {
3685: return 'ok';
3686: }
3687: }
3688: }
3689: }
3690: }
3691: }
3692: }
3693: }
3694: if ($guest) {
3695: return $guest;
3696: }
3697: }
3698: }
3699: return;
3700: }
3701:
3702: sub course_group_datechecker {
3703: my ($dates,$now,$status) = @_;
3704: my ($start,$end) = split(/\./,$dates);
3705: if (!$start && !$end) {
3706: return 'ok';
3707: }
3708: if (grep/^active$/,@{$status}) {
3709: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
3710: return 'ok';
3711: }
3712: }
3713: if (grep/^previous$/,@{$status}) {
3714: if ($end > $now ) {
3715: return 'ok';
3716: }
3717: }
3718: if (grep/^future$/,@{$status}) {
3719: if ($start > $now) {
3720: return 'ok';
3721: }
3722: }
3723: return;
3724: }
3725:
3726: sub parse_portfolio_url {
3727: my ($url) = @_;
3728:
3729: my ($type,$udom,$unum,$group,$file_name);
3730:
1.823 albertel 3731: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 3732: $type = 1;
3733: $udom = $1;
3734: $unum = $2;
3735: $file_name = $3;
1.823 albertel 3736: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 3737: $type = 2;
3738: $udom = $1;
3739: $unum = $2;
3740: $group = $3;
3741: $file_name = $3.'/'.$4;
3742: }
3743: if (wantarray) {
3744: return ($type,$udom,$unum,$file_name,$group);
3745: }
3746: return $type;
3747: }
3748:
3749: sub is_portfolio_url {
3750: my ($url) = @_;
3751: return scalar(&parse_portfolio_url($url));
3752: }
3753:
1.798 raeburn 3754: sub is_portfolio_file {
3755: my ($file) = @_;
1.820 raeburn 3756: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 3757: return 1;
3758: }
3759: return;
3760: }
3761:
3762:
1.341 www 3763: # ---------------------------------------------- Custom access rule evaluation
3764:
3765: sub customaccess {
3766: my ($priv,$uri)=@_;
1.807 albertel 3767: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 3768: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 3769: $udom = &LONCAPA::clean_domain($udom);
3770: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 3771: my $access=0;
1.800 albertel 3772: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
3773: my ($effect,$realm,$role)=split(/\:/,$right);
1.343 www 3774: if ($role) {
3775: if ($role ne $urole) { next; }
3776: }
1.800 albertel 3777: foreach my $scope (split(/\s*\,\s*/,$realm)) {
3778: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343 www 3779: if ($tdom) {
3780: if ($tdom ne $udom) { next; }
3781: }
3782: if ($tcrs) {
3783: if ($tcrs ne $ucrs) { next; }
3784: }
3785: if ($tsec) {
3786: if ($tsec ne $usec) { next; }
3787: }
3788: $access=($effect eq 'allow');
3789: last;
1.342 www 3790: }
1.402 bowersj2 3791: if ($realm eq '' && $role eq '') {
3792: $access=($effect eq 'allow');
3793: }
1.341 www 3794: }
3795: return $access;
3796: }
3797:
1.103 harris41 3798: # ------------------------------------------------- Check for a user privilege
1.12 www 3799:
3800: sub allowed {
1.810 raeburn 3801: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 3802: my $ver_orguri=$uri;
1.439 www 3803: $uri=&deversion($uri);
1.152 www 3804: my $orguri=$uri;
1.52 www 3805: $uri=&declutter($uri);
1.809 raeburn 3806:
1.810 raeburn 3807: if ($priv eq 'evb') {
3808: # Evade communication block restrictions for specified role in a course
3809: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
3810: return $1;
3811: } else {
3812: return;
3813: }
3814: }
3815:
1.620 albertel 3816: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 3817: # Free bre access to adm and meta resources
1.775 albertel 3818: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 3819: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
3820: && ($priv eq 'bre')) {
1.14 www 3821: return 'F';
1.159 www 3822: }
3823:
1.545 banghart 3824: # Free bre access to user's own portfolio contents
1.714 raeburn 3825: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 3826: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 3827: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 3828: my %setters;
3829: my ($startblock,$endblock) =
3830: &Apache::loncommon::blockcheck(\%setters,'port');
3831: if ($startblock && $endblock) {
3832: return 'B';
3833: } else {
3834: return 'F';
3835: }
1.545 banghart 3836: }
3837:
1.762 raeburn 3838: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 3839: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
3840: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
3841: if (exists($env{'request.course.id'})) {
3842: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3843: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3844: if (($domain eq $cdom) && ($name eq $cnum)) {
3845: my $courseprivid=$env{'request.course.id'};
3846: $courseprivid=~s/\_/\//;
3847: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
3848: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
3849: return $1;
1.762 raeburn 3850: } else {
3851: if ($env{'request.course.sec'}) {
3852: $courseprivid.='/'.$env{'request.course.sec'};
3853: }
3854: if ($env{'user.priv.'.$env{'request.role'}.'./'.
3855: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
3856: return $2;
3857: }
1.714 raeburn 3858: }
3859: }
3860: }
3861: }
3862:
1.159 www 3863: # Free bre to public access
3864:
3865: if ($priv eq 'bre') {
1.238 www 3866: my $copyright=&metadata($uri,'copyright');
1.620 albertel 3867: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 3868: return 'F';
3869: }
1.238 www 3870: if ($copyright eq 'priv') {
3871: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 3872: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 3873: return '';
3874: }
3875: }
3876: if ($copyright eq 'domain') {
3877: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 3878: unless (($env{'user.domain'} eq $1) ||
3879: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 3880: return '';
3881: }
1.262 matthew 3882: }
1.620 albertel 3883: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 3884: # Library role, so allow browsing of resources in this domain.
3885: return 'F';
1.238 www 3886: }
1.341 www 3887: if ($copyright eq 'custom') {
3888: unless (&customaccess($priv,$uri)) { return ''; }
3889: }
1.14 www 3890: }
1.264 matthew 3891: # Domain coordinator is trying to create a course
1.620 albertel 3892: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 3893: # uri is the requested domain in this case.
3894: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 3895: # a role of dc for the domain in question.
1.620 albertel 3896: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 3897: }
1.29 www 3898:
1.52 www 3899: my $thisallowed='';
3900: my $statecond=0;
3901: my $courseprivid='';
3902:
3903: # Course
3904:
1.620 albertel 3905: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 3906: $thisallowed.=$1;
3907: }
1.29 www 3908:
1.52 www 3909: # Domain
3910:
1.620 albertel 3911: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 3912: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 3913: $thisallowed.=$1;
3914: }
1.52 www 3915:
3916: # Course: uri itself is a course
1.66 www 3917: my $courseuri=$uri;
3918: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 3919: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 3920:
1.620 albertel 3921: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 3922: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 3923: $thisallowed.=$1;
3924: }
1.29 www 3925:
1.665 albertel 3926: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 3927: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 3928: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 3929: $thisallowed='';
1.671 raeburn 3930: my ($match)=&is_on_map($uri);
3931: if ($match) {
3932: if ($env{'user.priv.'.$env{'request.role'}.'./'}
3933: =~/\Q$priv\E\&([^\:]*)/) {
3934: $thisallowed.=$1;
3935: }
3936: } else {
1.705 albertel 3937: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 3938: if ($refuri) {
3939: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 3940: $thisallowed='F';
1.671 raeburn 3941: } else {
3942: $refuri=&declutter($refuri);
3943: my ($match) = &is_on_map($refuri);
3944: if ($match) {
3945: $thisallowed='F';
3946: }
1.669 raeburn 3947: }
1.671 raeburn 3948: }
3949: }
1.314 www 3950: }
1.492 albertel 3951:
1.766 albertel 3952: if ($priv eq 'bre'
3953: && $thisallowed ne 'F'
3954: && $thisallowed ne '2'
3955: && &is_portfolio_url($uri)) {
3956: $thisallowed = &portfolio_access($uri);
3957: }
3958:
1.52 www 3959: # Full access at system, domain or course-wide level? Exit.
1.29 www 3960:
3961: if ($thisallowed=~/F/) {
3962: return 'F';
3963: }
3964:
1.52 www 3965: # If this is generating or modifying users, exit with special codes
1.29 www 3966:
1.643 www 3967: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
3968: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 3969: my ($audom,$auname)=split('/',$uri);
1.643 www 3970: # no author name given, so this just checks on the general right to make a co-author in this domain
3971: unless ($auname) { return $thisallowed; }
3972: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 3973: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
3974: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
3975: ($audom ne $env{'request.role.domain'}))) { return ''; }
3976: }
1.52 www 3977: return $thisallowed;
3978: }
3979: #
1.103 harris41 3980: # Gathered so far: system, domain and course wide privileges
1.52 www 3981: #
3982: # Course: See if uri or referer is an individual resource that is part of
3983: # the course
3984:
1.620 albertel 3985: if ($env{'request.course.id'}) {
1.232 www 3986:
1.620 albertel 3987: $courseprivid=$env{'request.course.id'};
3988: if ($env{'request.course.sec'}) {
3989: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 3990: }
3991: $courseprivid=~s/\_/\//;
3992: my $checkreferer=1;
1.232 www 3993: my ($match,$cond)=&is_on_map($uri);
3994: if ($match) {
3995: $statecond=$cond;
1.620 albertel 3996: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 3997: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 3998: $thisallowed.=$1;
3999: $checkreferer=0;
4000: }
1.29 www 4001: }
1.83 www 4002:
1.148 www 4003: if ($checkreferer) {
1.620 albertel 4004: my $refuri=$env{'httpref.'.$orguri};
1.148 www 4005: unless ($refuri) {
1.800 albertel 4006: foreach my $key (keys(%env)) {
4007: if ($key=~/^httpref\..*\*/) {
4008: my $pattern=$key;
1.156 www 4009: $pattern=~s/^httpref\.\/res\///;
1.148 www 4010: $pattern=~s/\*/\[\^\/\]\+/g;
4011: $pattern=~s/\//\\\//g;
1.152 www 4012: if ($orguri=~/$pattern/) {
1.800 albertel 4013: $refuri=$env{$key};
1.148 www 4014: }
4015: }
1.191 harris41 4016: }
1.148 www 4017: }
1.232 www 4018:
1.148 www 4019: if ($refuri) {
1.152 www 4020: $refuri=&declutter($refuri);
1.232 www 4021: my ($match,$cond)=&is_on_map($refuri);
4022: if ($match) {
4023: my $refstatecond=$cond;
1.620 albertel 4024: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4025: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4026: $thisallowed.=$1;
1.53 www 4027: $uri=$refuri;
4028: $statecond=$refstatecond;
1.52 www 4029: }
4030: }
1.148 www 4031: }
1.29 www 4032: }
1.52 www 4033: }
1.29 www 4034:
1.52 www 4035: #
1.103 harris41 4036: # Gathered now: all privileges that could apply, and condition number
1.52 www 4037: #
4038: #
4039: # Full or no access?
4040: #
1.29 www 4041:
1.52 www 4042: if ($thisallowed=~/F/) {
4043: return 'F';
4044: }
1.29 www 4045:
1.52 www 4046: unless ($thisallowed) {
4047: return '';
4048: }
1.29 www 4049:
1.52 www 4050: # Restrictions exist, deal with them
4051: #
4052: # C:according to course preferences
4053: # R:according to resource settings
4054: # L:unless locked
4055: # X:according to user session state
4056: #
4057:
4058: # Possibly locked functionality, check all courses
1.54 www 4059: # Locks might take effect only after 10 minutes cache expiration for other
4060: # courses, and 2 minutes for current course
1.52 www 4061:
4062: my $envkey;
4063: if ($thisallowed=~/L/) {
1.620 albertel 4064: foreach $envkey (keys %env) {
1.54 www 4065: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
4066: my $courseid=$2;
4067: my $roleid=$1.'.'.$2;
1.92 www 4068: $courseid=~s/^\///;
1.54 www 4069: my $expiretime=600;
1.620 albertel 4070: if ($env{'request.role'} eq $roleid) {
1.54 www 4071: $expiretime=120;
4072: }
4073: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
4074: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 4075: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 4076: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 4077: }
1.620 albertel 4078: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
4079: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
4080: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
4081: &log($env{'user.domain'},$env{'user.name'},
4082: $env{'user.home'},
1.57 www 4083: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 4084: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4085: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4086: return '';
4087: }
4088: }
1.620 albertel 4089: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
4090: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
4091: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
4092: &log($env{'user.domain'},$env{'user.name'},
4093: $env{'user.home'},
1.57 www 4094: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 4095: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4096: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4097: return '';
4098: }
4099: }
4100: }
1.29 www 4101: }
1.52 www 4102: }
4103:
4104: #
4105: # Rest of the restrictions depend on selected course
4106: #
4107:
1.620 albertel 4108: unless ($env{'request.course.id'}) {
1.766 albertel 4109: if ($thisallowed eq 'A') {
4110: return 'A';
1.814 raeburn 4111: } elsif ($thisallowed eq 'B') {
4112: return 'B';
1.766 albertel 4113: } else {
4114: return '1';
4115: }
1.52 www 4116: }
1.29 www 4117:
1.52 www 4118: #
4119: # Now user is definitely in a course
4120: #
1.53 www 4121:
4122:
4123: # Course preferences
4124:
4125: if ($thisallowed=~/C/) {
1.620 albertel 4126: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4127: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
4128: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 4129: =~/\Q$rolecode\E/) {
1.689 albertel 4130: if ($priv ne 'pch') {
4131: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4132: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
4133: $env{'request.course.id'});
4134: }
1.237 www 4135: return '';
4136: }
4137:
1.620 albertel 4138: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 4139: =~/\Q$unamedom\E/) {
1.689 albertel 4140: if ($priv ne 'pch') {
4141: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
4142: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
4143: $env{'request.course.id'});
4144: }
1.54 www 4145: return '';
4146: }
1.53 www 4147: }
4148:
4149: # Resource preferences
4150:
4151: if ($thisallowed=~/R/) {
1.620 albertel 4152: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 4153: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 4154: if ($priv ne 'pch') {
4155: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4156: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
4157: }
4158: return '';
1.54 www 4159: }
1.53 www 4160: }
1.30 www 4161:
1.246 www 4162: # Restricted by state or randomout?
1.30 www 4163:
1.52 www 4164: if ($thisallowed=~/X/) {
1.620 albertel 4165: if ($env{'acc.randomout'}) {
1.579 albertel 4166: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 4167: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 4168: return '';
4169: }
1.247 www 4170: }
4171: if (&condval($statecond)) {
1.52 www 4172: return '2';
4173: } else {
4174: return '';
4175: }
4176: }
1.30 www 4177:
1.766 albertel 4178: if ($thisallowed eq 'A') {
4179: return 'A';
1.814 raeburn 4180: } elsif ($thisallowed eq 'B') {
4181: return 'B';
1.766 albertel 4182: }
1.52 www 4183: return 'F';
1.232 www 4184: }
4185:
1.710 albertel 4186: sub split_uri_for_cond {
4187: my $uri=&deversion(&declutter(shift));
4188: my @uriparts=split(/\//,$uri);
4189: my $filename=pop(@uriparts);
4190: my $pathname=join('/',@uriparts);
4191: return ($pathname,$filename);
4192: }
1.232 www 4193: # --------------------------------------------------- Is a resource on the map?
4194:
4195: sub is_on_map {
1.710 albertel 4196: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 4197: #Trying to find the conditional for the file
1.620 albertel 4198: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 4199: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 4200: if ($match) {
1.289 bowersj2 4201: return (1,$1);
4202: } else {
1.434 www 4203: return (0,0);
1.289 bowersj2 4204: }
1.12 www 4205: }
4206:
1.427 www 4207: # --------------------------------------------------------- Get symb from alias
4208:
4209: sub get_symb_from_alias {
4210: my $symb=shift;
4211: my ($map,$resid,$url)=&decode_symb($symb);
4212: # Already is a symb
4213: if ($url) { return $symb; }
4214: # Must be an alias
4215: my $aliassymb='';
4216: my %bighash;
1.620 albertel 4217: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 4218: &GDBM_READER(),0640)) {
4219: my $rid=$bighash{'mapalias_'.$symb};
4220: if ($rid) {
4221: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 4222: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
4223: $resid,$bighash{'src_'.$rid});
1.427 www 4224: }
4225: untie %bighash;
4226: }
4227: return $aliassymb;
4228: }
4229:
1.12 www 4230: # ----------------------------------------------------------------- Define Role
4231:
4232: sub definerole {
4233: if (allowed('mcr','/')) {
4234: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 4235: foreach my $role (split(':',$sysrole)) {
4236: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4237: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
4238: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
4239: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4240: return "refused:s:$crole&$cqual";
4241: }
4242: }
1.191 harris41 4243: }
1.800 albertel 4244: foreach my $role (split(':',$domrole)) {
4245: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4246: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
4247: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
4248: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 4249: return "refused:d:$crole&$cqual";
4250: }
4251: }
1.191 harris41 4252: }
1.800 albertel 4253: foreach my $role (split(':',$courole)) {
4254: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4255: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
4256: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
4257: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4258: return "refused:c:$crole&$cqual";
4259: }
4260: }
1.191 harris41 4261: }
1.620 albertel 4262: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4263: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 4264: "rolesdef_$rolename=".
4265: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 4266: return reply($command,$env{'user.home'});
1.12 www 4267: } else {
4268: return 'refused';
4269: }
1.105 harris41 4270: }
4271:
4272: # ---------------- Make a metadata query against the network of library servers
4273:
4274: sub metadata_query {
1.244 matthew 4275: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 4276: my %rhash;
1.845 albertel 4277: my %libserv = &all_library();
1.244 matthew 4278: my @server_list = (defined($server_array) ? @$server_array
4279: : keys(%libserv) );
4280: for my $server (@server_list) {
1.118 harris41 4281: unless ($custom or $customshow) {
4282: my $reply=&reply("querysend:".&escape($query),$server);
4283: $rhash{$server}=$reply;
4284: }
4285: else {
4286: my $reply=&reply("querysend:".&escape($query).':'.
4287: &escape($custom).':'.&escape($customshow),
4288: $server);
4289: $rhash{$server}=$reply;
4290: }
1.112 harris41 4291: }
1.118 harris41 4292: return \%rhash;
1.240 www 4293: }
4294:
4295: # ----------------------------------------- Send log queries and wait for reply
4296:
4297: sub log_query {
4298: my ($uname,$udom,$query,%filters)=@_;
4299: my $uhome=&homeserver($uname,$udom);
4300: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 4301: my $uhost=&hostname($uhome);
1.800 albertel 4302: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 4303: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
4304: $uhome);
1.479 albertel 4305: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 4306: return get_query_reply($queryid);
4307: }
4308:
1.818 raeburn 4309: # -------------------------- Update MySQL table for portfolio file
4310:
4311: sub update_portfolio_table {
1.821 raeburn 4312: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818 raeburn 4313: my $homeserver = &homeserver($uname,$udom);
4314: my $queryid=
1.821 raeburn 4315: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
4316: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 4317: my $reply = &get_query_reply($queryid);
4318: return $reply;
4319: }
4320:
1.508 raeburn 4321: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 4322:
4323: sub fetch_enrollment_query {
1.511 raeburn 4324: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 4325: my $homeserver;
1.547 raeburn 4326: my $maxtries = 1;
1.508 raeburn 4327: if ($context eq 'automated') {
4328: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 4329: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 4330: } else {
4331: $homeserver = &homeserver($cnum,$dom);
4332: }
1.838 albertel 4333: my $host=&hostname($homeserver);
1.506 raeburn 4334: my $cmd = '';
1.800 albertel 4335: foreach my $affiliate (keys %{$affiliatesref}) {
4336: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 4337: }
4338: $cmd =~ s/%%$//;
4339: $cmd = &escape($cmd);
4340: my $query = 'fetchenrollment';
1.620 albertel 4341: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 4342: unless ($queryid=~/^\Q$host\E\_/) {
4343: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
4344: return 'error: '.$queryid;
4345: }
1.506 raeburn 4346: my $reply = &get_query_reply($queryid);
1.547 raeburn 4347: my $tries = 1;
4348: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4349: $reply = &get_query_reply($queryid);
4350: $tries ++;
4351: }
1.526 raeburn 4352: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 4353: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 4354: } else {
1.515 raeburn 4355: my @responses = split/:/,$reply;
4356: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 4357: foreach my $line (@responses) {
4358: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 4359: $$replyref{$key} = $value;
4360: }
4361: } else {
1.506 raeburn 4362: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 4363: foreach my $line (@responses) {
4364: my ($key,$value) = split(/=/,$line);
1.506 raeburn 4365: $$replyref{$key} = $value;
4366: if ($value > 0) {
1.800 albertel 4367: foreach my $item (@{$$affiliatesref{$key}}) {
4368: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 4369: my $destname = $pathname.'/'.$filename;
4370: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 4371: if ($xml_classlist =~ /^error/) {
4372: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
4373: } else {
1.506 raeburn 4374: if ( open(FILE,">$destname") ) {
4375: print FILE &unescape($xml_classlist);
4376: close(FILE);
1.526 raeburn 4377: } else {
4378: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 4379: }
4380: }
4381: }
4382: }
4383: }
4384: }
4385: return 'ok';
4386: }
4387: return 'error';
4388: }
4389:
1.242 www 4390: sub get_query_reply {
4391: my $queryid=shift;
1.240 www 4392: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
4393: my $reply='';
4394: for (1..100) {
4395: sleep 2;
4396: if (-e $replyfile.'.end') {
1.448 albertel 4397: if (open(my $fh,$replyfile)) {
1.240 www 4398: $reply.=<$fh>;
1.448 albertel 4399: close($fh);
1.240 www 4400: } else { return 'error: reply_file_error'; }
1.242 www 4401: return &unescape($reply);
4402: }
1.240 www 4403: }
1.242 www 4404: return 'timeout:'.$queryid;
1.240 www 4405: }
4406:
4407: sub courselog_query {
1.241 www 4408: #
4409: # possible filters:
4410: # url: url or symb
4411: # username
4412: # domain
4413: # action: view, submit, grade
4414: # start: timestamp
4415: # end: timestamp
4416: #
1.240 www 4417: my (%filters)=@_;
1.620 albertel 4418: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 4419: if ($filters{'url'}) {
4420: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
4421: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
4422: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
4423: }
1.620 albertel 4424: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4425: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 4426: return &log_query($cname,$cdom,'courselog',%filters);
4427: }
4428:
4429: sub userlog_query {
1.858 raeburn 4430: #
4431: # possible filters:
4432: # action: log check role
4433: # start: timestamp
4434: # end: timestamp
4435: #
1.240 www 4436: my ($uname,$udom,%filters)=@_;
4437: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 4438: }
4439:
1.506 raeburn 4440: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
4441:
4442: sub auto_run {
1.508 raeburn 4443: my ($cnum,$cdom) = @_;
4444: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 4445: my $response = &reply('autorun:'.$cdom,$homeserver);
1.506 raeburn 4446: return $response;
4447: }
1.776 albertel 4448:
1.506 raeburn 4449: sub auto_get_sections {
1.508 raeburn 4450: my ($cnum,$cdom,$inst_coursecode) = @_;
4451: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 4452: my @secs = ();
1.511 raeburn 4453: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 4454: unless ($response eq 'refused') {
4455: @secs = split/:/,$response;
4456: }
4457: return @secs;
4458: }
1.776 albertel 4459:
1.506 raeburn 4460: sub auto_new_course {
1.508 raeburn 4461: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
4462: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 4463: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 4464: return $response;
4465: }
1.776 albertel 4466:
1.506 raeburn 4467: sub auto_validate_courseID {
1.508 raeburn 4468: my ($cnum,$cdom,$inst_course_id) = @_;
4469: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 4470: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 4471: return $response;
4472: }
1.776 albertel 4473:
1.506 raeburn 4474: sub auto_create_password {
1.508 raeburn 4475: my ($cnum,$cdom,$authparam) = @_;
4476: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 4477: my $create_passwd = 0;
4478: my $authchk = '';
1.511 raeburn 4479: my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506 raeburn 4480: if ($response eq 'refused') {
4481: $authchk = 'refused';
4482: } else {
4483: ($authparam,$create_passwd,$authchk) = split/:/,$response;
4484: }
4485: return ($authparam,$create_passwd,$authchk);
4486: }
4487:
1.706 raeburn 4488: sub auto_photo_permission {
4489: my ($cnum,$cdom,$students) = @_;
4490: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 4491: my ($outcome,$perm_reqd,$conditions) =
4492: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 4493: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4494: return (undef,undef);
4495: }
1.706 raeburn 4496: return ($outcome,$perm_reqd,$conditions);
4497: }
4498:
4499: sub auto_checkphotos {
4500: my ($uname,$udom,$pid) = @_;
4501: my $homeserver = &homeserver($uname,$udom);
4502: my ($result,$resulttype);
4503: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 4504: &escape($uname).':'.&escape($pid),
4505: $homeserver));
1.709 albertel 4506: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4507: return (undef,undef);
4508: }
1.706 raeburn 4509: if ($outcome) {
4510: ($result,$resulttype) = split(/:/,$outcome);
4511: }
4512: return ($result,$resulttype);
4513: }
4514:
4515: sub auto_photochoice {
4516: my ($cnum,$cdom) = @_;
4517: my $homeserver = &homeserver($cnum,$cdom);
4518: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 4519: &escape($cdom),
4520: $homeserver)));
1.709 albertel 4521: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4522: return (undef,undef);
4523: }
1.706 raeburn 4524: return ($update,$comment);
4525: }
4526:
4527: sub auto_photoupdate {
4528: my ($affiliatesref,$dom,$cnum,$photo) = @_;
4529: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 4530: my $host=&hostname($homeserver);
1.706 raeburn 4531: my $cmd = '';
4532: my $maxtries = 1;
1.800 albertel 4533: foreach my $affiliate (keys(%{$affiliatesref})) {
4534: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 4535: }
4536: $cmd =~ s/%%$//;
4537: $cmd = &escape($cmd);
4538: my $query = 'institutionalphotos';
4539: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
4540: unless ($queryid=~/^\Q$host\E\_/) {
4541: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
4542: return 'error: '.$queryid;
4543: }
4544: my $reply = &get_query_reply($queryid);
4545: my $tries = 1;
4546: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4547: $reply = &get_query_reply($queryid);
4548: $tries ++;
4549: }
4550: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
4551: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
4552: } else {
4553: my @responses = split(/:/,$reply);
4554: my $outcome = shift(@responses);
4555: foreach my $item (@responses) {
4556: my ($key,$value) = split(/=/,$item);
4557: $$photo{$key} = $value;
4558: }
4559: return $outcome;
4560: }
4561: return 'error';
4562: }
4563:
1.521 raeburn 4564: sub auto_instcode_format {
1.793 albertel 4565: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
4566: $cat_order) = @_;
1.521 raeburn 4567: my $courses = '';
1.772 raeburn 4568: my @homeservers;
1.521 raeburn 4569: if ($caller eq 'global') {
1.841 albertel 4570: my %servers = &get_servers($codedom,'library');
4571: foreach my $tryserver (keys(%servers)) {
4572: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4573: push(@homeservers,$tryserver);
4574: }
1.584 raeburn 4575: }
1.521 raeburn 4576: } else {
1.772 raeburn 4577: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 4578: }
1.793 albertel 4579: foreach my $code (keys(%{$instcodes})) {
4580: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 4581: }
4582: chop($courses);
1.772 raeburn 4583: my $ok_response = 0;
4584: my $response;
4585: while (@homeservers > 0 && $ok_response == 0) {
4586: my $server = shift(@homeservers);
4587: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
4588: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
4589: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.793 albertel 4590: split/:/,$response;
1.772 raeburn 4591: %{$codes} = (%{$codes},&str2hash($codes_str));
4592: push(@{$codetitles},&str2array($codetitles_str));
4593: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
4594: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
4595: $ok_response = 1;
4596: }
4597: }
4598: if ($ok_response) {
1.521 raeburn 4599: return 'ok';
1.772 raeburn 4600: } else {
4601: return $response;
1.521 raeburn 4602: }
4603: }
4604:
1.792 raeburn 4605: sub auto_instcode_defaults {
4606: my ($domain,$returnhash,$code_order) = @_;
4607: my @homeservers;
1.841 albertel 4608:
4609: my %servers = &get_servers($domain,'library');
4610: foreach my $tryserver (keys(%servers)) {
4611: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4612: push(@homeservers,$tryserver);
4613: }
1.792 raeburn 4614: }
1.841 albertel 4615:
1.792 raeburn 4616: my $response;
1.841 albertel 4617: foreach my $server (@homeservers) {
1.792 raeburn 4618: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 4619: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
4620:
4621: foreach my $pair (split(/\&/,$response)) {
4622: my ($name,$value)=split(/\=/,$pair);
4623: if ($name eq 'code_order') {
4624: @{$code_order} = split(/\&/,&unescape($value));
4625: } else {
4626: $returnhash->{&unescape($name)}=&unescape($value);
4627: }
4628: }
4629: return 'ok';
1.792 raeburn 4630: }
1.841 albertel 4631:
4632: return $response;
1.792 raeburn 4633: }
4634:
1.777 albertel 4635: sub auto_validate_class_sec {
1.773 raeburn 4636: my ($cdom,$cnum,$owner,$inst_class) = @_;
4637: my $homeserver = &homeserver($cnum,$cdom);
4638: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774 banghart 4639: &escape($owner).':'.$cdom,$homeserver);
1.773 raeburn 4640: return $response;
4641: }
4642:
1.679 raeburn 4643: # ------------------------------------------------------- Course Group routines
4644:
4645: sub get_coursegroups {
1.809 raeburn 4646: my ($cdom,$cnum,$group,$namespace) = @_;
4647: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 4648: }
4649:
1.679 raeburn 4650: sub modify_coursegroup {
4651: my ($cdom,$cnum,$groupsettings) = @_;
4652: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
4653: }
4654:
1.809 raeburn 4655: sub toggle_coursegroup_status {
4656: my ($cdom,$cnum,$group,$action) = @_;
4657: my ($from_namespace,$to_namespace);
4658: if ($action eq 'delete') {
4659: $from_namespace = 'coursegroups';
4660: $to_namespace = 'deleted_groups';
4661: } else {
4662: $from_namespace = 'deleted_groups';
4663: $to_namespace = 'coursegroups';
4664: }
4665: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 4666: if (my $tmp = &error(%curr_group)) {
4667: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
4668: return ('read error',$tmp);
4669: } else {
4670: my %savedsettings = %curr_group;
1.809 raeburn 4671: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 4672: my $deloutcome;
4673: if ($result eq 'ok') {
1.809 raeburn 4674: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 4675: } else {
4676: return ('write error',$result);
4677: }
4678: if ($deloutcome eq 'ok') {
4679: return 'ok';
4680: } else {
4681: return ('delete error',$deloutcome);
4682: }
4683: }
4684: }
4685:
1.679 raeburn 4686: sub modify_group_roles {
4687: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
4688: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
4689: my $role = 'gr/'.&escape($userprivs);
4690: my ($uname,$udom) = split(/:/,$user);
4691: my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684 raeburn 4692: if ($result eq 'ok') {
4693: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
4694: }
1.679 raeburn 4695: return $result;
4696: }
4697:
4698: sub modify_coursegroup_membership {
4699: my ($cdom,$cnum,$membership) = @_;
4700: my $result = &put('groupmembership',$membership,$cdom,$cnum);
4701: return $result;
4702: }
4703:
1.682 raeburn 4704: sub get_active_groups {
4705: my ($udom,$uname,$cdom,$cnum) = @_;
4706: my $now = time;
4707: my %groups = ();
4708: foreach my $key (keys(%env)) {
1.811 albertel 4709: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 4710: my ($start,$end) = split(/\./,$env{$key});
4711: if (($end!=0) && ($end<$now)) { next; }
4712: if (($start!=0) && ($start>$now)) { next; }
4713: if ($1 eq $cdom && $2 eq $cnum) {
4714: $groups{$3} = $env{$key} ;
4715: }
4716: }
4717: }
4718: return %groups;
4719: }
4720:
1.683 raeburn 4721: sub get_group_membership {
4722: my ($cdom,$cnum,$group) = @_;
4723: return(&dump('groupmembership',$cdom,$cnum,$group));
4724: }
4725:
4726: sub get_users_groups {
4727: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 4728: my @usersgroups;
1.683 raeburn 4729: my $cachetime=1800;
4730:
4731: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 4732: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
4733: if (defined($cached)) {
1.734 albertel 4734: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 4735: } else {
4736: $grouplist = '';
1.816 raeburn 4737: my $courseurl = &courseid_to_courseurl($courseid);
4738: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 4739: my $access_end = $env{'course.'.$courseid.
4740: '.default_enrollment_end_date'};
4741: my $now = time;
4742: foreach my $key (keys(%roleshash)) {
4743: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
4744: my $group = $1;
4745: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
4746: my $start = $2;
4747: my $end = $1;
4748: if ($start == -1) { next; } # deleted from group
4749: if (($start!=0) && ($start>$now)) { next; }
4750: if (($end!=0) && ($end<$now)) {
4751: if ($access_end && $access_end < $now) {
4752: if ($access_end - $end < 86400) {
4753: push(@usersgroups,$group);
1.733 raeburn 4754: }
4755: }
1.817 raeburn 4756: next;
1.733 raeburn 4757: }
1.817 raeburn 4758: push(@usersgroups,$group);
1.683 raeburn 4759: }
4760: }
4761: }
1.817 raeburn 4762: @usersgroups = &sort_course_groups($courseid,@usersgroups);
4763: $grouplist = join(':',@usersgroups);
4764: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 4765: }
1.733 raeburn 4766: return @usersgroups;
1.683 raeburn 4767: }
4768:
4769: sub devalidate_getgroups_cache {
4770: my ($udom,$uname,$cdom,$cnum)=@_;
4771: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 4772:
1.683 raeburn 4773: my $hashid="$udom:$uname:$courseid";
4774: &devalidate_cache_new('getgroups',$hashid);
4775: }
4776:
1.12 www 4777: # ------------------------------------------------------------------ Plain Text
4778:
4779: sub plaintext {
1.742 raeburn 4780: my ($short,$type,$cid) = @_;
1.758 albertel 4781: if ($short =~ /^cr/) {
4782: return (split('/',$short))[-1];
4783: }
1.742 raeburn 4784: if (!defined($cid)) {
4785: $cid = $env{'request.course.id'};
4786: }
4787: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
4788: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
4789: '.plaintext'});
4790: }
4791: my %rolenames = (
4792: Course => 'std',
4793: Group => 'alt1',
4794: );
4795: if (defined($type) &&
4796: defined($rolenames{$type}) &&
4797: defined($prp{$short}{$rolenames{$type}})) {
4798: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
4799: } else {
4800: return &Apache::lonlocal::mt($prp{$short}{'std'});
4801: }
1.12 www 4802: }
4803:
4804: # ----------------------------------------------------------------- Assign Role
4805:
4806: sub assignrole {
1.357 www 4807: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21 www 4808: my $mrole;
4809: if ($role =~ /^cr\//) {
1.393 www 4810: my $cwosec=$url;
1.811 albertel 4811: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 4812: unless (&allowed('ccr',$cwosec)) {
1.104 www 4813: &logthis('Refused custom assignrole: '.
4814: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 4815: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 4816: return 'refused';
4817: }
1.21 www 4818: $mrole='cr';
1.678 raeburn 4819: } elsif ($role =~ /^gr\//) {
4820: my $cwogrp=$url;
1.811 albertel 4821: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 4822: unless (&allowed('mdg',$cwogrp)) {
4823: &logthis('Refused group assignrole: '.
4824: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4825: $env{'user.name'}.' at '.$env{'user.domain'});
4826: return 'refused';
4827: }
4828: $mrole='gr';
1.21 www 4829: } else {
1.82 www 4830: my $cwosec=$url;
1.811 albertel 4831: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373 www 4832: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
1.104 www 4833: &logthis('Refused assignrole: '.
4834: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 4835: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 4836: return 'refused';
4837: }
1.21 www 4838: $mrole=$role;
4839: }
1.620 albertel 4840: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 4841: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 4842: if ($end) { $command.='_'.$end; }
1.21 www 4843: if ($start) {
4844: if ($end) {
1.81 www 4845: $command.='_'.$start;
1.21 www 4846: } else {
1.81 www 4847: $command.='_0_'.$start;
1.21 www 4848: }
4849: }
1.739 raeburn 4850: my $origstart = $start;
4851: my $origend = $end;
1.357 www 4852: # actually delete
4853: if ($deleteflag) {
1.373 www 4854: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 4855: # modify command to delete the role
1.620 albertel 4856: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 4857: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 4858: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 4859: # set start and finish to negative values for userrolelog
4860: $start=-1;
4861: $end=-1;
4862: }
4863: }
4864: # send command
1.349 www 4865: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 4866: # log new user role if status is ok
1.349 www 4867: if ($answer eq 'ok') {
1.663 raeburn 4868: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 4869: # for course roles, perform group memberships changes triggered by role change.
4870: unless ($role =~ /^gr/) {
4871: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
4872: $origstart);
4873: }
1.349 www 4874: }
4875: return $answer;
1.169 harris41 4876: }
4877:
4878: # -------------------------------------------------- Modify user authentication
1.197 www 4879: # Overrides without validation
4880:
1.169 harris41 4881: sub modifyuserauth {
4882: my ($udom,$uname,$umode,$upass)=@_;
4883: my $uhome=&homeserver($uname,$udom);
1.197 www 4884: unless (&allowed('mau',$udom)) { return 'refused'; }
4885: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 4886: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4887: ' in domain '.$env{'request.role.domain'});
1.169 harris41 4888: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
4889: &escape($upass),$uhome);
1.620 albertel 4890: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 4891: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
4892: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
4893: &log($udom,,$uname,$uhome,
1.620 albertel 4894: 'Authentication changed by '.$env{'user.domain'}.', '.
4895: $env{'user.name'}.', '.$umode.
1.197 www 4896: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 4897: unless ($reply eq 'ok') {
1.197 www 4898: &logthis('Authentication mode error: '.$reply);
1.169 harris41 4899: return 'error: '.$reply;
4900: }
1.170 harris41 4901: return 'ok';
1.80 www 4902: }
4903:
1.81 www 4904: # --------------------------------------------------------------- Modify a user
1.80 www 4905:
1.81 www 4906: sub modifyuser {
1.206 matthew 4907: my ($udom, $uname, $uid,
4908: $umode, $upass, $first,
4909: $middle, $last, $gene,
1.387 www 4910: $forceid, $desiredhome, $email)=@_;
1.807 albertel 4911: $udom= &LONCAPA::clean_domain($udom);
4912: $uname=&LONCAPA::clean_username($uname);
1.81 www 4913: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 4914: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 4915: $last.', '.$gene.'(forceid: '.$forceid.')'.
4916: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
4917: ' desiredhome not specified').
1.620 albertel 4918: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4919: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 4920: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 4921: # ----------------------------------------------------------------- Create User
1.406 albertel 4922: if (($uhome eq 'no_host') &&
4923: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 4924: my $unhome='';
1.844 albertel 4925: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 4926: $unhome = $desiredhome;
1.620 albertel 4927: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
4928: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 4929: } else { # load balancing routine for determining $unhome
1.81 www 4930: my $loadm=10000000;
1.841 albertel 4931: my %servers = &get_servers($udom,'library');
4932: foreach my $tryserver (keys(%servers)) {
4933: my $answer=reply('load',$tryserver);
4934: if (($answer=~/\d+/) && ($answer<$loadm)) {
4935: $loadm=$answer;
4936: $unhome=$tryserver;
4937: }
1.80 www 4938: }
4939: }
4940: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 4941: return 'error: unable to find a home server for '.$uname.
4942: ' in domain '.$udom;
1.80 www 4943: }
4944: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
4945: &escape($upass),$unhome);
4946: unless ($reply eq 'ok') {
4947: return 'error: '.$reply;
4948: }
1.230 stredwic 4949: $uhome=&homeserver($uname,$udom,'true');
1.80 www 4950: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 4951: return 'error: unable verify users home machine.';
1.80 www 4952: }
1.209 matthew 4953: } # End of creation of new user
1.80 www 4954: # ---------------------------------------------------------------------- Add ID
4955: if ($uid) {
4956: $uid=~tr/A-Z/a-z/;
4957: my %uidhash=&idrget($udom,$uname);
1.196 www 4958: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
4959: && (!$forceid)) {
1.80 www 4960: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 4961: return 'error: user id "'.$uid.'" does not match '.
4962: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 4963: }
4964: } else {
4965: &idput($udom,($uname => $uid));
4966: }
4967: }
4968: # -------------------------------------------------------------- Add names, etc
1.313 matthew 4969: my @tmp=&get('environment',
1.134 albertel 4970: ['firstname','middlename','lastname','generation'],
4971: $udom,$uname);
1.313 matthew 4972: my %names;
4973: if ($tmp[0] =~ m/^error:.*/) {
4974: %names=();
4975: } else {
4976: %names = @tmp;
4977: }
1.388 www 4978: #
4979: # Make sure to not trash student environment if instructor does not bother
4980: # to supply name and email information
4981: #
4982: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 4983: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 4984: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 4985: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 4986: if ($email) {
4987: $email=~s/[^\w\@\.\-\,]//gs;
4988: if ($email=~/\@/) { $names{'notification'} = $email;
4989: $names{'critnotification'} = $email;
4990: $names{'permanentemail'} = $email; }
4991: }
1.134 albertel 4992: my $reply = &put('environment', \%names, $udom,$uname);
4993: if ($reply ne 'ok') { return 'error: '.$reply; }
1.680 www 4994: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81 www 4995: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 4996: $umode.', '.$first.', '.$middle.', '.
4997: $last.', '.$gene.' by '.
1.620 albertel 4998: $env{'user.name'}.' at '.$env{'user.domain'});
1.134 albertel 4999: return 'ok';
1.80 www 5000: }
5001:
1.81 www 5002: # -------------------------------------------------------------- Modify student
1.80 www 5003:
1.81 www 5004: sub modifystudent {
5005: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515 raeburn 5006: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455 albertel 5007: if (!$cid) {
1.620 albertel 5008: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5009: return 'not_in_class';
5010: }
1.80 www 5011: }
5012: # --------------------------------------------------------------- Make the user
1.81 www 5013: my $reply=&modifyuser
1.209 matthew 5014: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 5015: $desiredhome,$email);
1.80 www 5016: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 5017: # This will cause &modify_student_enrollment to get the uid from the
5018: # students environment
5019: $uid = undef if (!$forceid);
1.455 albertel 5020: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515 raeburn 5021: $gene,$usec,$end,$start,$type,$locktype,$cid);
1.297 matthew 5022: return $reply;
5023: }
5024:
5025: sub modify_student_enrollment {
1.515 raeburn 5026: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455 albertel 5027: my ($cdom,$cnum,$chome);
5028: if (!$cid) {
1.620 albertel 5029: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5030: return 'not_in_class';
5031: }
1.620 albertel 5032: $cdom=$env{'course.'.$cid.'.domain'};
5033: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 5034: } else {
5035: ($cdom,$cnum)=split(/_/,$cid);
5036: }
1.620 albertel 5037: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 5038: if (!$chome) {
1.457 raeburn 5039: $chome=&homeserver($cnum,$cdom);
1.297 matthew 5040: }
1.455 albertel 5041: if (!$chome) { return 'unknown_course'; }
1.297 matthew 5042: # Make sure the user exists
1.81 www 5043: my $uhome=&homeserver($uname,$udom);
5044: if (($uhome eq '') || ($uhome eq 'no_host')) {
5045: return 'error: no such user';
5046: }
1.297 matthew 5047: # Get student data if we were not given enough information
5048: if (!defined($first) || $first eq '' ||
5049: !defined($last) || $last eq '' ||
5050: !defined($uid) || $uid eq '' ||
5051: !defined($middle) || $middle eq '' ||
5052: !defined($gene) || $gene eq '') {
1.294 matthew 5053: # They did not supply us with enough data to enroll the student, so
5054: # we need to pick up more information.
1.297 matthew 5055: my %tmp = &get('environment',
1.294 matthew 5056: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 5057: ,$udom,$uname);
5058:
1.800 albertel 5059: #foreach my $key (keys(%tmp)) {
5060: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 5061: #}
1.294 matthew 5062: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
5063: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
5064: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 5065: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 5066: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
5067: }
1.556 albertel 5068: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 5069: my $reply=cput('classlist',
5070: {"$uname:$udom" =>
1.515 raeburn 5071: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 5072: $cdom,$cnum);
1.81 www 5073: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
5074: return 'error: '.$reply;
1.652 albertel 5075: } else {
5076: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 5077: }
1.297 matthew 5078: # Add student role to user
1.83 www 5079: my $uurl='/'.$cid;
1.81 www 5080: $uurl=~s/\_/\//g;
5081: if ($usec) {
5082: $uurl.='/'.$usec;
5083: }
5084: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21 www 5085: }
5086:
1.556 albertel 5087: sub format_name {
5088: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
5089: my $name;
5090: if ($first ne 'lastname') {
5091: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
5092: } else {
5093: if ($lastname=~/\S/) {
5094: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
5095: $name=~s/\s+,/,/;
5096: } else {
5097: $name.= $firstname.' '.$middlename.' '.$generation;
5098: }
5099: }
5100: $name=~s/^\s+//;
5101: $name=~s/\s+$//;
5102: $name=~s/\s+/ /g;
5103: return $name;
5104: }
5105:
1.84 www 5106: # ------------------------------------------------- Write to course preferences
5107:
5108: sub writecoursepref {
5109: my ($courseid,%prefs)=@_;
5110: $courseid=~s/^\///;
5111: $courseid=~s/\_/\//g;
5112: my ($cdomain,$cnum)=split(/\//,$courseid);
5113: my $chome=homeserver($cnum,$cdomain);
5114: if (($chome eq '') || ($chome eq 'no_host')) {
5115: return 'error: no such course';
5116: }
5117: my $cstring='';
1.800 albertel 5118: foreach my $pref (keys(%prefs)) {
5119: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 5120: }
1.84 www 5121: $cstring=~s/\&$//;
5122: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
5123: }
5124:
5125: # ---------------------------------------------------------- Make/modify course
5126:
5127: sub createcourse {
1.741 raeburn 5128: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
5129: $course_owner,$crstype)=@_;
1.84 www 5130: $url=&declutter($url);
5131: my $cid='';
1.264 matthew 5132: unless (&allowed('ccc',$udom)) {
1.84 www 5133: return 'refused';
5134: }
5135: # ------------------------------------------------------------------- Create ID
1.674 www 5136: my $uname=int(1+rand(9)).
5137: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
5138: substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84 www 5139: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
5140: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 5141: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 5142: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5143: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
5144: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 5145: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5146: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5147: return 'error: unable to generate unique course-ID';
5148: }
5149: }
1.264 matthew 5150: # ------------------------------------------------ Check supplied server name
1.620 albertel 5151: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845 albertel 5152: if (! &is_library($course_server)) {
1.264 matthew 5153: return 'error:bad server name '.$course_server;
5154: }
1.84 www 5155: # ------------------------------------------------------------- Make the course
5156: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 5157: $course_server);
1.84 www 5158: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 5159: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5160: if (($uhome eq '') || ($uhome eq 'no_host')) {
5161: return 'error: no such course';
5162: }
1.271 www 5163: # ----------------------------------------------------------------- Course made
1.516 raeburn 5164: # log existence
5165: &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741 raeburn 5166: ':'.&escape($inst_code).':'.&escape($course_owner).':'.
5167: &escape($crstype),$uhome);
1.358 www 5168: &flushcourselogs();
5169: # set toplevel url
1.271 www 5170: my $topurl=$url;
5171: unless ($nonstandard) {
5172: # ------------------------------------------ For standard courses, make top url
5173: my $mapurl=&clutter($url);
1.278 www 5174: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 5175: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 5176: <map>
5177: <resource id="1" type="start"></resource>
5178: <resource id="2" src="$mapurl"></resource>
5179: <resource id="3" type="finish"></resource>
5180: <link index="1" from="1" to="2"></link>
5181: <link index="2" from="2" to="3"></link>
5182: </map>
5183: ENDINITMAP
5184: $topurl=&declutter(
1.638 albertel 5185: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 5186: );
5187: }
5188: # ----------------------------------------------------------- Write preferences
1.84 www 5189: &writecoursepref($udom.'_'.$uname,
5190: ('description' => $description,
1.271 www 5191: 'url' => $topurl));
1.84 www 5192: return '/'.$udom.'/'.$uname;
5193: }
5194:
1.813 albertel 5195: sub is_course {
5196: my ($cdom,$cnum) = @_;
5197: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
5198: undef,'.');
5199: if (exists($courses{$cdom.'_'.$cnum})) {
5200: return 1;
5201: }
5202: return 0;
5203: }
5204:
1.21 www 5205: # ---------------------------------------------------------- Assign Custom Role
5206:
5207: sub assigncustomrole {
1.357 www 5208: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21 www 5209: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357 www 5210: $end,$start,$deleteflag);
1.21 www 5211: }
5212:
5213: # ----------------------------------------------------------------- Revoke Role
5214:
5215: sub revokerole {
1.357 www 5216: my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21 www 5217: my $now=time;
1.357 www 5218: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21 www 5219: }
5220:
5221: # ---------------------------------------------------------- Revoke Custom Role
5222:
5223: sub revokecustomrole {
1.357 www 5224: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21 www 5225: my $now=time;
1.357 www 5226: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
5227: $deleteflag);
1.17 www 5228: }
5229:
1.533 banghart 5230: # ------------------------------------------------------------ Disk usage
1.535 albertel 5231: sub diskusage {
1.533 banghart 5232: my ($udom,$uname,$directoryRoot)=@_;
5233: $directoryRoot =~ s/\/$//;
1.535 albertel 5234: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514 albertel 5235: return $listing;
1.512 banghart 5236: }
5237:
1.566 banghart 5238: sub is_locked {
5239: my ($file_name, $domain, $user) = @_;
5240: my @check;
5241: my $is_locked;
5242: push @check, $file_name;
1.613 albertel 5243: my %locked = &get('file_permissions',\@check,
1.620 albertel 5244: $env{'user.domain'},$env{'user.name'});
1.615 albertel 5245: my ($tmp)=keys(%locked);
5246: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 5247:
1.566 banghart 5248: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 5249: $is_locked = 'false';
5250: foreach my $entry (@{$locked{$file_name}}) {
5251: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 5252: $is_locked = 'true';
5253: last;
1.745 raeburn 5254: }
5255: }
1.566 banghart 5256: } else {
5257: $is_locked = 'false';
5258: }
5259: }
5260:
1.759 albertel 5261: sub declutter_portfile {
5262: my ($file) = @_;
1.833 albertel 5263: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 5264: return $file;
5265: }
5266:
1.559 banghart 5267: # ------------------------------------------------------------- Mark as Read Only
5268:
5269: sub mark_as_readonly {
5270: my ($domain,$user,$files,$what) = @_;
1.613 albertel 5271: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5272: my ($tmp)=keys(%current_permissions);
5273: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 5274: foreach my $file (@{$files}) {
1.759 albertel 5275: $file = &declutter_portfile($file);
1.561 banghart 5276: push(@{$current_permissions{$file}},$what);
1.559 banghart 5277: }
1.613 albertel 5278: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 5279: return;
5280: }
5281:
1.572 banghart 5282: # ------------------------------------------------------------Save Selected Files
5283:
5284: sub save_selected_files {
5285: my ($user, $path, @files) = @_;
5286: my $filename = $user."savedfiles";
1.573 banghart 5287: my @other_files = &files_not_in_path($user, $path);
1.574 banghart 5288: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 5289: foreach my $file (@files) {
1.620 albertel 5290: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 5291: }
5292: foreach my $file (@other_files) {
1.574 banghart 5293: print (OUT $file."\n");
1.572 banghart 5294: }
1.574 banghart 5295: close (OUT);
1.572 banghart 5296: return 'ok';
5297: }
5298:
1.574 banghart 5299: sub clear_selected_files {
5300: my ($user) = @_;
5301: my $filename = $user."savedfiles";
5302: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5303: print (OUT undef);
5304: close (OUT);
5305: return ("ok");
5306: }
5307:
1.572 banghart 5308: sub files_in_path {
5309: my ($user, $path) = @_;
5310: my $filename = $user."savedfiles";
5311: my %return_files;
1.574 banghart 5312: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 5313: while (my $line_in = <IN>) {
1.574 banghart 5314: chomp ($line_in);
5315: my @paths_and_file = split (m!/!, $line_in);
5316: my $file_part = pop (@paths_and_file);
5317: my $path_part = join ('/', @paths_and_file);
1.573 banghart 5318: $path_part.='/';
5319: my $path_and_file = $path_part.$file_part;
5320: if ($path_part eq $path) {
5321: $return_files{$file_part}= 'selected';
5322: }
5323: }
1.574 banghart 5324: close (IN);
5325: return (\%return_files);
1.572 banghart 5326: }
5327:
5328: # called in portfolio select mode, to show files selected NOT in current directory
5329: sub files_not_in_path {
5330: my ($user, $path) = @_;
5331: my $filename = $user."savedfiles";
5332: my @return_files;
5333: my $path_part;
1.800 albertel 5334: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5335: while (my $line = <IN>) {
1.572 banghart 5336: #ok, I know it's clunky, but I want it to work
1.800 albertel 5337: my @paths_and_file = split(m|/|, $line);
5338: my $file_part = pop(@paths_and_file);
5339: chomp($file_part);
5340: my $path_part = join('/', @paths_and_file);
1.572 banghart 5341: $path_part .= '/';
5342: my $path_and_file = $path_part.$file_part;
5343: if ($path_part ne $path) {
1.800 albertel 5344: push(@return_files, ($path_and_file));
1.572 banghart 5345: }
5346: }
1.800 albertel 5347: close(OUT);
1.574 banghart 5348: return (@return_files);
1.572 banghart 5349: }
5350:
1.745 raeburn 5351: #----------------------------------------------Get portfolio file permissions
1.629 banghart 5352:
1.745 raeburn 5353: sub get_portfile_permissions {
5354: my ($domain,$user) = @_;
1.613 albertel 5355: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5356: my ($tmp)=keys(%current_permissions);
5357: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 5358: return \%current_permissions;
5359: }
5360:
5361: #---------------------------------------------Get portfolio file access controls
5362:
1.749 raeburn 5363: sub get_access_controls {
1.745 raeburn 5364: my ($current_permissions,$group,$file) = @_;
1.769 albertel 5365: my %access;
5366: my $real_file = $file;
5367: $file =~ s/\.meta$//;
1.745 raeburn 5368: if (defined($file)) {
1.749 raeburn 5369: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
5370: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 5371: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 5372: }
5373: }
1.745 raeburn 5374: } else {
1.749 raeburn 5375: foreach my $key (keys(%{$current_permissions})) {
5376: if ($key =~ /\0accesscontrol$/) {
5377: if (defined($group)) {
5378: if ($key !~ m-^\Q$group\E/-) {
5379: next;
5380: }
5381: }
5382: my ($fullpath) = split(/\0/,$key);
5383: if (ref($$current_permissions{$key}) eq 'HASH') {
5384: foreach my $control (keys(%{$$current_permissions{$key}})) {
5385: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
5386: }
5387: }
5388: }
5389: }
5390: }
5391: return %access;
5392: }
5393:
5394: sub modify_access_controls {
5395: my ($file_name,$changes,$domain,$user)=@_;
5396: my ($outcome,$deloutcome);
5397: my %store_permissions;
5398: my %new_values;
5399: my %new_control;
5400: my %translation;
5401: my @deletions = ();
5402: my $now = time;
5403: if (exists($$changes{'activate'})) {
5404: if (ref($$changes{'activate'}) eq 'HASH') {
5405: my @newitems = sort(keys(%{$$changes{'activate'}}));
5406: my $numnew = scalar(@newitems);
5407: for (my $i=0; $i<$numnew; $i++) {
5408: my $newkey = $newitems[$i];
5409: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 5410: if ($newkey =~ /^\d+:/) {
5411: $newkey =~ s/^(\d+)/$newid/;
5412: $translation{$1} = $newid;
5413: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
5414: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
5415: $translation{$1} = $newid;
5416: }
1.749 raeburn 5417: $new_values{$file_name."\0".$newkey} =
5418: $$changes{'activate'}{$newitems[$i]};
5419: $new_control{$newkey} = $now;
5420: }
5421: }
5422: }
5423: my %todelete;
5424: my %changed_items;
5425: foreach my $action ('delete','update') {
5426: if (exists($$changes{$action})) {
5427: if (ref($$changes{$action}) eq 'HASH') {
5428: foreach my $key (keys(%{$$changes{$action}})) {
5429: my ($itemnum) = ($key =~ /^([^:]+):/);
5430: if ($action eq 'delete') {
5431: $todelete{$itemnum} = 1;
5432: } else {
5433: $changed_items{$itemnum} = $key;
5434: }
5435: }
1.745 raeburn 5436: }
5437: }
1.749 raeburn 5438: }
5439: # get lock on access controls for file.
5440: my $lockhash = {
5441: $file_name."\0".'locked_access_records' => $env{'user.name'}.
5442: ':'.$env{'user.domain'},
5443: };
5444: my $tries = 0;
5445: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5446:
5447: while (($gotlock ne 'ok') && $tries <3) {
5448: $tries ++;
5449: sleep 1;
5450: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5451: }
5452: if ($gotlock eq 'ok') {
5453: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
5454: my ($tmp)=keys(%curr_permissions);
5455: if ($tmp=~/^error:/) { undef(%curr_permissions); }
5456: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
5457: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
5458: if (ref($curr_controls) eq 'HASH') {
5459: foreach my $control_item (keys(%{$curr_controls})) {
5460: my ($itemnum) = ($control_item =~ /^([^:]+):/);
5461: if (defined($todelete{$itemnum})) {
5462: push(@deletions,$file_name."\0".$control_item);
5463: } else {
5464: if (defined($changed_items{$itemnum})) {
5465: $new_control{$changed_items{$itemnum}} = $now;
5466: push(@deletions,$file_name."\0".$control_item);
5467: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
5468: } else {
5469: $new_control{$control_item} = $$curr_controls{$control_item};
5470: }
5471: }
1.745 raeburn 5472: }
5473: }
5474: }
1.749 raeburn 5475: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
5476: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
5477: $outcome = &put('file_permissions',\%new_values,$domain,$user);
5478: # remove lock
5479: my @del_lock = ($file_name."\0".'locked_access_records');
5480: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 5481: my ($file,$group);
5482: if (&is_course($domain,$user)) {
5483: ($group,$file) = split(/\//,$file_name,2);
5484: } else {
5485: $file = $file_name;
5486: }
5487: my $sqlresult =
5488: &update_portfolio_table($user,$domain,$file,'portfolio_access',
5489: $group);
1.749 raeburn 5490: } else {
5491: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 5492: }
1.749 raeburn 5493: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 5494: }
5495:
1.827 raeburn 5496: sub make_public_indefinitely {
5497: my ($requrl) = @_;
5498: my $now = time;
5499: my $action = 'activate';
5500: my $aclnum = 0;
5501: if (&is_portfolio_url($requrl)) {
5502: my (undef,$udom,$unum,$file_name,$group) =
5503: &parse_portfolio_url($requrl);
5504: my $current_perms = &get_portfile_permissions($udom,$unum);
5505: my %access_controls = &get_access_controls($current_perms,
5506: $group,$file_name);
5507: foreach my $key (keys(%{$access_controls{$file_name}})) {
5508: my ($num,$scope,$end,$start) =
5509: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5510: if ($scope eq 'public') {
5511: if ($start <= $now && $end == 0) {
5512: $action = 'none';
5513: } else {
5514: $action = 'update';
5515: $aclnum = $num;
5516: }
5517: last;
5518: }
5519: }
5520: if ($action eq 'none') {
5521: return 'ok';
5522: } else {
5523: my %changes;
5524: my $newend = 0;
5525: my $newstart = $now;
5526: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
5527: $changes{$action}{$newkey} = {
5528: type => 'public',
5529: time => {
5530: start => $newstart,
5531: end => $newend,
5532: },
5533: };
5534: my ($outcome,$deloutcome,$new_values,$translation) =
5535: &modify_access_controls($file_name,\%changes,$udom,$unum);
5536: return $outcome;
5537: }
5538: } else {
5539: return 'invalid';
5540: }
5541: }
5542:
1.745 raeburn 5543: #------------------------------------------------------Get Marked as Read Only
5544:
5545: sub get_marked_as_readonly {
5546: my ($domain,$user,$what,$group) = @_;
5547: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 5548: my @readonly_files;
1.629 banghart 5549: my $cmp1=$what;
5550: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 5551: while (my ($file_name,$value) = each(%{$current_permissions})) {
5552: if (defined($group)) {
5553: if ($file_name !~ m-^\Q$group\E/-) {
5554: next;
5555: }
5556: }
1.561 banghart 5557: if (ref($value) eq "ARRAY"){
5558: foreach my $stored_what (@{$value}) {
1.629 banghart 5559: my $cmp2=$stored_what;
1.759 albertel 5560: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 5561: $cmp2=join('',@{$stored_what});
1.745 raeburn 5562: }
1.629 banghart 5563: if ($cmp1 eq $cmp2) {
1.561 banghart 5564: push(@readonly_files, $file_name);
1.745 raeburn 5565: last;
1.563 banghart 5566: } elsif (!defined($what)) {
5567: push(@readonly_files, $file_name);
1.745 raeburn 5568: last;
1.561 banghart 5569: }
5570: }
1.745 raeburn 5571: }
1.561 banghart 5572: }
5573: return @readonly_files;
5574: }
1.577 banghart 5575: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 5576:
1.577 banghart 5577: sub get_marked_as_readonly_hash {
1.745 raeburn 5578: my ($current_permissions,$group,$what) = @_;
1.577 banghart 5579: my %readonly_files;
1.745 raeburn 5580: while (my ($file_name,$value) = each(%{$current_permissions})) {
5581: if (defined($group)) {
5582: if ($file_name !~ m-^\Q$group\E/-) {
5583: next;
5584: }
5585: }
1.577 banghart 5586: if (ref($value) eq "ARRAY"){
5587: foreach my $stored_what (@{$value}) {
1.745 raeburn 5588: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 5589: foreach my $lock_descriptor(@{$stored_what}) {
5590: if ($lock_descriptor eq 'graded') {
5591: $readonly_files{$file_name} = 'graded';
5592: } elsif ($lock_descriptor eq 'handback') {
5593: $readonly_files{$file_name} = 'handback';
5594: } else {
5595: if (!exists($readonly_files{$file_name})) {
5596: $readonly_files{$file_name} = 'locked';
5597: }
5598: }
1.745 raeburn 5599: }
1.750 banghart 5600: }
1.577 banghart 5601: }
5602: }
5603: }
5604: return %readonly_files;
5605: }
1.559 banghart 5606: # ------------------------------------------------------------ Unmark as Read Only
5607:
5608: sub unmark_as_readonly {
1.629 banghart 5609: # unmarks $file_name (if $file_name is defined), or all files locked by $what
5610: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 5611: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 5612: $file_name = &declutter_portfile($file_name);
1.634 albertel 5613: my $symb_crs = $what;
5614: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 5615: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 5616: my ($tmp)=keys(%current_permissions);
5617: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 5618: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 5619: foreach my $file (@readonly_files) {
1.759 albertel 5620: my $clean_file = &declutter_portfile($file);
5621: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 5622: my $current_locks = $current_permissions{$file};
1.563 banghart 5623: my @new_locks;
5624: my @del_keys;
5625: if (ref($current_locks) eq "ARRAY"){
5626: foreach my $locker (@{$current_locks}) {
1.632 albertel 5627: my $compare=$locker;
1.749 raeburn 5628: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 5629: $compare=join('',@{$locker});
1.746 raeburn 5630: if ($compare ne $symb_crs) {
5631: push(@new_locks, $locker);
5632: }
1.563 banghart 5633: }
5634: }
1.650 albertel 5635: if (scalar(@new_locks) > 0) {
1.563 banghart 5636: $current_permissions{$file} = \@new_locks;
5637: } else {
5638: push(@del_keys, $file);
1.613 albertel 5639: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 5640: delete($current_permissions{$file});
1.563 banghart 5641: }
5642: }
1.561 banghart 5643: }
1.613 albertel 5644: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 5645: return;
5646: }
1.512 banghart 5647:
1.17 www 5648: # ------------------------------------------------------------ Directory lister
5649:
5650: sub dirlist {
1.253 stredwic 5651: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
5652:
1.18 www 5653: $uri=~s/^\///;
5654: $uri=~s/\/$//;
1.253 stredwic 5655: my ($udom, $uname);
5656: (undef,$udom,$uname)=split(/\//,$uri);
5657: if(defined($userdomain)) {
5658: $udom = $userdomain;
5659: }
5660: if(defined($username)) {
5661: $uname = $username;
5662: }
5663:
5664: my $dirRoot = $perlvar{'lonDocRoot'};
5665: if(defined($alternateDirectoryRoot)) {
5666: $dirRoot = $alternateDirectoryRoot;
5667: $dirRoot =~ s/\/$//;
1.751 banghart 5668: }
1.253 stredwic 5669:
5670: if($udom) {
5671: if($uname) {
1.800 albertel 5672: my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
5673: &homeserver($uname,$udom));
1.605 matthew 5674: my @listing_results;
5675: if ($listing eq 'unknown_cmd') {
1.800 albertel 5676: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
5677: &homeserver($uname,$udom));
1.605 matthew 5678: @listing_results = split(/:/,$listing);
5679: } else {
5680: @listing_results = map { &unescape($_); } split(/:/,$listing);
5681: }
5682: return @listing_results;
1.253 stredwic 5683: } elsif(!defined($alternateDirectoryRoot)) {
1.800 albertel 5684: my %allusers;
1.841 albertel 5685: my %servers = &get_servers($udom,'library');
5686: foreach my $tryserver (keys(%servers)) {
5687: my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
5688: $udom, $tryserver);
5689: my @listing_results;
5690: if ($listing eq 'unknown_cmd') {
5691: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
5692: $udom, $tryserver);
5693: @listing_results = split(/:/,$listing);
5694: } else {
5695: @listing_results =
5696: map { &unescape($_); } split(/:/,$listing);
5697: }
5698: if ($listing_results[0] ne 'no_such_dir' &&
5699: $listing_results[0] ne 'empty' &&
5700: $listing_results[0] ne 'con_lost') {
5701: foreach my $line (@listing_results) {
5702: my ($entry) = split(/&/,$line,2);
5703: $allusers{$entry} = 1;
5704: }
5705: }
1.253 stredwic 5706: }
5707: my $alluserstr='';
1.800 albertel 5708: foreach my $user (sort(keys(%allusers))) {
5709: $alluserstr.=$user.'&user:';
1.253 stredwic 5710: }
5711: $alluserstr=~s/:$//;
5712: return split(/:/,$alluserstr);
5713: } else {
1.800 albertel 5714: return ('missing user name');
1.253 stredwic 5715: }
5716: } elsif(!defined($alternateDirectoryRoot)) {
1.841 albertel 5717: my @all_domains = sort(&all_domains());
5718: foreach my $domain (@all_domains) {
5719: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
5720: }
5721: return @all_domains;
5722: } else {
1.800 albertel 5723: return ('missing domain');
1.275 stredwic 5724: }
5725: }
5726:
5727: # --------------------------------------------- GetFileTimestamp
5728: # This function utilizes dirlist and returns the date stamp for
5729: # when it was last modified. It will also return an error of -1
5730: # if an error occurs
5731:
1.410 matthew 5732: ##
5733: ## FIXME: This subroutine assumes its caller knows something about the
5734: ## directory structure of the home server for the student ($root).
5735: ## Not a good assumption to make. Since this is for looking up files
5736: ## in user directories, the full path should be constructed by lond, not
5737: ## whatever machine we request data from.
5738: ##
1.275 stredwic 5739: sub GetFileTimestamp {
5740: my ($studentDomain,$studentName,$filename,$root)=@_;
1.807 albertel 5741: $studentDomain = &LONCAPA::clean_domain($studentDomain);
5742: $studentName = &LONCAPA::clean_username($studentName);
1.275 stredwic 5743: my $subdir=$studentName.'__';
5744: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
5745: my $proname="$studentDomain/$subdir/$studentName";
5746: $proname .= '/'.$filename;
1.375 matthew 5747: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
5748: $studentName, $root);
1.275 stredwic 5749: my @stats = split('&', $fileStat);
5750: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 5751: # @stats contains first the filename, then the stat output
5752: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 5753: } else {
5754: return -1;
1.253 stredwic 5755: }
1.26 www 5756: }
5757:
1.712 albertel 5758: sub stat_file {
5759: my ($uri) = @_;
1.787 albertel 5760: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 5761:
1.712 albertel 5762: my ($udom,$uname,$file,$dir);
5763: if ($uri =~ m-^/(uploaded|editupload)/-) {
5764: ($udom,$uname,$file) =
1.811 albertel 5765: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 5766: $file = 'userfiles/'.$file;
1.740 www 5767: $dir = &propath($udom,$uname);
1.712 albertel 5768: }
5769: if ($uri =~ m-^/res/-) {
5770: ($udom,$uname) =
1.807 albertel 5771: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 5772: $file = $uri;
5773: }
5774:
5775: if (!$udom || !$uname || !$file) {
5776: # unable to handle the uri
5777: return ();
5778: }
5779:
5780: my ($result) = &dirlist($file,$udom,$uname,$dir);
5781: my @stats = split('&', $result);
1.721 banghart 5782:
1.712 albertel 5783: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
5784: shift(@stats); #filename is first
5785: return @stats;
5786: }
5787: return ();
5788: }
5789:
1.26 www 5790: # -------------------------------------------------------- Value of a Condition
5791:
1.713 albertel 5792: # gets the value of a specific preevaluated condition
5793: # stored in the string $env{user.state.<cid>}
5794: # or looks up a condition reference in the bighash and if if hasn't
5795: # already been evaluated recurses into docondval to get the value of
5796: # the condition, then memoizing it to
5797: # $env{user.state.<cid>.<condition>}
1.40 www 5798: sub directcondval {
5799: my $number=shift;
1.620 albertel 5800: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 5801: &Apache::lonuserstate::evalstate();
5802: }
1.713 albertel 5803: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
5804: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
5805: } elsif ($number =~ /^_/) {
5806: my $sub_condition;
5807: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5808: &GDBM_READER(),0640)) {
5809: $sub_condition=$bighash{'conditions'.$number};
5810: untie(%bighash);
5811: }
5812: my $value = &docondval($sub_condition);
5813: &appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
5814: return $value;
5815: }
1.620 albertel 5816: if ($env{'user.state.'.$env{'request.course.id'}}) {
5817: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 5818: } else {
5819: return 2;
5820: }
5821: }
5822:
1.713 albertel 5823: # get the collection of conditions for this resource
1.26 www 5824: sub condval {
5825: my $condidx=shift;
1.54 www 5826: my $allpathcond='';
1.713 albertel 5827: foreach my $cond (split(/\|/,$condidx)) {
5828: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
5829: $allpathcond.=
5830: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
5831: }
1.191 harris41 5832: }
1.54 www 5833: $allpathcond=~s/\|$//;
1.713 albertel 5834: return &docondval($allpathcond);
5835: }
5836:
5837: #evaluates an expression of conditions
5838: sub docondval {
5839: my ($allpathcond) = @_;
5840: my $result=0;
5841: if ($env{'request.course.id'}
5842: && defined($allpathcond)) {
5843: my $operand='|';
5844: my @stack;
5845: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
5846: if ($chunk eq '(') {
5847: push @stack,($operand,$result);
5848: } elsif ($chunk eq ')') {
5849: my $before=pop @stack;
5850: if (pop @stack eq '&') {
5851: $result=$result>$before?$before:$result;
5852: } else {
5853: $result=$result>$before?$result:$before;
5854: }
5855: } elsif (($chunk eq '&') || ($chunk eq '|')) {
5856: $operand=$chunk;
5857: } else {
5858: my $new=directcondval($chunk);
5859: if ($operand eq '&') {
5860: $result=$result>$new?$new:$result;
5861: } else {
5862: $result=$result>$new?$result:$new;
5863: }
5864: }
5865: }
1.26 www 5866: }
5867: return $result;
1.421 albertel 5868: }
5869:
5870: # ---------------------------------------------------- Devalidate courseresdata
5871:
5872: sub devalidatecourseresdata {
5873: my ($coursenum,$coursedomain)=@_;
5874: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 5875: &devalidate_cache_new('courseres',$hashid);
1.28 www 5876: }
5877:
1.763 www 5878:
1.200 www 5879: # --------------------------------------------------- Course Resourcedata Query
5880:
1.624 albertel 5881: sub get_courseresdata {
5882: my ($coursenum,$coursedomain)=@_;
1.200 www 5883: my $coursehom=&homeserver($coursenum,$coursedomain);
5884: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 5885: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 5886: my %dumpreply;
1.417 albertel 5887: unless (defined($cached)) {
1.624 albertel 5888: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 5889: $result=\%dumpreply;
1.251 albertel 5890: my ($tmp) = keys(%dumpreply);
5891: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 5892: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 5893: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
5894: return $tmp;
1.416 albertel 5895: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 5896: $result=undef;
1.599 albertel 5897: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 5898: }
5899: }
1.624 albertel 5900: return $result;
5901: }
5902:
1.633 albertel 5903: sub devalidateuserresdata {
5904: my ($uname,$udom)=@_;
5905: my $hashid="$udom:$uname";
5906: &devalidate_cache_new('userres',$hashid);
5907: }
5908:
1.624 albertel 5909: sub get_userresdata {
5910: my ($uname,$udom)=@_;
5911: #most student don\'t have any data set, check if there is some data
5912: if (&EXT_cache_status($udom,$uname)) { return undef; }
5913:
5914: my $hashid="$udom:$uname";
5915: my ($result,$cached)=&is_cached_new('userres',$hashid);
5916: if (!defined($cached)) {
5917: my %resourcedata=&dump('resourcedata',$udom,$uname);
5918: $result=\%resourcedata;
5919: &do_cache_new('userres',$hashid,$result,600);
5920: }
5921: my ($tmp)=keys(%$result);
5922: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
5923: return $result;
5924: }
5925: #error 2 occurs when the .db doesn't exist
5926: if ($tmp!~/error: 2 /) {
1.672 albertel 5927: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 5928: " Trying to get resource data for ".
5929: $uname." at ".$udom.": ".
5930: $tmp."</font>");
5931: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 5932: #&EXT_cache_set($udom,$uname);
5933: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 5934: undef($tmp); # not really an error so don't send it back
1.624 albertel 5935: }
5936: return $tmp;
5937: }
5938:
5939: sub resdata {
5940: my ($name,$domain,$type,@which)=@_;
5941: my $result;
5942: if ($type eq 'course') {
5943: $result=&get_courseresdata($name,$domain);
5944: } elsif ($type eq 'user') {
5945: $result=&get_userresdata($name,$domain);
5946: }
5947: if (!ref($result)) { return $result; }
1.251 albertel 5948: foreach my $item (@which) {
1.417 albertel 5949: if (defined($result->{$item})) {
5950: return $result->{$item};
1.251 albertel 5951: }
1.250 albertel 5952: }
1.291 albertel 5953: return undef;
1.200 www 5954: }
5955:
1.379 matthew 5956: #
5957: # EXT resource caching routines
5958: #
5959:
5960: sub clear_EXT_cache_status {
1.383 albertel 5961: &delenv('cache.EXT.');
1.379 matthew 5962: }
5963:
5964: sub EXT_cache_status {
5965: my ($target_domain,$target_user) = @_;
1.383 albertel 5966: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 5967: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 5968: # We know already the user has no data
5969: return 1;
5970: } else {
5971: return 0;
5972: }
5973: }
5974:
5975: sub EXT_cache_set {
5976: my ($target_domain,$target_user) = @_;
1.383 albertel 5977: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633 albertel 5978: #&appenv($cachename => time);
1.379 matthew 5979: }
5980:
1.28 www 5981: # --------------------------------------------------------- Value of a Variable
1.58 www 5982: sub EXT {
1.715 albertel 5983:
1.395 albertel 5984: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 5985: unless ($varname) { return ''; }
1.218 albertel 5986: #get real user name/domain, courseid and symb
5987: my $courseid;
1.359 albertel 5988: my $publicuser;
1.427 www 5989: if ($symbparm) {
5990: $symbparm=&get_symb_from_alias($symbparm);
5991: }
1.218 albertel 5992: if (!($uname && $udom)) {
1.790 albertel 5993: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 5994: if (!$symbparm) { $symbparm=$cursymb; }
5995: } else {
1.620 albertel 5996: $courseid=$env{'request.course.id'};
1.218 albertel 5997: }
1.48 www 5998: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
5999: my $rest;
1.320 albertel 6000: if (defined($therest[0])) {
1.48 www 6001: $rest=join('.',@therest);
6002: } else {
6003: $rest='';
6004: }
1.320 albertel 6005:
1.57 www 6006: my $qualifierrest=$qualifier;
6007: if ($rest) { $qualifierrest.='.'.$rest; }
6008: my $spacequalifierrest=$space;
6009: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 6010: if ($realm eq 'user') {
1.48 www 6011: # --------------------------------------------------------------- user.resource
6012: if ($space eq 'resource') {
1.651 albertel 6013: if ( (defined($Apache::lonhomework::parsing_a_problem)
6014: || defined($Apache::lonhomework::parsing_a_task))
6015: &&
1.744 albertel 6016: ($symbparm eq &symbread()) ) {
6017: # if we are in the middle of processing the resource the
6018: # get the value we are planning on committing
6019: if (defined($Apache::lonhomework::results{$qualifierrest})) {
6020: return $Apache::lonhomework::results{$qualifierrest};
6021: } else {
6022: return $Apache::lonhomework::history{$qualifierrest};
6023: }
1.335 albertel 6024: } else {
1.359 albertel 6025: my %restored;
1.620 albertel 6026: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 6027: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
6028: } else {
6029: %restored=&restore($symbparm,$courseid,$udom,$uname);
6030: }
1.335 albertel 6031: return $restored{$qualifierrest};
6032: }
1.48 www 6033: # ----------------------------------------------------------------- user.access
6034: } elsif ($space eq 'access') {
1.218 albertel 6035: # FIXME - not supporting calls for a specific user
1.48 www 6036: return &allowed($qualifier,$rest);
6037: # ------------------------------------------ user.preferences, user.environment
6038: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 6039: if (($uname eq $env{'user.name'}) &&
6040: ($udom eq $env{'user.domain'})) {
6041: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 6042: } else {
1.359 albertel 6043: my %returnhash;
6044: if (!$publicuser) {
6045: %returnhash=&userenvironment($udom,$uname,
6046: $qualifierrest);
6047: }
1.218 albertel 6048: return $returnhash{$qualifierrest};
6049: }
1.48 www 6050: # ----------------------------------------------------------------- user.course
6051: } elsif ($space eq 'course') {
1.218 albertel 6052: # FIXME - not supporting calls for a specific user
1.620 albertel 6053: return $env{join('.',('request.course',$qualifier))};
1.48 www 6054: # ------------------------------------------------------------------- user.role
6055: } elsif ($space eq 'role') {
1.218 albertel 6056: # FIXME - not supporting calls for a specific user
1.620 albertel 6057: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 6058: if ($qualifier eq 'value') {
6059: return $role;
6060: } elsif ($qualifier eq 'extent') {
6061: return $where;
6062: }
6063: # ----------------------------------------------------------------- user.domain
6064: } elsif ($space eq 'domain') {
1.218 albertel 6065: return $udom;
1.48 www 6066: # ------------------------------------------------------------------- user.name
6067: } elsif ($space eq 'name') {
1.218 albertel 6068: return $uname;
1.48 www 6069: # ---------------------------------------------------- Any other user namespace
1.29 www 6070: } else {
1.359 albertel 6071: my %reply;
6072: if (!$publicuser) {
6073: %reply=&get($space,[$qualifierrest],$udom,$uname);
6074: }
6075: return $reply{$qualifierrest};
1.48 www 6076: }
1.236 www 6077: } elsif ($realm eq 'query') {
6078: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 6079: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
6080: [$spacequalifierrest]);
1.620 albertel 6081: return $env{'form.'.$spacequalifierrest};
1.236 www 6082: } elsif ($realm eq 'request') {
1.48 www 6083: # ------------------------------------------------------------- request.browser
6084: if ($space eq 'browser') {
1.430 www 6085: if ($qualifier eq 'textremote') {
1.676 albertel 6086: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 6087: return 1;
6088: } else {
6089: return 0;
6090: }
6091: } else {
1.620 albertel 6092: return $env{'browser.'.$qualifier};
1.430 www 6093: }
1.57 www 6094: # ------------------------------------------------------------ request.filename
6095: } else {
1.620 albertel 6096: return $env{'request.'.$spacequalifierrest};
1.29 www 6097: }
1.28 www 6098: } elsif ($realm eq 'course') {
1.48 www 6099: # ---------------------------------------------------------- course.description
1.620 albertel 6100: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 6101: } elsif ($realm eq 'resource') {
1.165 www 6102:
1.620 albertel 6103: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 6104: if (!$symbparm) { $symbparm=&symbread(); }
6105: }
1.693 albertel 6106:
6107: if ($space eq 'title') {
6108: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
6109: return &gettitle($symbparm);
6110: }
6111:
6112: if ($space eq 'map') {
6113: my ($map) = &decode_symb($symbparm);
6114: return &symbread($map);
6115: }
6116:
6117: my ($section, $group, @groups);
1.593 albertel 6118: my ($courselevelm,$courselevel);
1.539 albertel 6119: if ($symbparm && defined($courseid) &&
1.620 albertel 6120: $courseid eq $env{'request.course.id'}) {
1.165 www 6121:
1.218 albertel 6122: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 6123:
1.60 www 6124: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 6125: my $symbp=$symbparm;
1.735 albertel 6126: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 6127:
6128: my $symbparm=$symbp.'.'.$spacequalifierrest;
6129: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
6130:
1.620 albertel 6131: if (($env{'user.name'} eq $uname) &&
6132: ($env{'user.domain'} eq $udom)) {
6133: $section=$env{'request.course.sec'};
1.733 raeburn 6134: @groups = split(/:/,$env{'request.course.groups'});
6135: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 6136: } else {
1.539 albertel 6137: if (! defined($usection)) {
1.551 albertel 6138: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 6139: } else {
6140: $section = $usection;
6141: }
1.733 raeburn 6142: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 6143: }
6144:
6145: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
6146: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
6147: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
6148:
1.593 albertel 6149: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 6150: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 6151: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 6152:
1.60 www 6153: # ----------------------------------------------------------- first, check user
1.624 albertel 6154:
6155: my $userreply=&resdata($uname,$udom,'user',
6156: ($courselevelr,$courselevelm,
6157: $courselevel));
6158: if (defined($userreply)) { return $userreply; }
1.95 www 6159:
1.594 albertel 6160: # ------------------------------------------------ second, check some of course
1.684 raeburn 6161: my $coursereply;
1.691 raeburn 6162: if (@groups > 0) {
6163: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
6164: $mapparm,$spacequalifierrest);
1.684 raeburn 6165: if (defined($coursereply)) { return $coursereply; }
6166: }
1.96 www 6167:
1.684 raeburn 6168: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624 albertel 6169: $env{'course.'.$courseid.'.domain'},
6170: 'course',
6171: ($seclevelr,$seclevelm,$seclevel,
6172: $courselevelr));
1.287 albertel 6173: if (defined($coursereply)) { return $coursereply; }
1.200 www 6174:
1.60 www 6175: # ------------------------------------------------------ third, check map parms
1.218 albertel 6176: my %parmhash=();
6177: my $thisparm='';
6178: if (tie(%parmhash,'GDBM_File',
1.620 albertel 6179: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 6180: &GDBM_READER(),0640)) {
1.218 albertel 6181: $thisparm=$parmhash{$symbparm};
6182: untie(%parmhash);
6183: }
6184: if ($thisparm) { return $thisparm; }
6185: }
1.594 albertel 6186: # ------------------------------------------ fourth, look in resource metadata
1.71 www 6187:
1.218 albertel 6188: $spacequalifierrest=~s/\./\_/;
1.282 albertel 6189: my $filename;
6190: if (!$symbparm) { $symbparm=&symbread(); }
6191: if ($symbparm) {
1.409 www 6192: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 6193: } else {
1.620 albertel 6194: $filename=$env{'request.filename'};
1.282 albertel 6195: }
6196: my $metadata=&metadata($filename,$spacequalifierrest);
1.288 albertel 6197: if (defined($metadata)) { return $metadata; }
1.282 albertel 6198: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288 albertel 6199: if (defined($metadata)) { return $metadata; }
1.142 www 6200:
1.594 albertel 6201: # ---------------------------------------------- fourth, look in rest pf course
1.593 albertel 6202: if ($symbparm && defined($courseid) &&
1.620 albertel 6203: $courseid eq $env{'request.course.id'}) {
1.624 albertel 6204: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
6205: $env{'course.'.$courseid.'.domain'},
6206: 'course',
6207: ($courselevelm,$courselevel));
1.593 albertel 6208: if (defined($coursereply)) { return $coursereply; }
6209: }
1.145 www 6210: # ------------------------------------------------------------------ Cascade up
1.218 albertel 6211: unless ($space eq '0') {
1.336 albertel 6212: my @parts=split(/_/,$space);
6213: my $id=pop(@parts);
6214: my $part=join('_',@parts);
6215: if ($part eq '') { $part='0'; }
6216: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 6217: $symbparm,$udom,$uname,$section,1);
1.337 albertel 6218: if (defined($partgeneral)) { return $partgeneral; }
1.218 albertel 6219: }
1.395 albertel 6220: if ($recurse) { return undef; }
6221: my $pack_def=&packages_tab_default($filename,$varname);
6222: if (defined($pack_def)) { return $pack_def; }
1.71 www 6223:
1.48 www 6224: # ---------------------------------------------------- Any other user namespace
6225: } elsif ($realm eq 'environment') {
6226: # ----------------------------------------------------------------- environment
1.620 albertel 6227: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
6228: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 6229: } else {
1.770 albertel 6230: if ($uname eq 'anonymous' && $udom eq '') {
6231: return '';
6232: }
1.219 albertel 6233: my %returnhash=&userenvironment($udom,$uname,
6234: $spacequalifierrest);
6235: return $returnhash{$spacequalifierrest};
6236: }
1.28 www 6237: } elsif ($realm eq 'system') {
1.48 www 6238: # ----------------------------------------------------------------- system.time
6239: if ($space eq 'time') {
6240: return time;
6241: }
1.696 albertel 6242: } elsif ($realm eq 'server') {
6243: # ----------------------------------------------------------------- system.time
6244: if ($space eq 'name') {
6245: return $ENV{'SERVER_NAME'};
6246: }
1.28 www 6247: }
1.48 www 6248: return '';
1.61 www 6249: }
6250:
1.691 raeburn 6251: sub check_group_parms {
6252: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
6253: my @groupitems = ();
6254: my $resultitem;
6255: my @levels = ($symbparm,$mapparm,$what);
6256: foreach my $group (@{$groups}) {
6257: foreach my $level (@levels) {
6258: my $item = $courseid.'.['.$group.'].'.$level;
6259: push(@groupitems,$item);
6260: }
6261: }
6262: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
6263: $env{'course.'.$courseid.'.domain'},
6264: 'course',@groupitems);
6265: return $coursereply;
6266: }
6267:
6268: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 6269: my ($courseid,@groups) = @_;
6270: @groups = sort(@groups);
1.691 raeburn 6271: return @groups;
6272: }
6273:
1.395 albertel 6274: sub packages_tab_default {
6275: my ($uri,$varname)=@_;
6276: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 6277:
6278: my (@extension,@specifics,$do_default);
6279: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 6280: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 6281: if ($pack_type eq 'default') {
6282: $do_default=1;
6283: } elsif ($pack_type eq 'extension') {
6284: push(@extension,[$package,$pack_type,$pack_part]);
1.848 albertel 6285: } elsif ($pack_part eq $part) {
6286: # only look at packages defaults for packages that this id is
1.738 albertel 6287: push(@specifics,[$package,$pack_type,$pack_part]);
6288: }
6289: }
6290: # first look for a package that matches the requested part id
6291: foreach my $package (@specifics) {
6292: my (undef,$pack_type,$pack_part)=@{$package};
6293: next if ($pack_part ne $part);
6294: if (defined($packagetab{"$pack_type&$name&default"})) {
6295: return $packagetab{"$pack_type&$name&default"};
6296: }
6297: }
6298: # look for any possible matching non extension_ package
6299: foreach my $package (@specifics) {
6300: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 6301: if (defined($packagetab{"$pack_type&$name&default"})) {
6302: return $packagetab{"$pack_type&$name&default"};
6303: }
1.585 albertel 6304: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 6305: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
6306: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 6307: }
6308: }
1.738 albertel 6309: # look for any posible extension_ match
6310: foreach my $package (@extension) {
6311: my ($package,$pack_type)=@{$package};
6312: if (defined($packagetab{"$pack_type&$name&default"})) {
6313: return $packagetab{"$pack_type&$name&default"};
6314: }
6315: if (defined($packagetab{$package."&$name&default"})) {
6316: return $packagetab{$package."&$name&default"};
6317: }
6318: }
6319: # look for a global default setting
6320: if ($do_default && defined($packagetab{"default&$name&default"})) {
6321: return $packagetab{"default&$name&default"};
6322: }
1.395 albertel 6323: return undef;
6324: }
6325:
1.334 albertel 6326: sub add_prefix_and_part {
6327: my ($prefix,$part)=@_;
6328: my $keyroot;
6329: if (defined($prefix) && $prefix !~ /^__/) {
6330: # prefix that has a part already
6331: $keyroot=$prefix;
6332: } elsif (defined($prefix)) {
6333: # prefix that is missing a part
6334: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
6335: } else {
6336: # no prefix at all
6337: if (defined($part)) { $keyroot='_'.$part; }
6338: }
6339: return $keyroot;
6340: }
6341:
1.71 www 6342: # ---------------------------------------------------------------- Get metadata
6343:
1.599 albertel 6344: my %metaentry;
1.71 www 6345: sub metadata {
1.176 www 6346: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 6347: $uri=&declutter($uri);
1.288 albertel 6348: # if it is a non metadata possible uri return quickly
1.529 albertel 6349: if (($uri eq '') ||
6350: (($uri =~ m|^/*adm/|) &&
1.698 albertel 6351: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423 albertel 6352: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807 albertel 6353: ($uri =~ m|home/$match_username/public_html/|)) {
1.468 albertel 6354: return undef;
1.288 albertel 6355: }
1.73 www 6356: my $filename=$uri;
6357: $uri=~s/\.meta$//;
1.172 www 6358: #
6359: # Is the metadata already cached?
1.177 www 6360: # Look at timestamp of caching
1.172 www 6361: # Everything is cached by the main uri, libraries are never directly cached
6362: #
1.428 albertel 6363: if (!defined($liburi)) {
1.599 albertel 6364: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 6365: if (defined($cached)) { return $result->{':'.$what}; }
6366: }
6367: {
1.172 www 6368: #
6369: # Is this a recursive call for a library?
6370: #
1.599 albertel 6371: # if (! exists($metacache{$uri})) {
6372: # $metacache{$uri}={};
6373: # }
1.171 www 6374: if ($liburi) {
6375: $liburi=&declutter($liburi);
6376: $filename=$liburi;
1.401 bowersj2 6377: } else {
1.599 albertel 6378: &devalidate_cache_new('meta',$uri);
6379: undef(%metaentry);
1.401 bowersj2 6380: }
1.140 www 6381: my %metathesekeys=();
1.73 www 6382: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 6383: my $metastring;
1.768 albertel 6384: if ($uri !~ m -^(editupload)/-) {
1.543 albertel 6385: my $file=&filelocation('',&clutter($filename));
1.599 albertel 6386: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 6387: $metastring=&getfile($file);
1.489 albertel 6388: }
1.208 albertel 6389: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 6390: my $token;
1.140 www 6391: undef %metathesekeys;
1.71 www 6392: while ($token=$parser->get_token) {
1.339 albertel 6393: if ($token->[0] eq 'S') {
6394: if (defined($token->[2]->{'package'})) {
1.172 www 6395: #
6396: # This is a package - get package info
6397: #
1.339 albertel 6398: my $package=$token->[2]->{'package'};
6399: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6400: if (defined($token->[2]->{'id'})) {
6401: $keyroot.='_'.$token->[2]->{'id'};
6402: }
1.599 albertel 6403: if ($metaentry{':packages'}) {
6404: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 6405: } else {
1.599 albertel 6406: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 6407: }
1.736 albertel 6408: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 6409: my $part=$keyroot;
6410: $part=~s/^\_//;
1.736 albertel 6411: if ($pack_entry=~/^\Q$package\E\&/ ||
6412: $pack_entry=~/^\Q$package\E_0\&/) {
6413: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 6414: # ignore package.tab specified default values
6415: # here &package_tab_default() will fetch those
6416: if ($subp eq 'default') { next; }
1.736 albertel 6417: my $value=$packagetab{$pack_entry};
1.432 albertel 6418: my $unikey;
6419: if ($pack =~ /_0$/) {
6420: $unikey='parameter_0_'.$name;
6421: $part=0;
6422: } else {
6423: $unikey='parameter'.$keyroot.'_'.$name;
6424: }
1.339 albertel 6425: if ($subp eq 'display') {
6426: $value.=' [Part: '.$part.']';
6427: }
1.599 albertel 6428: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 6429: $metathesekeys{$unikey}=1;
1.599 albertel 6430: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6431: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 6432: }
1.599 albertel 6433: if (defined($metaentry{':'.$unikey.'.default'})) {
6434: $metaentry{':'.$unikey}=
6435: $metaentry{':'.$unikey.'.default'};
1.356 albertel 6436: }
1.339 albertel 6437: }
6438: }
6439: } else {
1.172 www 6440: #
6441: # This is not a package - some other kind of start tag
1.339 albertel 6442: #
6443: my $entry=$token->[1];
6444: my $unikey;
6445: if ($entry eq 'import') {
6446: $unikey='';
6447: } else {
6448: $unikey=$entry;
6449: }
6450: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6451:
6452: if (defined($token->[2]->{'id'})) {
6453: $unikey.='_'.$token->[2]->{'id'};
6454: }
1.175 www 6455:
1.339 albertel 6456: if ($entry eq 'import') {
1.175 www 6457: #
6458: # Importing a library here
1.339 albertel 6459: #
6460: if ($depthcount<20) {
6461: my $location=$parser->get_text('/import');
6462: my $dir=$filename;
6463: $dir=~s|[^/]*$||;
6464: $location=&filelocation($dir,$location);
1.736 albertel 6465: my $metadata =
6466: &metadata($uri,'keys', $location,$unikey,
6467: $depthcount+1);
6468: foreach my $meta (split(',',$metadata)) {
6469: $metaentry{':'.$meta}=$metaentry{':'.$meta};
6470: $metathesekeys{$meta}=1;
1.339 albertel 6471: }
6472: }
6473: } else {
6474:
6475: if (defined($token->[2]->{'name'})) {
6476: $unikey.='_'.$token->[2]->{'name'};
6477: }
6478: $metathesekeys{$unikey}=1;
1.736 albertel 6479: foreach my $param (@{$token->[3]}) {
6480: $metaentry{':'.$unikey.'.'.$param} =
6481: $token->[2]->{$param};
1.339 albertel 6482: }
6483: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 6484: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 6485: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
6486: # only ws inside the tag, and not in default, so use default
6487: # as value
1.599 albertel 6488: $metaentry{':'.$unikey}=$default;
1.339 albertel 6489: } else {
1.321 albertel 6490: # either something interesting inside the tag or default
6491: # uninteresting
1.599 albertel 6492: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 6493: }
1.172 www 6494: # end of not-a-package not-a-library import
1.339 albertel 6495: }
1.172 www 6496: # end of not-a-package start tag
1.339 albertel 6497: }
1.172 www 6498: # the next is the end of "start tag"
1.339 albertel 6499: }
6500: }
1.483 albertel 6501: my ($extension) = ($uri =~ /\.(\w+)$/);
1.737 albertel 6502: foreach my $key (keys(%packagetab)) {
1.483 albertel 6503: #no specific packages #how's our extension
6504: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 6505: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 6506: \%metathesekeys);
6507: }
1.599 albertel 6508: if (!exists($metaentry{':packages'})) {
1.737 albertel 6509: foreach my $key (keys(%packagetab)) {
1.483 albertel 6510: #no specific packages well let's get default then
6511: if ($key!~/^default&/) { next; }
1.488 albertel 6512: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 6513: \%metathesekeys);
6514: }
6515: }
1.338 www 6516: # are there custom rights to evaluate
1.599 albertel 6517: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 6518:
1.338 www 6519: #
6520: # Importing a rights file here
1.339 albertel 6521: #
6522: unless ($depthcount) {
1.599 albertel 6523: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 6524: my $dir=$filename;
6525: $dir=~s|[^/]*$||;
6526: $location=&filelocation($dir,$location);
1.736 albertel 6527: my $rights_metadata =
6528: &metadata($uri,'keys',$location,'_rights',
6529: $depthcount+1);
6530: foreach my $rights (split(',',$rights_metadata)) {
6531: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
6532: $metathesekeys{$rights}=1;
1.339 albertel 6533: }
6534: }
6535: }
1.737 albertel 6536: # uniqifiy package listing
6537: my %seen;
6538: my @uniq_packages =
6539: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
6540: $metaentry{':packages'} = join(',',@uniq_packages);
6541:
6542: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 6543: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
6544: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699 albertel 6545: &do_cache_new('meta',$uri,\%metaentry,60*60);
1.177 www 6546: # this is the end of "was not already recently cached
1.71 www 6547: }
1.599 albertel 6548: return $metaentry{':'.$what};
1.261 albertel 6549: }
6550:
1.488 albertel 6551: sub metadata_create_package_def {
1.483 albertel 6552: my ($uri,$key,$package,$metathesekeys)=@_;
6553: my ($pack,$name,$subp)=split(/\&/,$key);
6554: if ($subp eq 'default') { next; }
6555:
1.599 albertel 6556: if (defined($metaentry{':packages'})) {
6557: $metaentry{':packages'}.=','.$package;
1.483 albertel 6558: } else {
1.599 albertel 6559: $metaentry{':packages'}=$package;
1.483 albertel 6560: }
6561: my $value=$packagetab{$key};
6562: my $unikey;
6563: $unikey='parameter_0_'.$name;
1.599 albertel 6564: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 6565: $$metathesekeys{$unikey}=1;
1.599 albertel 6566: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6567: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 6568: }
1.599 albertel 6569: if (defined($metaentry{':'.$unikey.'.default'})) {
6570: $metaentry{':'.$unikey}=
6571: $metaentry{':'.$unikey.'.default'};
1.483 albertel 6572: }
6573: }
6574:
1.261 albertel 6575: sub metadata_generate_part0 {
6576: my ($metadata,$metacache,$uri) = @_;
6577: my %allnames;
1.737 albertel 6578: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 6579: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 6580: my $part=$$metacache{':'.$metakey.'.part'};
6581: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 6582: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 6583: $allnames{$name}=$part;
6584: }
6585: }
6586: }
6587: foreach my $name (keys(%allnames)) {
6588: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 6589: my $key=":parameter_0_$name";
1.261 albertel 6590: $$metacache{"$key.part"}='0';
6591: $$metacache{"$key.name"}=$name;
1.428 albertel 6592: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 6593: $allnames{$name}.'_'.$name.
6594: '.type'};
1.428 albertel 6595: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 6596: '.display'};
1.644 www 6597: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 6598: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 6599: $$metacache{"$key.display"}=$olddis;
6600: }
1.71 www 6601: }
6602:
1.764 albertel 6603: # ------------------------------------------------------ Devalidate title cache
6604:
6605: sub devalidate_title_cache {
6606: my ($url)=@_;
6607: if (!$env{'request.course.id'}) { return; }
6608: my $symb=&symbread($url);
6609: if (!$symb) { return; }
6610: my $key=$env{'request.course.id'}."\0".$symb;
6611: &devalidate_cache_new('title',$key);
6612: }
6613:
1.301 www 6614: # ------------------------------------------------- Get the title of a resource
6615:
6616: sub gettitle {
6617: my $urlsymb=shift;
6618: my $symb=&symbread($urlsymb);
1.534 albertel 6619: if ($symb) {
1.620 albertel 6620: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 6621: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 6622: if (defined($cached)) {
6623: return $result;
6624: }
1.534 albertel 6625: my ($map,$resid,$url)=&decode_symb($symb);
6626: my $title='';
6627: my %bighash;
1.620 albertel 6628: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534 albertel 6629: &GDBM_READER(),0640)) {
6630: my $mapid=$bighash{'map_pc_'.&clutter($map)};
6631: $title=$bighash{'title_'.$mapid.'.'.$resid};
6632: untie %bighash;
6633: }
6634: $title=~s/\&colon\;/\:/gs;
6635: if ($title) {
1.599 albertel 6636: return &do_cache_new('title',$key,$title,600);
1.534 albertel 6637: }
6638: $urlsymb=$url;
6639: }
6640: my $title=&metadata($urlsymb,'title');
6641: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
6642: return $title;
1.301 www 6643: }
1.613 albertel 6644:
1.614 albertel 6645: sub get_slot {
6646: my ($which,$cnum,$cdom)=@_;
6647: if (!$cnum || !$cdom) {
1.790 albertel 6648: (undef,my $courseid)=&whichuser();
1.620 albertel 6649: $cdom=$env{'course.'.$courseid.'.domain'};
6650: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 6651: }
1.703 albertel 6652: my $key=join("\0",'slots',$cdom,$cnum,$which);
6653: my %slotinfo;
6654: if (exists($remembered{$key})) {
6655: $slotinfo{$which} = $remembered{$key};
6656: } else {
6657: %slotinfo=&get('slots',[$which],$cdom,$cnum);
6658: &Apache::lonhomework::showhash(%slotinfo);
6659: my ($tmp)=keys(%slotinfo);
6660: if ($tmp=~/^error:/) { return (); }
6661: $remembered{$key} = $slotinfo{$which};
6662: }
1.616 albertel 6663: if (ref($slotinfo{$which}) eq 'HASH') {
6664: return %{$slotinfo{$which}};
6665: }
6666: return $slotinfo{$which};
1.614 albertel 6667: }
1.31 www 6668: # ------------------------------------------------- Update symbolic store links
6669:
6670: sub symblist {
6671: my ($mapname,%newhash)=@_;
1.438 www 6672: $mapname=&deversion(&declutter($mapname));
1.31 www 6673: my %hash;
1.620 albertel 6674: if (($env{'request.course.fn'}) && (%newhash)) {
6675: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 6676: &GDBM_WRCREAT(),0640)) {
1.711 albertel 6677: foreach my $url (keys %newhash) {
6678: next if ($url eq 'last_known'
6679: && $env{'form.no_update_last_known'});
6680: $hash{declutter($url)}=&encode_symb($mapname,
6681: $newhash{$url}->[1],
6682: $newhash{$url}->[0]);
1.191 harris41 6683: }
1.31 www 6684: if (untie(%hash)) {
6685: return 'ok';
6686: }
6687: }
6688: }
6689: return 'error';
1.212 www 6690: }
6691:
6692: # --------------------------------------------------------------- Verify a symb
6693:
6694: sub symbverify {
1.510 www 6695: my ($symb,$thisurl)=@_;
6696: my $thisfn=$thisurl;
1.439 www 6697: $thisfn=&declutter($thisfn);
1.215 www 6698: # direct jump to resource in page or to a sequence - will construct own symbs
6699: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
6700: # check URL part
1.409 www 6701: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 6702:
1.431 www 6703: unless ($url eq $thisfn) { return 0; }
1.213 www 6704:
1.216 www 6705: $symb=&symbclean($symb);
1.510 www 6706: $thisurl=&deversion($thisurl);
1.439 www 6707: $thisfn=&deversion($thisfn);
1.213 www 6708:
6709: my %bighash;
6710: my $okay=0;
1.431 www 6711:
1.620 albertel 6712: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 6713: &GDBM_READER(),0640)) {
1.510 www 6714: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 6715: unless ($ids) {
1.510 www 6716: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 6717: }
6718: if ($ids) {
6719: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 6720: foreach my $id (split(/\,/,$ids)) {
6721: my ($mapid,$resid)=split(/\./,$id);
1.216 www 6722: if (
6723: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
6724: eq $symb) {
1.620 albertel 6725: if (($env{'request.role.adv'}) ||
1.800 albertel 6726: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 6727: $okay=1;
6728: }
6729: }
1.216 www 6730: }
6731: }
1.213 www 6732: untie(%bighash);
6733: }
6734: return $okay;
1.31 www 6735: }
6736:
1.210 www 6737: # --------------------------------------------------------------- Clean-up symb
6738:
6739: sub symbclean {
6740: my $symb=shift;
1.568 albertel 6741: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 6742: # remove version from map
6743: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 6744:
1.210 www 6745: # remove version from URL
6746: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 6747:
1.507 www 6748: # remove wrapper
6749:
1.510 www 6750: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 6751: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 6752: return $symb;
1.409 www 6753: }
6754:
6755: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 6756:
6757: sub encode_symb {
6758: my ($map,$resid,$url)=@_;
6759: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
6760: }
1.409 www 6761:
6762: sub decode_symb {
1.568 albertel 6763: my $symb=shift;
6764: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
6765: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 6766: return (&fixversion($map),$resid,&fixversion($url));
6767: }
6768:
6769: sub fixversion {
6770: my $fn=shift;
1.609 banghart 6771: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 6772: my %bighash;
6773: my $uri=&clutter($fn);
1.620 albertel 6774: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 6775: # is this cached?
1.599 albertel 6776: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 6777: if (defined($cached)) { return $result; }
6778: # unfortunately not cached, or expired
1.620 albertel 6779: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 6780: &GDBM_READER(),0640)) {
6781: if ($bighash{'version_'.$uri}) {
6782: my $version=$bighash{'version_'.$uri};
1.444 www 6783: unless (($version eq 'mostrecent') ||
6784: ($version==&getversion($uri))) {
1.440 www 6785: $uri=~s/\.(\w+)$/\.$version\.$1/;
6786: }
6787: }
6788: untie %bighash;
1.413 www 6789: }
1.599 albertel 6790: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 6791: }
6792:
6793: sub deversion {
6794: my $url=shift;
6795: $url=~s/\.\d+\.(\w+)$/\.$1/;
6796: return $url;
1.210 www 6797: }
6798:
1.31 www 6799: # ------------------------------------------------------ Return symb list entry
6800:
6801: sub symbread {
1.249 www 6802: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 6803: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 6804: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 6805: # no filename provided? try from environment
1.44 www 6806: unless ($thisfn) {
1.620 albertel 6807: if ($env{'request.symb'}) {
6808: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 6809: }
1.620 albertel 6810: $thisfn=$env{'request.filename'};
1.44 www 6811: }
1.569 albertel 6812: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 6813: # is that filename actually a symb? Verify, clean, and return
6814: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 6815: if (&symbverify($thisfn,$1)) {
1.620 albertel 6816: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 6817: }
1.242 www 6818: }
1.44 www 6819: $thisfn=declutter($thisfn);
1.31 www 6820: my %hash;
1.37 www 6821: my %bighash;
6822: my $syval='';
1.620 albertel 6823: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 6824: my $targetfn = $thisfn;
1.609 banghart 6825: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 6826: $targetfn = 'adm/wrapper/'.$thisfn;
6827: }
1.687 albertel 6828: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
6829: $targetfn=$1;
6830: }
1.620 albertel 6831: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 6832: &GDBM_READER(),0640)) {
1.481 raeburn 6833: $syval=$hash{$targetfn};
1.37 www 6834: untie(%hash);
6835: }
6836: # ---------------------------------------------------------- There was an entry
6837: if ($syval) {
1.601 albertel 6838: #unless ($syval=~/\_\d+$/) {
1.620 albertel 6839: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601 albertel 6840: #&appenv('request.ambiguous' => $thisfn);
1.620 albertel 6841: #return $env{$cache_str}='';
1.601 albertel 6842: #}
6843: #$syval.=$1;
6844: #}
1.37 www 6845: } else {
6846: # ------------------------------------------------------- Was not in symb table
1.620 albertel 6847: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 6848: &GDBM_READER(),0640)) {
1.37 www 6849: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 6850: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 6851: unless ($ids) {
6852: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 6853: }
6854: unless ($ids) {
6855: # alias?
6856: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 6857: }
1.37 www 6858: if ($ids) {
6859: # ------------------------------------------------------------------- Has ID(s)
6860: my @possibilities=split(/\,/,$ids);
1.39 www 6861: if ($#possibilities==0) {
6862: # ----------------------------------------------- There is only one possibility
1.37 www 6863: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 6864: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6865: $resid,$thisfn);
1.249 www 6866: } elsif (!$donotrecurse) {
1.39 www 6867: # ------------------------------------------ There is more than one possibility
6868: my $realpossible=0;
1.800 albertel 6869: foreach my $id (@possibilities) {
6870: my $file=$bighash{'src_'.$id};
1.39 www 6871: if (&allowed('bre',$file)) {
1.800 albertel 6872: my ($mapid,$resid)=split(/\./,$id);
1.39 www 6873: if ($bighash{'map_type_'.$mapid} ne 'page') {
6874: $realpossible++;
1.626 albertel 6875: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6876: $resid,$thisfn);
1.39 www 6877: }
6878: }
1.191 harris41 6879: }
1.39 www 6880: if ($realpossible!=1) { $syval=''; }
1.249 www 6881: } else {
6882: $syval='';
1.37 www 6883: }
6884: }
6885: untie(%bighash)
1.481 raeburn 6886: }
1.31 www 6887: }
1.62 www 6888: if ($syval) {
1.620 albertel 6889: return $env{$cache_str}=$syval;
1.62 www 6890: }
1.31 www 6891: }
1.44 www 6892: &appenv('request.ambiguous' => $thisfn);
1.620 albertel 6893: return $env{$cache_str}='';
1.31 www 6894: }
6895:
6896: # ---------------------------------------------------------- Return random seed
6897:
1.32 www 6898: sub numval {
6899: my $txt=shift;
6900: $txt=~tr/A-J/0-9/;
6901: $txt=~tr/a-j/0-9/;
6902: $txt=~tr/K-T/0-9/;
6903: $txt=~tr/k-t/0-9/;
6904: $txt=~tr/U-Z/0-5/;
6905: $txt=~tr/u-z/0-5/;
6906: $txt=~s/\D//g;
1.564 albertel 6907: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 6908: return int($txt);
1.368 albertel 6909: }
6910:
1.484 albertel 6911: sub numval2 {
6912: my $txt=shift;
6913: $txt=~tr/A-J/0-9/;
6914: $txt=~tr/a-j/0-9/;
6915: $txt=~tr/K-T/0-9/;
6916: $txt=~tr/k-t/0-9/;
6917: $txt=~tr/U-Z/0-5/;
6918: $txt=~tr/u-z/0-5/;
6919: $txt=~s/\D//g;
6920: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6921: my $total;
6922: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 6923: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 6924: return int($total);
6925: }
6926:
1.575 albertel 6927: sub numval3 {
6928: use integer;
6929: my $txt=shift;
6930: $txt=~tr/A-J/0-9/;
6931: $txt=~tr/a-j/0-9/;
6932: $txt=~tr/K-T/0-9/;
6933: $txt=~tr/k-t/0-9/;
6934: $txt=~tr/U-Z/0-5/;
6935: $txt=~tr/u-z/0-5/;
6936: $txt=~s/\D//g;
6937: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6938: my $total;
6939: foreach my $val (@txts) { $total+=$val; }
6940: if ($_64bit) { $total=(($total<<32)>>32); }
6941: return $total;
6942: }
6943:
1.675 albertel 6944: sub digest {
6945: my ($data)=@_;
6946: my $digest=&Digest::MD5::md5($data);
6947: my ($a,$b,$c,$d)=unpack("iiii",$digest);
6948: my ($e,$f);
6949: {
6950: use integer;
6951: $e=($a+$b);
6952: $f=($c+$d);
6953: if ($_64bit) {
6954: $e=(($e<<32)>>32);
6955: $f=(($f<<32)>>32);
6956: }
6957: }
6958: if (wantarray) {
6959: return ($e,$f);
6960: } else {
6961: my $g;
6962: {
6963: use integer;
6964: $g=($e+$f);
6965: if ($_64bit) {
6966: $g=(($g<<32)>>32);
6967: }
6968: }
6969: return $g;
6970: }
6971: }
6972:
1.368 albertel 6973: sub latest_rnd_algorithm_id {
1.675 albertel 6974: return '64bit5';
1.366 albertel 6975: }
1.32 www 6976:
1.503 albertel 6977: sub get_rand_alg {
6978: my ($courseid)=@_;
1.790 albertel 6979: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 6980: if ($courseid) {
1.620 albertel 6981: return $env{"course.$courseid.rndseed"};
1.503 albertel 6982: }
6983: return &latest_rnd_algorithm_id();
6984: }
6985:
1.562 albertel 6986: sub validCODE {
6987: my ($CODE)=@_;
6988: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
6989: return 0;
6990: }
6991:
1.491 albertel 6992: sub getCODE {
1.620 albertel 6993: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 6994: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
6995: defined($Apache::lonhomework::parsing_a_task) ) &&
6996: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 6997: return $Apache::lonhomework::history{'resource.CODE'};
6998: }
6999: return undef;
7000: }
7001:
1.31 www 7002: sub rndseed {
1.155 albertel 7003: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 7004: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155 albertel 7005: if (!$symb) {
1.366 albertel 7006: unless ($symb=$wsymb) { return time; }
7007: }
7008: if (!$courseid) { $courseid=$wcourseid; }
7009: if (!$domain) { $domain=$wdomain; }
7010: if (!$username) { $username=$wusername }
1.503 albertel 7011: my $which=&get_rand_alg();
1.803 albertel 7012:
1.491 albertel 7013: if (defined(&getCODE())) {
1.675 albertel 7014: if ($which eq '64bit5') {
7015: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
7016: } elsif ($which eq '64bit4') {
1.575 albertel 7017: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
7018: } else {
7019: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
7020: }
1.675 albertel 7021: } elsif ($which eq '64bit5') {
7022: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 7023: } elsif ($which eq '64bit4') {
7024: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 7025: } elsif ($which eq '64bit3') {
7026: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 7027: } elsif ($which eq '64bit2') {
7028: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 7029: } elsif ($which eq '64bit') {
7030: return &rndseed_64bit($symb,$courseid,$domain,$username);
7031: }
7032: return &rndseed_32bit($symb,$courseid,$domain,$username);
7033: }
7034:
7035: sub rndseed_32bit {
7036: my ($symb,$courseid,$domain,$username)=@_;
7037: {
7038: use integer;
7039: my $symbchck=unpack("%32C*",$symb) << 27;
7040: my $symbseed=numval($symb) << 22;
7041: my $namechck=unpack("%32C*",$username) << 17;
7042: my $nameseed=numval($username) << 12;
7043: my $domainseed=unpack("%32C*",$domain) << 7;
7044: my $courseseed=unpack("%32C*",$courseid);
7045: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 7046: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7047: #&logthis("rndseed :$num:$symb");
1.564 albertel 7048: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 7049: return $num;
7050: }
7051: }
7052:
7053: sub rndseed_64bit {
7054: my ($symb,$courseid,$domain,$username)=@_;
7055: {
7056: use integer;
7057: my $symbchck=unpack("%32S*",$symb) << 21;
7058: my $symbseed=numval($symb) << 10;
7059: my $namechck=unpack("%32S*",$username);
7060:
7061: my $nameseed=numval($username) << 21;
7062: my $domainseed=unpack("%32S*",$domain) << 10;
7063: my $courseseed=unpack("%32S*",$courseid);
7064:
7065: my $num1=$symbchck+$symbseed+$namechck;
7066: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7067: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7068: #&logthis("rndseed :$num:$symb");
1.564 albertel 7069: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 7070: return "$num1,$num2";
1.155 albertel 7071: }
1.366 albertel 7072: }
7073:
1.443 albertel 7074: sub rndseed_64bit2 {
7075: my ($symb,$courseid,$domain,$username)=@_;
7076: {
7077: use integer;
7078: # strings need to be an even # of cahracters long, it it is odd the
7079: # last characters gets thrown away
7080: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7081: my $symbseed=numval($symb) << 10;
7082: my $namechck=unpack("%32S*",$username.' ');
7083:
7084: my $nameseed=numval($username) << 21;
1.501 albertel 7085: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7086: my $courseseed=unpack("%32S*",$courseid.' ');
7087:
7088: my $num1=$symbchck+$symbseed+$namechck;
7089: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7090: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7091: #&logthis("rndseed :$num:$symb");
1.803 albertel 7092: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 7093: return "$num1,$num2";
7094: }
7095: }
7096:
7097: sub rndseed_64bit3 {
7098: my ($symb,$courseid,$domain,$username)=@_;
7099: {
7100: use integer;
7101: # strings need to be an even # of cahracters long, it it is odd the
7102: # last characters gets thrown away
7103: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7104: my $symbseed=numval2($symb) << 10;
7105: my $namechck=unpack("%32S*",$username.' ');
7106:
7107: my $nameseed=numval2($username) << 21;
1.443 albertel 7108: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7109: my $courseseed=unpack("%32S*",$courseid.' ');
7110:
7111: my $num1=$symbchck+$symbseed+$namechck;
7112: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7113: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7114: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 7115: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7116:
1.503 albertel 7117: return "$num1:$num2";
1.443 albertel 7118: }
7119: }
7120:
1.575 albertel 7121: sub rndseed_64bit4 {
7122: my ($symb,$courseid,$domain,$username)=@_;
7123: {
7124: use integer;
7125: # strings need to be an even # of cahracters long, it it is odd the
7126: # last characters gets thrown away
7127: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7128: my $symbseed=numval3($symb) << 10;
7129: my $namechck=unpack("%32S*",$username.' ');
7130:
7131: my $nameseed=numval3($username) << 21;
7132: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7133: my $courseseed=unpack("%32S*",$courseid.' ');
7134:
7135: my $num1=$symbchck+$symbseed+$namechck;
7136: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7137: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7138: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 7139: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7140:
7141: return "$num1:$num2";
7142: }
7143: }
7144:
1.675 albertel 7145: sub rndseed_64bit5 {
7146: my ($symb,$courseid,$domain,$username)=@_;
7147: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
7148: return "$num1:$num2";
7149: }
7150:
1.366 albertel 7151: sub rndseed_CODE_64bit {
7152: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 7153: {
1.366 albertel 7154: use integer;
1.443 albertel 7155: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 7156: my $symbseed=numval2($symb);
1.491 albertel 7157: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7158: my $CODEseed=numval(&getCODE());
1.443 albertel 7159: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 7160: my $num1=$symbseed+$CODEchck;
7161: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7162: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7163: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 7164: if ($_64bit) { $num1=(($num1<<32)>>32); }
7165: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 7166: return "$num1:$num2";
1.366 albertel 7167: }
7168: }
7169:
1.575 albertel 7170: sub rndseed_CODE_64bit4 {
7171: my ($symb,$courseid,$domain,$username)=@_;
7172: {
7173: use integer;
7174: my $symbchck=unpack("%32S*",$symb.' ') << 16;
7175: my $symbseed=numval3($symb);
7176: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7177: my $CODEseed=numval3(&getCODE());
7178: my $courseseed=unpack("%32S*",$courseid.' ');
7179: my $num1=$symbseed+$CODEchck;
7180: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7181: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7182: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 7183: if ($_64bit) { $num1=(($num1<<32)>>32); }
7184: if ($_64bit) { $num2=(($num2<<32)>>32); }
7185: return "$num1:$num2";
7186: }
7187: }
7188:
1.675 albertel 7189: sub rndseed_CODE_64bit5 {
7190: my ($symb,$courseid,$domain,$username)=@_;
7191: my $code = &getCODE();
7192: my ($num1,$num2)=&digest("$symb,$courseid,$code");
7193: return "$num1:$num2";
7194: }
7195:
1.366 albertel 7196: sub setup_random_from_rndseed {
7197: my ($rndseed)=@_;
1.503 albertel 7198: if ($rndseed =~/([,:])/) {
7199: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 7200: &Math::Random::random_set_seed(abs($num1),abs($num2));
7201: } else {
7202: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 7203: }
1.36 albertel 7204: }
7205:
1.474 albertel 7206: sub latest_receipt_algorithm_id {
1.835 albertel 7207: return 'receipt3';
1.474 albertel 7208: }
7209:
1.480 www 7210: sub recunique {
7211: my $fucourseid=shift;
7212: my $unique;
1.835 albertel 7213: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
7214: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7215: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 7216: } else {
7217: $unique=$perlvar{'lonReceipt'};
7218: }
7219: return unpack("%32C*",$unique);
7220: }
7221:
7222: sub recprefix {
7223: my $fucourseid=shift;
7224: my $prefix;
1.835 albertel 7225: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
7226: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7227: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 7228: } else {
7229: $prefix=$perlvar{'lonHostID'};
7230: }
7231: return unpack("%32C*",$prefix);
7232: }
7233:
1.76 www 7234: sub ireceipt {
1.474 albertel 7235: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 7236:
7237: my $return =&recprefix($fucourseid).'-';
7238:
7239: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
7240: $env{'request.state'} eq 'construct') {
7241: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
7242: return $return;
7243: }
7244:
1.76 www 7245: my $cuname=unpack("%32C*",$funame);
7246: my $cudom=unpack("%32C*",$fudom);
7247: my $cucourseid=unpack("%32C*",$fucourseid);
7248: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 7249: my $cunique=&recunique($fucourseid);
1.474 albertel 7250: my $cpart=unpack("%32S*",$part);
1.835 albertel 7251: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
7252:
1.790 albertel 7253: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 7254:
7255: $return.= ($cunique%$cuname+
7256: $cunique%$cudom+
7257: $cusymb%$cuname+
7258: $cusymb%$cudom+
7259: $cucourseid%$cuname+
7260: $cucourseid%$cudom+
7261: $cpart%$cuname+
7262: $cpart%$cudom);
7263: } else {
7264: $return.= ($cunique%$cuname+
7265: $cunique%$cudom+
7266: $cusymb%$cuname+
7267: $cusymb%$cudom+
7268: $cucourseid%$cuname+
7269: $cucourseid%$cudom);
7270: }
7271: return $return;
1.76 www 7272: }
7273:
7274: sub receipt {
1.474 albertel 7275: my ($part)=@_;
1.790 albertel 7276: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 7277: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 7278: }
1.260 ng 7279:
1.790 albertel 7280: sub whichuser {
7281: my ($passedsymb)=@_;
7282: my ($symb,$courseid,$domain,$name,$publicuser);
7283: if (defined($env{'form.grade_symb'})) {
7284: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
7285: my $allowed=&allowed('vgr',$tmp_courseid);
7286: if (!$allowed &&
7287: exists($env{'request.course.sec'}) &&
7288: $env{'request.course.sec'} !~ /^\s*$/) {
7289: $allowed=&allowed('vgr',$tmp_courseid.
7290: '/'.$env{'request.course.sec'});
7291: }
7292: if ($allowed) {
7293: ($symb)=&get_env_multiple('form.grade_symb');
7294: $courseid=$tmp_courseid;
7295: ($domain)=&get_env_multiple('form.grade_domain');
7296: ($name)=&get_env_multiple('form.grade_username');
7297: return ($symb,$courseid,$domain,$name,$publicuser);
7298: }
7299: }
7300: if (!$passedsymb) {
7301: $symb=&symbread();
7302: } else {
7303: $symb=$passedsymb;
7304: }
7305: $courseid=$env{'request.course.id'};
7306: $domain=$env{'user.domain'};
7307: $name=$env{'user.name'};
7308: if ($name eq 'public' && $domain eq 'public') {
7309: if (!defined($env{'form.username'})) {
7310: $env{'form.username'}.=time.rand(10000000);
7311: }
7312: $name.=$env{'form.username'};
7313: }
7314: return ($symb,$courseid,$domain,$name,$publicuser);
7315:
7316: }
7317:
1.36 albertel 7318: # ------------------------------------------------------------ Serves up a file
1.472 albertel 7319: # returns either the contents of the file or
7320: # -1 if the file doesn't exist
1.481 raeburn 7321: #
7322: # if the target is a file that was uploaded via DOCS,
7323: # a check will be made to see if a current copy exists on the local server,
7324: # if it does this will be served, otherwise a copy will be retrieved from
7325: # the home server for the course and stored in /home/httpd/html/userfiles on
7326: # the local server.
1.472 albertel 7327:
1.36 albertel 7328: sub getfile {
1.538 albertel 7329: my ($file) = @_;
1.609 banghart 7330: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 7331: &repcopy($file);
7332: return &readfile($file);
7333: }
7334:
7335: sub repcopy_userfile {
7336: my ($file)=@_;
1.609 banghart 7337: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 7338: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 7339: my ($cdom,$cnum,$filename) =
1.811 albertel 7340: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 7341: my $uri="/uploaded/$cdom/$cnum/$filename";
7342: if (-e "$file") {
1.828 www 7343: # we already have a local copy, check it out
1.538 albertel 7344: my @fileinfo = stat($file);
1.828 www 7345: my $rtncode;
7346: my $info;
1.538 albertel 7347: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 7348: if ($lwpresp ne 'ok') {
1.828 www 7349: # there is no such file anymore, even though we had a local copy
1.482 albertel 7350: if ($rtncode eq '404') {
1.538 albertel 7351: unlink($file);
1.482 albertel 7352: }
7353: return -1;
7354: }
7355: if ($info < $fileinfo[9]) {
1.828 www 7356: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 7357: return 'ok';
1.828 www 7358: } else {
7359: # the file is outdated, get rid of it
7360: unlink($file);
1.482 albertel 7361: }
1.828 www 7362: }
7363: # one way or the other, at this point, we don't have the file
7364: # construct the correct path for the file
7365: my @parts = ($cdom,$cnum);
7366: if ($filename =~ m|^(.+)/[^/]+$|) {
7367: push @parts, split(/\//,$1);
7368: }
7369: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
7370: foreach my $part (@parts) {
7371: $path .= '/'.$part;
7372: if (!-e $path) {
7373: mkdir($path,0770);
1.482 albertel 7374: }
7375: }
1.828 www 7376: # now the path exists for sure
7377: # get a user agent
7378: my $ua=new LWP::UserAgent;
7379: my $transferfile=$file.'.in.transfer';
7380: # FIXME: this should flock
7381: if (-e $transferfile) { return 'ok'; }
7382: my $request;
7383: $uri=~s/^\///;
1.838 albertel 7384: $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828 www 7385: my $response=$ua->request($request,$transferfile);
7386: # did it work?
7387: if ($response->is_error()) {
7388: unlink($transferfile);
7389: &logthis("Userfile repcopy failed for $uri");
7390: return -1;
7391: }
7392: # worked, rename the transfer file
7393: rename($transferfile,$file);
1.607 raeburn 7394: return 'ok';
1.481 raeburn 7395: }
7396:
1.517 albertel 7397: sub tokenwrapper {
7398: my $uri=shift;
1.552 albertel 7399: $uri=~s|^http\://([^/]+)||;
7400: $uri=~s|^/||;
1.620 albertel 7401: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 7402: my $token=$1;
1.552 albertel 7403: my (undef,$udom,$uname,$file)=split('/',$uri,4);
7404: if ($udom && $uname && $file) {
7405: $file=~s|(\?\.*)*$||;
1.620 albertel 7406: &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838 albertel 7407: return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517 albertel 7408: (($uri=~/\?/)?'&':'?').'token='.$token.
7409: '&tokenissued='.$perlvar{'lonHostID'};
7410: } else {
7411: return '/adm/notfound.html';
7412: }
7413: }
7414:
1.828 www 7415: # call with reqtype HEAD: get last modification time
7416: # call with reqtype GET: get the file contents
7417: # Do not call this with reqtype GET for large files! It loads everything into memory
7418: #
1.481 raeburn 7419: sub getuploaded {
7420: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
7421: $uri=~s/^\///;
1.838 albertel 7422: $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481 raeburn 7423: my $ua=new LWP::UserAgent;
7424: my $request=new HTTP::Request($reqtype,$uri);
7425: my $response=$ua->request($request);
7426: $$rtncode = $response->code;
1.482 albertel 7427: if (! $response->is_success()) {
7428: return 'failed';
7429: }
7430: if ($reqtype eq 'HEAD') {
1.486 www 7431: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 7432: } elsif ($reqtype eq 'GET') {
7433: $$info = $response->content;
1.472 albertel 7434: }
1.482 albertel 7435: return 'ok';
1.36 albertel 7436: }
7437:
1.481 raeburn 7438: sub readfile {
7439: my $file = shift;
7440: if ( (! -e $file ) || ($file eq '') ) { return -1; };
7441: my $fh;
7442: open($fh,"<$file");
7443: my $a='';
1.800 albertel 7444: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 7445: return $a;
7446: }
7447:
1.36 albertel 7448: sub filelocation {
1.590 banghart 7449: my ($dir,$file) = @_;
7450: my $location;
7451: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 7452:
7453: if ($file =~ m-^/adm/-) {
7454: $file=~s-^/adm/wrapper/-/-;
7455: $file=~s-^/adm/coursedocs/showdoc/-/-;
7456: }
1.590 banghart 7457: if ($file=~m:^/~:) { # is a contruction space reference
7458: $location = $file;
7459: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 7460: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 7461: # is a correct contruction space reference
7462: $location = $file;
1.609 banghart 7463: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 7464: my ($udom,$uname,$filename)=
1.811 albertel 7465: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 7466: my $home=&homeserver($uname,$udom);
7467: my $is_me=0;
7468: my @ids=¤t_machine_ids();
7469: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
7470: if ($is_me) {
1.740 www 7471: $location=&propath($udom,$uname).
1.590 banghart 7472: '/userfiles/'.$filename;
7473: } else {
7474: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
7475: $udom.'/'.$uname.'/'.$filename;
7476: }
7477: } else {
7478: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
7479: $file=~s:^/res/:/:;
7480: if ( !( $file =~ m:^/:) ) {
7481: $location = $dir. '/'.$file;
7482: } else {
7483: $location = '/home/httpd/html/res'.$file;
7484: }
1.59 albertel 7485: }
1.590 banghart 7486: $location=~s://+:/:g; # remove duplicate /
7487: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
7488: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
7489: return $location;
1.46 www 7490: }
1.36 albertel 7491:
1.46 www 7492: sub hreflocation {
7493: my ($dir,$file)=@_;
1.460 albertel 7494: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666 albertel 7495: $file=filelocation($dir,$file);
1.700 albertel 7496: } elsif ($file=~m-^/adm/-) {
7497: $file=~s-^/adm/wrapper/-/-;
7498: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 7499: }
7500: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
7501: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 7502: } elsif ($file=~m-/home/($match_username)/public_html/-) {
7503: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 7504: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 7505: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 7506: -/uploaded/$1/$2/-x;
1.46 www 7507: }
1.462 albertel 7508: return $file;
1.465 albertel 7509: }
7510:
7511: sub current_machine_domains {
1.853 albertel 7512: return &machine_domains(&hostname($perlvar{'lonHostID'}));
7513: }
7514:
7515: sub machine_domains {
7516: my ($hostname) = @_;
1.465 albertel 7517: my @domains;
1.838 albertel 7518: my %hostname = &all_hostnames();
1.465 albertel 7519: while( my($id, $name) = each(%hostname)) {
1.467 matthew 7520: # &logthis("-$id-$name-$hostname-");
1.465 albertel 7521: if ($hostname eq $name) {
1.844 albertel 7522: push(@domains,&host_domain($id));
1.465 albertel 7523: }
7524: }
7525: return @domains;
7526: }
7527:
7528: sub current_machine_ids {
1.853 albertel 7529: return &machine_ids(&hostname($perlvar{'lonHostID'}));
7530: }
7531:
7532: sub machine_ids {
7533: my ($hostname) = @_;
7534: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 7535: my @ids;
1.838 albertel 7536: my %hostname = &all_hostnames();
1.465 albertel 7537: while( my($id, $name) = each(%hostname)) {
1.467 matthew 7538: # &logthis("-$id-$name-$hostname-");
1.465 albertel 7539: if ($hostname eq $name) {
7540: push(@ids,$id);
7541: }
7542: }
7543: return @ids;
1.31 www 7544: }
7545:
1.824 raeburn 7546: sub additional_machine_domains {
7547: my @domains;
7548: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
7549: while( my $line = <$fh>) {
7550: $line =~ s/\s//g;
7551: push(@domains,$line);
7552: }
7553: return @domains;
7554: }
7555:
7556: sub default_login_domain {
7557: my $domain = $perlvar{'lonDefDomain'};
7558: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
7559: foreach my $posdom (¤t_machine_domains(),
7560: &additional_machine_domains()) {
7561: if (lc($posdom) eq lc($testdomain)) {
7562: $domain=$posdom;
7563: last;
7564: }
7565: }
7566: return $domain;
7567: }
7568:
1.31 www 7569: # ------------------------------------------------------------- Declutters URLs
7570:
7571: sub declutter {
7572: my $thisfn=shift;
1.569 albertel 7573: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 7574: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 7575: $thisfn=~s/^\///;
1.697 albertel 7576: $thisfn=~s|^adm/wrapper/||;
7577: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 7578: $thisfn=~s/^res\///;
1.235 www 7579: $thisfn=~s/\?.+$//;
1.268 www 7580: return $thisfn;
7581: }
7582:
7583: # ------------------------------------------------------------- Clutter up URLs
7584:
7585: sub clutter {
7586: my $thisfn='/'.&declutter(shift);
1.609 banghart 7587: unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) {
1.270 www 7588: $thisfn='/res'.$thisfn;
7589: }
1.694 albertel 7590: if ($thisfn !~m|/adm|) {
1.695 albertel 7591: if ($thisfn =~ m|/ext/|) {
1.694 albertel 7592: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 7593: } else {
7594: my ($ext) = ($thisfn =~ /\.(\w+)$/);
7595: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 7596: if ($embstyle eq 'ssi'
7597: || ($embstyle eq 'hdn')
7598: || ($embstyle eq 'rat')
7599: || ($embstyle eq 'prv')
7600: || ($embstyle eq 'ign')) {
7601: #do nothing with these
7602: } elsif (($embstyle eq 'img')
1.695 albertel 7603: || ($embstyle eq 'emb')
7604: || ($embstyle eq 'wrp')) {
7605: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 7606: } elsif ($embstyle eq 'unk'
7607: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 7608: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 7609: } else {
1.718 www 7610: # &logthis("Got a blank emb style");
1.695 albertel 7611: }
1.694 albertel 7612: }
7613: }
1.31 www 7614: return $thisfn;
1.12 www 7615: }
7616:
1.787 albertel 7617: sub clutter_with_no_wrapper {
7618: my $uri = &clutter(shift);
7619: if ($uri =~ m-^/adm/-) {
7620: $uri =~ s-^/adm/wrapper/-/-;
7621: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
7622: }
7623: return $uri;
7624: }
7625:
1.557 albertel 7626: sub freeze_escape {
7627: my ($value)=@_;
7628: if (ref($value)) {
7629: $value=&nfreeze($value);
7630: return '__FROZEN__'.&escape($value);
7631: }
7632: return &escape($value);
7633: }
7634:
1.11 www 7635:
1.557 albertel 7636: sub thaw_unescape {
7637: my ($value)=@_;
7638: if ($value =~ /^__FROZEN__/) {
7639: substr($value,0,10,undef);
7640: $value=&unescape($value);
7641: return &thaw($value);
7642: }
7643: return &unescape($value);
7644: }
7645:
1.436 albertel 7646: sub correct_line_ends {
7647: my ($result)=@_;
7648: $$result =~s/\r\n/\n/mg;
7649: $$result =~s/\r/\n/mg;
1.415 albertel 7650: }
1.1 albertel 7651: # ================================================================ Main Program
7652:
1.184 www 7653: sub goodbye {
1.204 albertel 7654: &logthis("Starting Shut down");
1.443 albertel 7655: #not converted to using infrastruture and probably shouldn't be
1.599 albertel 7656: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443 albertel 7657: #converted
1.599 albertel 7658: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
7659: &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
7660: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
7661: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425 albertel 7662: #1.1 only
1.599 albertel 7663: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
7664: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
7665: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
7666: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
7667: &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
7668: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
7669: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 7670: &flushcourselogs();
7671: &logthis("Shutting down");
7672: }
7673:
1.852 albertel 7674: sub get_dns {
7675: my ($url,$func) = @_;
7676: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
7677: foreach my $dns (<$config>) {
7678: next if ($dns !~ /^\^(\S*)/x);
7679: $dns = $1;
7680: my $ua=new LWP::UserAgent;
7681: my $request=new HTTP::Request('GET',"http://$dns$url");
7682: my $response=$ua->request($request);
7683: next if ($response->is_error());
7684: my @content = split("\n",$response->content);
7685: &$func(\@content);
7686: }
7687: close($config);
7688: }
1.327 albertel 7689: # ------------------------------------------------------------ Read domain file
7690: {
1.852 albertel 7691: my $loaded;
1.846 albertel 7692: my %domain;
7693:
1.852 albertel 7694: sub parse_domain_tab {
7695: my ($lines) = @_;
7696: foreach my $line (@$lines) {
7697: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 7698:
1.846 albertel 7699: chomp($line);
1.852 albertel 7700: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 7701: my %this_domain;
7702: foreach my $field ('description', 'auth_def', 'auth_arg_def',
7703: 'lang_def', 'city', 'longi', 'lati',
7704: 'primary') {
7705: $this_domain{$field} = shift(@elements);
7706: }
7707: $domain{$name} = \%this_domain;
1.852 albertel 7708: }
7709: }
1.864 albertel 7710:
7711: sub reset_domain_info {
7712: undef($loaded);
7713: undef(%domain);
7714: }
7715:
1.852 albertel 7716: sub load_domain_tab {
7717: &get_dns('/adm/dns/domain',\&parse_domain_tab);
7718: my $fh;
7719: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
7720: my @lines = <$fh>;
7721: &parse_domain_tab(\@lines);
1.448 albertel 7722: }
1.852 albertel 7723: close($fh);
7724: $loaded = 1;
1.327 albertel 7725: }
1.846 albertel 7726:
7727: sub domain {
1.852 albertel 7728: &load_domain_tab() if (!$loaded);
7729:
1.846 albertel 7730: my ($name,$what) = @_;
7731: return if ( !exists($domain{$name}) );
7732:
7733: if (!$what) {
7734: return $domain{$name}{'description'};
7735: }
7736: return $domain{$name}{$what};
7737: }
1.327 albertel 7738: }
7739:
7740:
1.1 albertel 7741: # ------------------------------------------------------------- Read hosts file
7742: {
1.838 albertel 7743: my %hostname;
1.844 albertel 7744: my %hostdom;
1.845 albertel 7745: my %libserv;
1.852 albertel 7746: my $loaded;
7747:
7748: sub parse_hosts_tab {
7749: my ($file) = @_;
7750: foreach my $configline (@$file) {
7751: next if ($configline =~ /^(\#|\s*$ )/x);
7752: next if ($configline =~ /^\^/);
7753: chomp($configline);
7754: my ($id,$domain,$role,$name)=split(/:/,$configline);
7755: $name=~s/\s//g;
7756: if ($id && $domain && $role && $name) {
7757: $hostname{$id}=$name;
7758: $hostdom{$id}=$domain;
7759: if ($role eq 'library') { $libserv{$id}=$name; }
7760: }
7761: }
7762: }
1.864 albertel 7763:
7764: sub reset_hosts_info {
7765: &reset_domain_info();
7766: &reset_hosts_ip_info();
7767: undef(%hostname);
7768: undef(%hostdom);
7769: undef(%libserv);
7770: undef($loaded);
7771: }
1.1 albertel 7772:
1.852 albertel 7773: sub load_hosts_tab {
7774: &get_dns('/adm/dns/hosts',\&parse_hosts_tab);
7775: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
7776: my @config = <$config>;
7777: &parse_hosts_tab(\@config);
7778: close($config);
7779: $loaded=1;
1.1 albertel 7780: }
1.852 albertel 7781:
1.838 albertel 7782: sub hostname {
1.852 albertel 7783: &load_hosts_tab() if (!$loaded);
7784:
1.838 albertel 7785: my ($lonid) = @_;
7786: return $hostname{$lonid};
7787: }
1.845 albertel 7788:
1.838 albertel 7789: sub all_hostnames {
1.852 albertel 7790: &load_hosts_tab() if (!$loaded);
7791:
1.838 albertel 7792: return %hostname;
7793: }
1.845 albertel 7794:
7795: sub is_library {
1.852 albertel 7796: &load_hosts_tab() if (!$loaded);
7797:
1.845 albertel 7798: return exists($libserv{$_[0]});
7799: }
7800:
7801: sub all_library {
1.852 albertel 7802: &load_hosts_tab() if (!$loaded);
7803:
1.845 albertel 7804: return %libserv;
7805: }
7806:
1.841 albertel 7807: sub get_servers {
1.852 albertel 7808: &load_hosts_tab() if (!$loaded);
7809:
1.841 albertel 7810: my ($domain,$type) = @_;
7811: my %possible_hosts = ($type eq 'library') ? %libserv
7812: : %hostname;
7813: my %result;
1.842 albertel 7814: if (ref($domain) eq 'ARRAY') {
7815: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 7816: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 7817: $result{$host} = $hostname;
7818: }
7819: }
7820: } else {
7821: while ( my ($host,$hostname) = each(%possible_hosts)) {
7822: if ($hostdom{$host} eq $domain) {
7823: $result{$host} = $hostname;
7824: }
1.841 albertel 7825: }
7826: }
7827: return %result;
7828: }
1.845 albertel 7829:
1.844 albertel 7830: sub host_domain {
1.852 albertel 7831: &load_hosts_tab() if (!$loaded);
7832:
1.844 albertel 7833: my ($lonid) = @_;
7834: return $hostdom{$lonid};
7835: }
7836:
1.841 albertel 7837: sub all_domains {
1.852 albertel 7838: &load_hosts_tab() if (!$loaded);
7839:
1.841 albertel 7840: my %seen;
7841: my @uniq = grep(!$seen{$_}++, values(%hostdom));
7842: return @uniq;
7843: }
1.1 albertel 7844: }
7845:
1.847 albertel 7846: {
7847: my %iphost;
1.856 albertel 7848: my %name_to_ip;
7849: my %lonid_to_ip;
1.847 albertel 7850: sub get_hosts_from_ip {
7851: my ($ip) = @_;
7852: my %iphosts = &get_iphost();
7853: if (ref($iphosts{$ip})) {
7854: return @{$iphosts{$ip}};
7855: }
7856: return;
1.839 albertel 7857: }
1.864 albertel 7858:
7859: sub reset_hosts_ip_info {
7860: undef(%iphost);
7861: undef(%name_to_ip);
7862: undef(%lonid_to_ip);
7863: }
1.856 albertel 7864:
7865: sub get_host_ip {
7866: my ($lonid) = @_;
7867: if (exists($lonid_to_ip{$lonid})) {
7868: return $lonid_to_ip{$lonid};
7869: }
7870: my $name=&hostname($lonid);
7871: my $ip = gethostbyname($name);
7872: return if (!$ip || length($ip) ne 4);
7873: $ip=inet_ntoa($ip);
7874: $name_to_ip{$name} = $ip;
7875: $lonid_to_ip{$lonid} = $ip;
7876: return $ip;
7877: }
1.847 albertel 7878:
7879: sub get_iphost {
7880: if (%iphost) { return %iphost; }
7881: my %hostname = &all_hostnames();
7882: foreach my $id (keys(%hostname)) {
1.864 albertel 7883: my $name=&hostname($id);
1.847 albertel 7884: my $ip;
7885: if (!exists($name_to_ip{$name})) {
7886: $ip = gethostbyname($name);
7887: if (!$ip || length($ip) ne 4) {
7888: &logthis("Skipping host $id name $name no IP found");
7889: next;
7890: }
7891: $ip=inet_ntoa($ip);
7892: $name_to_ip{$name} = $ip;
7893: } else {
7894: $ip = $name_to_ip{$name};
1.653 albertel 7895: }
1.856 albertel 7896: $lonid_to_ip{$id} = $ip;
1.847 albertel 7897: push(@{$iphost{$ip}},$id);
1.598 albertel 7898: }
1.847 albertel 7899: return %iphost;
1.598 albertel 7900: }
7901: }
7902:
1.862 albertel 7903: BEGIN {
7904:
7905: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
7906: unless ($readit) {
7907: {
7908: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
7909: %perlvar = (%perlvar,%{$configvars});
7910: }
7911:
7912:
1.1 albertel 7913: # ------------------------------------------------------ Read spare server file
7914: {
1.448 albertel 7915: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 7916:
7917: while (my $configline=<$config>) {
7918: chomp($configline);
1.284 matthew 7919: if ($configline) {
1.784 albertel 7920: my ($host,$type) = split(':',$configline,2);
1.785 albertel 7921: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 7922: push(@{ $spareid{$type} }, $host);
1.1 albertel 7923: }
7924: }
1.448 albertel 7925: close($config);
1.1 albertel 7926: }
1.11 www 7927: # ------------------------------------------------------------ Read permissions
7928: {
1.448 albertel 7929: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 7930:
7931: while (my $configline=<$config>) {
1.448 albertel 7932: chomp($configline);
7933: if ($configline) {
7934: my ($role,$perm)=split(/ /,$configline);
7935: if ($perm ne '') { $pr{$role}=$perm; }
7936: }
1.11 www 7937: }
1.448 albertel 7938: close($config);
1.11 www 7939: }
7940:
7941: # -------------------------------------------- Read plain texts for permissions
7942: {
1.448 albertel 7943: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 7944:
7945: while (my $configline=<$config>) {
1.448 albertel 7946: chomp($configline);
7947: if ($configline) {
1.742 raeburn 7948: my ($short,@plain)=split(/:/,$configline);
7949: %{$prp{$short}} = ();
7950: if (@plain > 0) {
7951: $prp{$short}{'std'} = $plain[0];
7952: for (my $i=1; $i<@plain; $i++) {
7953: $prp{$short}{'alt'.$i} = $plain[$i];
7954: }
7955: }
1.448 albertel 7956: }
1.135 www 7957: }
1.448 albertel 7958: close($config);
1.135 www 7959: }
7960:
7961: # ---------------------------------------------------------- Read package table
7962: {
1.448 albertel 7963: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 7964:
7965: while (my $configline=<$config>) {
1.483 albertel 7966: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 7967: chomp($configline);
7968: my ($short,$plain)=split(/:/,$configline);
7969: my ($pack,$name)=split(/\&/,$short);
7970: if ($plain ne '') {
7971: $packagetab{$pack.'&'.$name.'&name'}=$name;
7972: $packagetab{$short}=$plain;
7973: }
1.11 www 7974: }
1.448 albertel 7975: close($config);
1.329 matthew 7976: }
7977:
7978: # ------------- set up temporary directory
7979: {
7980: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
7981:
1.11 www 7982: }
7983:
1.794 albertel 7984: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
7985: 'compress_threshold'=> 20_000,
7986: });
1.185 www 7987:
1.281 www 7988: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 7989: $dumpcount=0;
1.22 www 7990:
1.163 harris41 7991: &logtouch();
1.672 albertel 7992: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 7993: $readit=1;
1.564 albertel 7994: {
7995: use integer;
7996: my $test=(2**32)+1;
1.568 albertel 7997: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 7998: &logthis(" Detected 64bit platform ($_64bit)");
7999: }
1.195 www 8000: }
1.1 albertel 8001: }
1.179 www 8002:
1.1 albertel 8003: 1;
1.191 harris41 8004: __END__
8005:
1.243 albertel 8006: =pod
8007:
1.191 harris41 8008: =head1 NAME
8009:
1.243 albertel 8010: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 8011:
8012: =head1 SYNOPSIS
8013:
1.243 albertel 8014: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 8015:
8016: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
8017:
1.243 albertel 8018: Common parameters:
8019:
8020: =over 4
8021:
8022: =item *
8023:
8024: $uname : an internal username (if $cname expecting a course Id specifically)
8025:
8026: =item *
8027:
8028: $udom : a domain (if $cdom expecting a course's domain specifically)
8029:
8030: =item *
8031:
8032: $symb : a resource instance identifier
8033:
8034: =item *
8035:
8036: $namespace : the name of a .db file that contains the data needed or
8037: being set.
8038:
8039: =back
8040:
1.394 bowersj2 8041: =head1 OVERVIEW
1.191 harris41 8042:
1.394 bowersj2 8043: lonnet provides subroutines which interact with the
8044: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
8045: about classes, users, and resources.
1.243 albertel 8046:
8047: For many of these objects you can also use this to store data about
8048: them or modify them in various ways.
1.191 harris41 8049:
1.394 bowersj2 8050: =head2 Symbs
1.191 harris41 8051:
1.394 bowersj2 8052: To identify a specific instance of a resource, LON-CAPA uses symbols
8053: or "symbs"X<symb>. These identifiers are built from the URL of the
8054: map, the resource number of the resource in the map, and the URL of
8055: the resource itself. The latter is somewhat redundant, but might help
8056: if maps change.
8057:
8058: An example is
8059:
8060: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
8061:
8062: The respective map entry is
8063:
8064: <resource id="19" src="/res/msu/korte/tests/part12.problem"
8065: title="Problem 2">
8066: </resource>
8067:
8068: Symbs are used by the random number generator, as well as to store and
8069: restore data specific to a certain instance of for example a problem.
8070:
8071: =head2 Storing And Retrieving Data
8072:
8073: X<store()>X<cstore()>X<restore()>Three of the most important functions
8074: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
8075: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
8076: is is the non-critical message twin of cstore. These functions are for
8077: handlers to store a perl hash to a user's permanent data space in an
8078: easy manner, and to retrieve it again on another call. It is expected
8079: that a handler would use this once at the beginning to retrieve data,
8080: and then again once at the end to send only the new data back.
8081:
8082: The data is stored in the user's data directory on the user's
8083: homeserver under the ID of the course.
8084:
8085: The hash that is returned by restore will have all of the previous
8086: value for all of the elements of the hash.
8087:
8088: Example:
8089:
8090: #creating a hash
8091: my %hash;
8092: $hash{'foo'}='bar';
8093:
8094: #storing it
8095: &Apache::lonnet::cstore(\%hash);
8096:
8097: #changing a value
8098: $hash{'foo'}='notbar';
8099:
8100: #adding a new value
8101: $hash{'bar'}='foo';
8102: &Apache::lonnet::cstore(\%hash);
8103:
8104: #retrieving the hash
8105: my %history=&Apache::lonnet::restore();
8106:
8107: #print the hash
8108: foreach my $key (sort(keys(%history))) {
8109: print("\%history{$key} = $history{$key}");
8110: }
8111:
8112: Will print out:
1.191 harris41 8113:
1.394 bowersj2 8114: %history{1:foo} = bar
8115: %history{1:keys} = foo:timestamp
8116: %history{1:timestamp} = 990455579
8117: %history{2:bar} = foo
8118: %history{2:foo} = notbar
8119: %history{2:keys} = foo:bar:timestamp
8120: %history{2:timestamp} = 990455580
8121: %history{bar} = foo
8122: %history{foo} = notbar
8123: %history{timestamp} = 990455580
8124: %history{version} = 2
8125:
8126: Note that the special hash entries C<keys>, C<version> and
8127: C<timestamp> were added to the hash. C<version> will be equal to the
8128: total number of versions of the data that have been stored. The
8129: C<timestamp> attribute will be the UNIX time the hash was
8130: stored. C<keys> is available in every historical section to list which
8131: keys were added or changed at a specific historical revision of a
8132: hash.
8133:
8134: B<Warning>: do not store the hash that restore returns directly. This
8135: will cause a mess since it will restore the historical keys as if the
8136: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 8137:
1.394 bowersj2 8138: Calling convention:
1.191 harris41 8139:
1.394 bowersj2 8140: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
8141: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 8142:
1.394 bowersj2 8143: For more detailed information, see lonnet specific documentation.
1.191 harris41 8144:
1.394 bowersj2 8145: =head1 RETURN MESSAGES
1.191 harris41 8146:
1.394 bowersj2 8147: =over 4
1.191 harris41 8148:
1.394 bowersj2 8149: =item * B<con_lost>: unable to contact remote host
1.191 harris41 8150:
1.394 bowersj2 8151: =item * B<con_delayed>: unable to contact remote host, message will be delivered
8152: when the connection is brought back up
1.191 harris41 8153:
1.394 bowersj2 8154: =item * B<con_failed>: unable to contact remote host and unable to save message
8155: for later delivery
1.191 harris41 8156:
1.394 bowersj2 8157: =item * B<error:>: an error a occured, a description of the error follows the :
1.191 harris41 8158:
1.394 bowersj2 8159: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 8160: that was requested
1.191 harris41 8161:
1.243 albertel 8162: =back
1.191 harris41 8163:
1.243 albertel 8164: =head1 PUBLIC SUBROUTINES
1.191 harris41 8165:
1.243 albertel 8166: =head2 Session Environment Functions
1.191 harris41 8167:
1.243 albertel 8168: =over 4
1.191 harris41 8169:
1.394 bowersj2 8170: =item *
8171: X<appenv()>
8172: B<appenv(%hash)>: the value of %hash is written to
8173: the user envirnoment file, and will be restored for each access this
1.620 albertel 8174: user makes during this session, also modifies the %env for the current
1.394 bowersj2 8175: process
1.191 harris41 8176:
8177: =item *
1.394 bowersj2 8178: X<delenv()>
8179: B<delenv($regexp)>: removes all items from the session
8180: environment file that matches the regular expression in $regexp. The
1.620 albertel 8181: values are also delted from the current processes %env.
1.191 harris41 8182:
1.795 albertel 8183: =item * get_env_multiple($name)
8184:
8185: gets $name from the %env hash, it seemlessly handles the cases where multiple
8186: values may be defined and end up as an array ref.
8187:
8188: returns an array of values
8189:
1.243 albertel 8190: =back
8191:
8192: =head2 User Information
1.191 harris41 8193:
1.243 albertel 8194: =over 4
1.191 harris41 8195:
8196: =item *
1.394 bowersj2 8197: X<queryauthenticate()>
8198: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 8199: authentication scheme
8200:
8201: =item *
1.394 bowersj2 8202: X<authenticate()>
8203: B<authenticate($uname,$upass,$udom)>: try to
8204: authenticate user from domain's lib servers (first use the current
8205: one). C<$upass> should be the users password.
1.191 harris41 8206:
8207: =item *
1.394 bowersj2 8208: X<homeserver()>
8209: B<homeserver($uname,$udom)>: find the server which has
8210: the user's directory and files (there must be only one), this caches
8211: the answer, and also caches if there is a borken connection.
1.191 harris41 8212:
8213: =item *
1.394 bowersj2 8214: X<idget()>
8215: B<idget($udom,@ids)>: find the usernames behind a list of IDs
8216: (IDs are a unique resource in a domain, there must be only 1 ID per
8217: username, and only 1 username per ID in a specific domain) (returns
8218: hash: id=>name,id=>name)
1.191 harris41 8219:
8220: =item *
1.394 bowersj2 8221: X<idrget()>
8222: B<idrget($udom,@unames)>: find the IDs behind a list of
8223: usernames (returns hash: name=>id,name=>id)
1.191 harris41 8224:
8225: =item *
1.394 bowersj2 8226: X<idput()>
8227: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 8228:
8229: =item *
1.394 bowersj2 8230: X<rolesinit()>
8231: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 8232:
8233: =item *
1.551 albertel 8234: X<getsection()>
8235: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 8236: course $cname, return section name/number or '' for "not in course"
8237: and '-1' for "no section"
8238:
8239: =item *
1.394 bowersj2 8240: X<userenvironment()>
8241: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 8242: passed in @what from the requested user's environment, returns a hash
8243:
1.858 raeburn 8244: =item *
8245: X<userlog_query()>
1.859 albertel 8246: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
8247: activity.log file. %filters defines filters applied when parsing the
8248: log file. These can be start or end timestamps, or the type of action
8249: - log to look for Login or Logout events, check for Checkin or
8250: Checkout, role for role selection. The response is in the form
8251: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
8252: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 8253:
1.243 albertel 8254: =back
8255:
8256: =head2 User Roles
8257:
8258: =over 4
8259:
8260: =item *
8261:
1.810 raeburn 8262: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 8263: F: full access
8264: U,I,K: authentication modes (cxx only)
8265: '': forbidden
8266: 1: user needs to choose course
8267: 2: browse allowed
1.766 albertel 8268: A: passphrase authentication needed
1.243 albertel 8269:
8270: =item *
8271:
8272: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
8273: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
8274: and course level
8275:
8276: =item *
8277:
8278: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
8279: explanation of a user role term
8280:
1.832 raeburn 8281: =item *
8282:
1.858 raeburn 8283: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
8284: All arguments are optional. Returns a hash of a roles, either for
8285: co-author/assistant author roles for a user's Construction Space
8286: (default), or if $context is 'user', roles for the user himself,
8287: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
8288: and value is set to colon-separated start and end times for the role.
8289: If no username and domain are specified, will default to current
8290: user/domain. Types, roles, and roledoms are references to arrays,
8291: of role statuses (active, future or previous), roles
8292: (e.g., cc,in, st etc.) and domains of the roles which can be used
8293: to restrict the list of roles reported. If no array ref is
8294: provided for types, will default to return only active roles.
1.834 albertel 8295:
1.243 albertel 8296: =back
8297:
8298: =head2 User Modification
8299:
8300: =over 4
8301:
8302: =item *
8303:
8304: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
8305: user for the level given by URL. Optional start and end dates (leave empty
8306: string or zero for "no date")
1.191 harris41 8307:
8308: =item *
8309:
1.243 albertel 8310: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
8311: change a users, password, possible return values are: ok,
8312: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
8313: refused
1.191 harris41 8314:
8315: =item *
8316:
1.243 albertel 8317: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 8318:
8319: =item *
8320:
1.243 albertel 8321: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
8322: modify user
1.191 harris41 8323:
8324: =item *
8325:
1.286 matthew 8326: modifystudent
8327:
8328: modify a students enrollment and identification information.
8329: The course id is resolved based on the current users environment.
8330: This means the envoking user must be a course coordinator or otherwise
8331: associated with a course.
8332:
1.297 matthew 8333: This call is essentially a wrapper for lonnet::modifyuser and
8334: lonnet::modify_student_enrollment
1.286 matthew 8335:
8336: Inputs:
8337:
8338: =over 4
8339:
8340: =item B<$udom> Students loncapa domain
8341:
8342: =item B<$uname> Students loncapa login name
8343:
8344: =item B<$uid> Students id/student number
8345:
8346: =item B<$umode> Students authentication mode
8347:
8348: =item B<$upass> Students password
8349:
8350: =item B<$first> Students first name
8351:
8352: =item B<$middle> Students middle name
8353:
8354: =item B<$last> Students last name
8355:
8356: =item B<$gene> Students generation
8357:
8358: =item B<$usec> Students section in course
8359:
8360: =item B<$end> Unix time of the roles expiration
8361:
8362: =item B<$start> Unix time of the roles start date
8363:
8364: =item B<$forceid> If defined, allow $uid to be changed
8365:
8366: =item B<$desiredhome> server to use as home server for student
8367:
8368: =back
1.297 matthew 8369:
8370: =item *
8371:
8372: modify_student_enrollment
8373:
8374: Change a students enrollment status in a class. The environment variable
8375: 'role.request.course' must be defined for this function to proceed.
8376:
8377: Inputs:
8378:
8379: =over 4
8380:
8381: =item $udom, students domain
8382:
8383: =item $uname, students name
8384:
8385: =item $uid, students user id
8386:
8387: =item $first, students first name
8388:
8389: =item $middle
8390:
8391: =item $last
8392:
8393: =item $gene
8394:
8395: =item $usec
8396:
8397: =item $end
8398:
8399: =item $start
8400:
8401: =back
8402:
1.191 harris41 8403:
8404: =item *
8405:
1.243 albertel 8406: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
8407: custom role; give a custom role to a user for the level given by URL. Specify
8408: name and domain of role author, and role name
1.191 harris41 8409:
8410: =item *
8411:
1.243 albertel 8412: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 8413:
8414: =item *
8415:
1.243 albertel 8416: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
8417:
8418: =back
8419:
8420: =head2 Course Infomation
8421:
8422: =over 4
1.191 harris41 8423:
8424: =item *
8425:
1.631 albertel 8426: coursedescription($courseid) : returns a hash of information about the
8427: specified course id, including all environment settings for the
8428: course, the description of the course will be in the hash under the
8429: key 'description'
1.191 harris41 8430:
8431: =item *
8432:
1.624 albertel 8433: resdata($name,$domain,$type,@which) : request for current parameter
8434: setting for a specific $type, where $type is either 'course' or 'user',
8435: @what should be a list of parameters to ask about. This routine caches
8436: answers for 5 minutes.
1.243 albertel 8437:
8438: =back
8439:
8440: =head2 Course Modification
8441:
8442: =over 4
1.191 harris41 8443:
8444: =item *
8445:
1.243 albertel 8446: writecoursepref($courseid,%prefs) : write preferences (environment
8447: database) for a course
1.191 harris41 8448:
8449: =item *
8450:
1.243 albertel 8451: createcourse($udom,$description,$url) : make/modify course
8452:
8453: =back
8454:
8455: =head2 Resource Subroutines
8456:
8457: =over 4
1.191 harris41 8458:
8459: =item *
8460:
1.243 albertel 8461: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 8462:
8463: =item *
8464:
1.243 albertel 8465: repcopy($filename) : subscribes to the requested file, and attempts to
8466: replicate from the owning library server, Might return
1.607 raeburn 8467: 'unavailable', 'not_found', 'forbidden', 'ok', or
8468: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 8469: resource. Expects the local filesystem pathname
8470: (/home/httpd/html/res/....)
8471:
8472: =back
8473:
8474: =head2 Resource Information
8475:
8476: =over 4
1.191 harris41 8477:
8478: =item *
8479:
1.243 albertel 8480: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
8481: a vairety of different possible values, $varname should be a request
8482: string, and the other parameters can be used to specify who and what
8483: one is asking about.
8484:
8485: Possible values for $varname are environment.lastname (or other item
8486: from the envirnment hash), user.name (or someother aspect about the
8487: user), resource.0.maxtries (or some other part and parameter of a
8488: resource)
1.204 albertel 8489:
8490: =item *
8491:
1.243 albertel 8492: directcondval($number) : get current value of a condition; reads from a state
8493: string
1.204 albertel 8494:
8495: =item *
8496:
1.243 albertel 8497: condval($condidx) : value of condition index based on state
1.204 albertel 8498:
8499: =item *
8500:
1.243 albertel 8501: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
8502: resource's metadata, $what should be either a specific key, or either
8503: 'keys' (to get a list of possible keys) or 'packages' to get a list of
8504: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
8505:
8506: this function automatically caches all requests
1.191 harris41 8507:
8508: =item *
8509:
1.243 albertel 8510: metadata_query($query,$custom,$customshow) : make a metadata query against the
8511: network of library servers; returns file handle of where SQL and regex results
8512: will be stored for query
1.191 harris41 8513:
8514: =item *
8515:
1.243 albertel 8516: symbread($filename) : return symbolic list entry (filename argument optional);
8517: returns the data handle
1.191 harris41 8518:
8519: =item *
8520:
1.243 albertel 8521: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 8522: a possible symb for the URL in $thisfn, and if is an encryypted
8523: resource that the user accessed using /enc/ returns a 1 on success, 0
8524: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 8525: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 8526:
1.191 harris41 8527:
8528: =item *
8529:
1.243 albertel 8530: symbclean($symb) : removes versions numbers from a symb, returns the
8531: cleaned symb
1.191 harris41 8532:
8533: =item *
8534:
1.243 albertel 8535: is_on_map($uri) : checks if the $uri is somewhere on the current
8536: course map, user must be in a course for it to work.
1.191 harris41 8537:
8538: =item *
8539:
1.243 albertel 8540: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 8541:
8542: =item *
8543:
1.243 albertel 8544: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
8545: a random seed, all arguments are optional, if they aren't sent it uses the
8546: environment to derive them. Note: if symb isn't sent and it can't get one
8547: from &symbread it will use the current time as its return value
1.191 harris41 8548:
8549: =item *
8550:
1.243 albertel 8551: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
8552: unfakeable, receipt
1.191 harris41 8553:
8554: =item *
8555:
1.620 albertel 8556: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 8557:
8558: =item *
8559:
1.243 albertel 8560: countacc($url) : count the number of accesses to a given URL
1.191 harris41 8561:
8562: =item *
8563:
1.243 albertel 8564: 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 8565:
8566: =item *
8567:
1.243 albertel 8568: 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 8569:
8570: =item *
8571:
1.243 albertel 8572: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 8573:
8574: =item *
8575:
1.243 albertel 8576: devalidate($symb) : devalidate temporary spreadsheet calculations,
8577: forcing spreadsheet to reevaluate the resource scores next time.
8578:
8579: =back
8580:
8581: =head2 Storing/Retreiving Data
8582:
8583: =over 4
1.191 harris41 8584:
8585: =item *
8586:
1.243 albertel 8587: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
8588: for this url; hashref needs to be given and should be a \%hashname; the
8589: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 8590: be derived from the env
1.191 harris41 8591:
8592: =item *
8593:
1.243 albertel 8594: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
8595: uses critical subroutine
1.191 harris41 8596:
8597: =item *
8598:
1.243 albertel 8599: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
8600: all args are optional
1.191 harris41 8601:
8602: =item *
8603:
1.717 albertel 8604: dumpstore($namespace,$udom,$uname,$regexp,$range) :
8605: dumps the complete (or key matching regexp) namespace into a hash
8606: ($udom, $uname, $regexp, $range are optional) for a namespace that is
8607: normally &store()ed into
8608:
8609: $range should be either an integer '100' (give me the first 100
8610: matching records)
8611: or be two integers sperated by a - with no spaces
8612: '30-50' (give me the 30th through the 50th matching
8613: records)
8614:
8615:
8616: =item *
8617:
8618: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
8619: replaces a &store() version of data with a replacement set of data
8620: for a particular resource in a namespace passed in the $storehash hash
8621: reference
8622:
8623: =item *
8624:
1.243 albertel 8625: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
8626: works very similar to store/cstore, but all data is stored in a
8627: temporary location and can be reset using tmpreset, $storehash should
8628: be a hash reference, returns nothing on success
1.191 harris41 8629:
8630: =item *
8631:
1.243 albertel 8632: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
8633: similar to restore, but all data is stored in a temporary location and
8634: can be reset using tmpreset. Returns a hash of values on success,
8635: error string otherwise.
1.191 harris41 8636:
8637: =item *
8638:
1.243 albertel 8639: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
8640: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 8641:
8642: =item *
8643:
1.243 albertel 8644: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8645: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 8646:
8647: =item *
8648:
1.243 albertel 8649: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
8650: namesp ($udom and $uname are optional)
1.191 harris41 8651:
8652: =item *
8653:
1.702 albertel 8654: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 8655: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 8656: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 8657:
1.702 albertel 8658: $range should be either an integer '100' (give me the first 100
8659: matching records)
8660: or be two integers sperated by a - with no spaces
8661: '30-50' (give me the 30th through the 50th matching
8662: records)
1.449 matthew 8663: =item *
8664:
8665: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
8666: $store can be a scalar, an array reference, or if the amount to be
8667: incremented is > 1, a hash reference.
8668:
8669: ($udom and $uname are optional)
1.191 harris41 8670:
8671: =item *
8672:
1.243 albertel 8673: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
8674: ($udom and $uname are optional)
1.191 harris41 8675:
8676: =item *
8677:
1.243 albertel 8678: cput($namespace,$storehash,$udom,$uname) : critical put
8679: ($udom and $uname are optional)
1.191 harris41 8680:
8681: =item *
8682:
1.748 albertel 8683: newput($namespace,$storehash,$udom,$uname) :
8684:
8685: Attempts to store the items in the $storehash, but only if they don't
8686: currently exist, if this succeeds you can be certain that you have
8687: successfully created a new key value pair in the $namespace db.
8688:
8689:
8690: Args:
8691: $namespace: name of database to store values to
8692: $storehash: hashref to store to the db
8693: $udom: (optional) domain of user containing the db
8694: $uname: (optional) name of user caontaining the db
8695:
8696: Returns:
8697: 'ok' -> succeeded in storing all keys of $storehash
8698: 'key_exists: <key>' -> failed to anything out of $storehash, as at
8699: least <key> already existed in the db (other
8700: requested keys may also already exist)
8701: 'error: <msg>' -> unable to tie the DB or other erorr occured
8702: 'con_lost' -> unable to contact request server
8703: 'refused' -> action was not allowed by remote machine
8704:
8705:
8706: =item *
8707:
1.243 albertel 8708: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8709: reference filled in from namesp (encrypts the return communication)
8710: ($udom and $uname are optional)
1.191 harris41 8711:
8712: =item *
8713:
1.243 albertel 8714: log($udom,$name,$home,$message) : write to permanent log for user; use
8715: critical subroutine
8716:
1.806 raeburn 8717: =item *
8718:
1.860 raeburn 8719: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
8720: array reference filled in from namespace found in domain level on either
8721: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 8722:
8723: =item *
8724:
1.860 raeburn 8725: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
8726: domain level either on specified domain server ($uhome) or primary domain
8727: server ($udom and $uhome are optional)
1.806 raeburn 8728:
1.243 albertel 8729: =back
8730:
8731: =head2 Network Status Functions
8732:
8733: =over 4
1.191 harris41 8734:
8735: =item *
8736:
8737: dirlist($uri) : return directory list based on URI
8738:
8739: =item *
8740:
1.243 albertel 8741: spareserver() : find server with least workload from spare.tab
8742:
8743: =back
8744:
8745: =head2 Apache Request
8746:
8747: =over 4
1.191 harris41 8748:
8749: =item *
8750:
1.243 albertel 8751: ssi($url,%hash) : server side include, does a complete request cycle on url to
8752: localhost, posts hash
8753:
8754: =back
8755:
8756: =head2 Data to String to Data
8757:
8758: =over 4
1.191 harris41 8759:
8760: =item *
8761:
1.243 albertel 8762: hash2str(%hash) : convert a hash into a string complete with escaping and '='
8763: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 8764:
8765: =item *
8766:
1.243 albertel 8767: hashref2str($hashref) : convert a hashref into a string complete with
8768: escaping and '=' and '&' separators, supports elements that are
8769: arrayrefs and hashrefs
1.191 harris41 8770:
8771: =item *
8772:
1.243 albertel 8773: arrayref2str($arrayref) : convert an arrayref into a string complete
8774: with escaping and '&' separators, supports elements that are arrayrefs
8775: and hashrefs
1.191 harris41 8776:
8777: =item *
8778:
1.243 albertel 8779: str2hash($string) : convert string to hash using unescaping and
8780: splitting on '=' and '&', supports elements that are arrayrefs and
8781: hashrefs
1.191 harris41 8782:
8783: =item *
8784:
1.243 albertel 8785: str2array($string) : convert string to hash using unescaping and
8786: splitting on '&', supports elements that are arrayrefs and hashrefs
8787:
8788: =back
8789:
8790: =head2 Logging Routines
8791:
8792: =over 4
8793:
8794: These routines allow one to make log messages in the lonnet.log and
8795: lonnet.perm logfiles.
1.191 harris41 8796:
8797: =item *
8798:
1.243 albertel 8799: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 8800:
8801: =item *
8802:
1.243 albertel 8803: logthis() : append message to the normal lonnet.log file, it gets
8804: preiodically rolled over and deleted.
1.191 harris41 8805:
8806: =item *
8807:
1.243 albertel 8808: logperm() : append a permanent message to lonnet.perm.log, this log
8809: file never gets deleted by any automated portion of the system, only
8810: messages of critical importance should go in here.
8811:
8812: =back
8813:
8814: =head2 General File Helper Routines
8815:
8816: =over 4
1.191 harris41 8817:
8818: =item *
8819:
1.481 raeburn 8820: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
8821: (a) files in /uploaded
8822: (i) If a local copy of the file exists -
8823: compares modification date of local copy with last-modified date for
8824: definitive version stored on home server for course. If local copy is
8825: stale, requests a new version from the home server and stores it.
8826: If the original has been removed from the home server, then local copy
8827: is unlinked.
8828: (ii) If local copy does not exist -
8829: requests the file from the home server and stores it.
8830:
8831: If $caller is 'uploadrep':
8832: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
8833: for request for files originally uploaded via DOCS.
8834: - returns 'ok' if fresh local copy now available, -1 otherwise.
8835:
8836: Otherwise:
8837: This indicates a call from the content generation phase of the request.
8838: - returns the entire contents of the file or -1.
8839:
8840: (b) files in /res
8841: - returns the entire contents of a file or -1;
8842: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 8843:
1.712 albertel 8844:
8845: =item *
8846:
8847: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
8848: reference
8849:
8850: returns either a stat() list of data about the file or an empty list
8851: if the file doesn't exist or couldn't find out about it (connection
8852: problems or user unknown)
8853:
1.191 harris41 8854: =item *
8855:
1.243 albertel 8856: filelocation($dir,$file) : returns file system location of a file
8857: based on URI; meant to be "fairly clean" absolute reference, $dir is a
8858: directory that relative $file lookups are to looked in ($dir of /a/dir
8859: and a file of ../bob will become /a/bob)
1.191 harris41 8860:
8861: =item *
8862:
8863: hreflocation($dir,$file) : returns file system location or a URL; same as
8864: filelocation except for hrefs
8865:
8866: =item *
8867:
8868: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
8869:
1.243 albertel 8870: =back
8871:
1.608 albertel 8872: =head2 Usererfile file routines (/uploaded*)
8873:
8874: =over 4
8875:
8876: =item *
8877:
8878: userfileupload(): main rotine for putting a file in a user or course's
8879: filespace, arguments are,
8880:
1.620 albertel 8881: formname - required - this is the name of the element in $env where the
1.608 albertel 8882: filename, and the contents of the file to create/modifed exist
1.620 albertel 8883: the filename is in $env{'form.'.$formname.'.filename'} and the
8884: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 8885: coursedoc - if true, store the file in the course of the active role
8886: of the current user
8887: subdir - required - subdirectory to put the file in under ../userfiles/
8888: if undefined, it will be placed in "unknown"
8889:
8890: (This routine calls clean_filename() to remove any dangerous
8891: characters from the filename, and then calls finuserfileupload() to
8892: complete the transaction)
8893:
8894: returns either the url of the uploaded file (/uploaded/....) if successful
8895: and /adm/notfound.html if unsuccessful
8896:
8897: =item *
8898:
8899: clean_filename(): routine for cleaing a filename up for storage in
8900: userfile space, argument is:
8901:
8902: filename - proposed filename
8903:
8904: returns: the new clean filename
8905:
8906: =item *
8907:
8908: finishuserfileupload(): routine that creaes and sends the file to
8909: userspace, probably shouldn't be called directly
8910:
8911: docuname: username or courseid of destination for the file
8912: docudom: domain of user/course of destination for the file
8913: formname: same as for userfileupload()
8914: fname: filename (inculding subdirectories) for the file
8915:
8916: returns either the url of the uploaded file (/uploaded/....) if successful
8917: and /adm/notfound.html if unsuccessful
8918:
8919: =item *
8920:
8921: renameuserfile(): renames an existing userfile to a new name
8922:
8923: Args:
8924: docuname: username or courseid of destination for the file
8925: docudom: domain of user/course of destination for the file
8926: old: current file name (including any subdirs under userfiles)
8927: new: desired file name (including any subdirs under userfiles)
8928:
8929: =item *
8930:
8931: mkdiruserfile(): creates a directory is a userfiles dir
8932:
8933: Args:
8934: docuname: username or courseid of destination for the file
8935: docudom: domain of user/course of destination for the file
8936: dir: dir to create (including any subdirs under userfiles)
8937:
8938: =item *
8939:
8940: removeuserfile(): removes a file that exists in userfiles
8941:
8942: Args:
8943: docuname: username or courseid of destination for the file
8944: docudom: domain of user/course of destination for the file
8945: fname: filname to delete (including any subdirs under userfiles)
8946:
8947: =item *
8948:
8949: removeuploadedurl(): convience function for removeuserfile()
8950:
8951: Args:
8952: url: a full /uploaded/... url to delete
8953:
1.747 albertel 8954: =item *
8955:
8956: get_portfile_permissions():
8957: Args:
8958: domain: domain of user or course contain the portfolio files
8959: user: name of user or num of course contain the portfolio files
8960: Returns:
8961: hashref of a dump of the proper file_permissions.db
8962:
8963:
8964: =item *
8965:
8966: get_access_controls():
8967:
8968: Args:
8969: current_permissions: the hash ref returned from get_portfile_permissions()
8970: group: (optional) the group you want the files associated with
8971: file: (optional) the file you want access info on
8972:
8973: Returns:
1.749 raeburn 8974: a hash (keys are file names) of hashes containing
8975: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
8976: values are XML containing access control settings (see below)
1.747 albertel 8977:
8978: Internal notes:
8979:
1.749 raeburn 8980: access controls are stored in file_permissions.db as key=value pairs.
8981: key -> path to file/file_name\0uniqueID:scope_end_start
8982: where scope -> public,guest,course,group,domains or users.
8983: end -> UNIX time for end of access (0 -> no end date)
8984: start -> UNIX time for start of access
8985:
8986: value -> XML description of access control
8987: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
8988: <start></start>
8989: <end></end>
8990:
8991: <password></password> for scope type = guest
8992:
8993: <domain></domain> for scope type = course or group
8994: <number></number>
8995: <roles id="">
8996: <role></role>
8997: <access></access>
8998: <section></section>
8999: <group></group>
9000: </roles>
9001:
9002: <dom></dom> for scope type = domains
9003:
9004: <users> for scope type = users
9005: <user>
9006: <uname></uname>
9007: <udom></udom>
9008: </user>
9009: </users>
9010: </scope>
9011:
9012: Access data is also aggregated for each file in an additional key=value pair:
9013: key -> path to file/file_name\0accesscontrol
9014: value -> reference to hash
9015: hash contains key = value pairs
9016: where key = uniqueID:scope_end_start
9017: value = UNIX time record was last updated
9018:
9019: Used to improve speed of look-ups of access controls for each file.
9020:
9021: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
9022:
9023: modify_access_controls():
9024:
9025: Modifies access controls for a portfolio file
9026: Args
9027: 1. file name
9028: 2. reference to hash of required changes,
9029: 3. domain
9030: 4. username
9031: where domain,username are the domain of the portfolio owner
9032: (either a user or a course)
9033:
9034: Returns:
9035: 1. result of additions or updates ('ok' or 'error', with error message).
9036: 2. result of deletions ('ok' or 'error', with error message).
9037: 3. reference to hash of any new or updated access controls.
9038: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
9039: key = integer (inbound ID)
9040: value = uniqueID
1.747 albertel 9041:
1.608 albertel 9042: =back
9043:
1.243 albertel 9044: =head2 HTTP Helper Routines
9045:
9046: =over 4
9047:
1.191 harris41 9048: =item *
9049:
9050: escape() : unpack non-word characters into CGI-compatible hex codes
9051:
9052: =item *
9053:
9054: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
9055:
1.243 albertel 9056: =back
9057:
9058: =head1 PRIVATE SUBROUTINES
9059:
9060: =head2 Underlying communication routines (Shouldn't call)
9061:
9062: =over 4
9063:
9064: =item *
9065:
9066: subreply() : tries to pass a message to lonc, returns con_lost if incapable
9067:
9068: =item *
9069:
9070: reply() : uses subreply to send a message to remote machine, logs all failures
9071:
9072: =item *
9073:
9074: critical() : passes a critical message to another server; if cannot
9075: get through then place message in connection buffer directory and
9076: returns con_delayed, if incapable of saving message, returns
9077: con_failed
9078:
9079: =item *
9080:
9081: reconlonc() : tries to reconnect lonc client processes.
9082:
9083: =back
9084:
9085: =head2 Resource Access Logging
9086:
9087: =over 4
9088:
9089: =item *
9090:
9091: flushcourselogs() : flush (save) buffer logs and access logs
9092:
9093: =item *
9094:
9095: courselog($what) : save message for course in hash
9096:
9097: =item *
9098:
9099: courseacclog($what) : save message for course using &courselog(). Perform
9100: special processing for specific resource types (problems, exams, quizzes, etc).
9101:
1.191 harris41 9102: =item *
9103:
9104: goodbye() : flush course logs and log shutting down; it is called in srm.conf
9105: as a PerlChildExitHandler
1.243 albertel 9106:
9107: =back
9108:
9109: =head2 Other
9110:
9111: =over 4
9112:
9113: =item *
9114:
9115: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 9116:
9117: =back
9118:
9119: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>