Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.804
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.804 ! raeburn 4: # $Id: lonnet.pm,v 1.803 2006/11/10 18:44:34 albertel 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.599 albertel 38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom
39: %libserv %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.599 albertel 42: %domaindescription %domain_auth_def %domain_auth_arg_def
1.685 raeburn 43: %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
44: $tmpdir $_64bit %env);
1.403 www 45:
1.1 albertel 46: use IO::Socket;
1.31 www 47: use GDBM_File;
1.208 albertel 48: use HTML::LCParser;
1.637 raeburn 49: use HTML::Parser;
1.88 www 50: use Fcntl qw(:flock);
1.557 albertel 51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539 albertel 52: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 53: use Cache::Memcached;
1.676 albertel 54: use Digest::MD5;
1.790 albertel 55: use Math::Random;
1.740 www 56: use lib '/home/httpd/lib/perl';
57: use LONCAPA;
58: use LONCAPA::Configuration;
1.676 albertel 59:
1.195 www 60: my $readit;
1.550 foxr 61: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 62:
1.619 albertel 63: require Exporter;
64:
65: our @ISA = qw (Exporter);
66: our @EXPORT = qw(%env);
67:
1.449 matthew 68: =pod
69:
70: =head1 Package Variables
71:
72: These are largely undocumented, so if you decipher one please note it here.
73:
74: =over 4
75:
76: =item $processmarker
77:
78: Contains the time this process was started and this servers host id.
79:
80: =item $dumpcount
81:
82: Counts the number of times a message log flush has been attempted (regardless
83: of success) by this process. Used as part of the filename when messages are
84: delayed.
85:
86: =back
87:
88: =cut
89:
90:
1.1 albertel 91: # --------------------------------------------------------------------- Logging
1.729 www 92: {
93: my $logid;
94: sub instructor_log {
95: my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
96: $logid++;
97: my $id=time().'00000'.$$.'00000'.$logid;
98: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 99: { $id => {
100: 'exe_uname' => $env{'user.name'},
101: 'exe_udom' => $env{'user.domain'},
102: 'exe_time' => time(),
103: 'exe_ip' => $ENV{'REMOTE_ADDR'},
104: 'delflag' => $delflag,
105: 'logentry' => $storehash,
106: 'uname' => $uname,
107: 'udom' => $udom,
108: }
109: },
1.729 www 110: $env{'course.'.$env{'request.course.id'}.'.domain'},
111: $env{'course.'.$env{'request.course.id'}.'.num'}
112: );
113: }
114: }
1.1 albertel 115:
1.163 harris41 116: sub logtouch {
117: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 118: unless (-e "$execdir/logs/lonnet.log") {
119: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 120: close $fh;
121: }
122: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
123: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
124: }
125:
1.1 albertel 126: sub logthis {
127: my $message=shift;
128: my $execdir=$perlvar{'lonDaemons'};
129: my $now=time;
130: my $local=localtime($now);
1.448 albertel 131: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
132: print $fh "$local ($$): $message\n";
133: close($fh);
134: }
1.1 albertel 135: return 1;
136: }
137:
138: sub logperm {
139: my $message=shift;
140: my $execdir=$perlvar{'lonDaemons'};
141: my $now=time;
142: my $local=localtime($now);
1.448 albertel 143: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
144: print $fh "$now:$message:$local\n";
145: close($fh);
146: }
1.1 albertel 147: return 1;
148: }
149:
150: # -------------------------------------------------- Non-critical communication
151: sub subreply {
152: my ($cmd,$server)=@_;
1.704 albertel 153: my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549 foxr 154: #
155: # With loncnew process trimming, there's a timing hole between lonc server
156: # process exit and the master server picking up the listen on the AF_UNIX
157: # socket. In that time interval, a lock file will exist:
158:
159: my $lockfile=$peerfile.".lock";
160: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
161: sleep(1);
162: }
163: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 164: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 165: #
1.550 foxr 166: # We'll give the connection a few tries before abandoning it. If
167: # connection is not possible, we'll con_lost back to the client.
168: #
169: my $client;
170: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
171: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
172: Type => SOCK_STREAM,
173: Timeout => 10);
174: if($client) {
175: last; # Connected!
176: }
177: sleep(1); # Try again later if failed connection.
178: }
179: my $answer;
180: if ($client) {
1.704 albertel 181: print $client "sethost:$server:$cmd\n";
1.550 foxr 182: $answer=<$client>;
183: if (!$answer) { $answer="con_lost"; }
184: chomp($answer);
185: } else {
186: $answer = 'con_lost'; # Failed connection.
187: }
1.1 albertel 188: return $answer;
189: }
190:
191: sub reply {
192: my ($cmd,$server)=@_;
1.205 www 193: unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1 albertel 194: my $answer=subreply($cmd,$server);
1.65 www 195: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 196: &logthis("<font color=\"blue\">WARNING:".
1.12 www 197: " $cmd to $server returned $answer</font>");
198: }
1.1 albertel 199: return $answer;
200: }
201:
202: # ----------------------------------------------------------- Send USR1 to lonc
203:
204: sub reconlonc {
205: my $peerfile=shift;
206: &logthis("Trying to reconnect for $peerfile");
207: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 208: if (open(my $fh,"<$loncfile")) {
1.1 albertel 209: my $loncpid=<$fh>;
210: chomp($loncpid);
211: if (kill 0 => $loncpid) {
212: &logthis("lonc at pid $loncpid responding, sending USR1");
213: kill USR1 => $loncpid;
214: sleep 1;
215: if (-e "$peerfile") { return; }
216: &logthis("$peerfile still not there, give it another try");
217: sleep 5;
218: if (-e "$peerfile") { return; }
1.12 www 219: &logthis(
1.672 albertel 220: "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1 albertel 221: } else {
1.12 www 222: &logthis(
1.672 albertel 223: "<font color=\"blue\">WARNING:".
1.12 www 224: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 225: }
226: } else {
1.672 albertel 227: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 228: }
229: }
230:
231: # ------------------------------------------------------ Critical communication
1.12 www 232:
1.1 albertel 233: sub critical {
234: my ($cmd,$server)=@_;
1.89 www 235: unless ($hostname{$server}) {
1.672 albertel 236: &logthis("<font color=\"blue\">WARNING:".
1.89 www 237: " Critical message to unknown server ($server)</font>");
238: return 'no_such_host';
239: }
1.1 albertel 240: my $answer=reply($cmd,$server);
241: if ($answer eq 'con_lost') {
242: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 243: my $answer=reply($cmd,$server);
1.1 albertel 244: if ($answer eq 'con_lost') {
245: my $now=time;
246: my $middlename=$cmd;
1.5 www 247: $middlename=substr($middlename,0,16);
1.1 albertel 248: $middlename=~s/\W//g;
249: my $dfilename=
1.305 www 250: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
251: $dumpcount++;
1.1 albertel 252: {
1.448 albertel 253: my $dfh;
254: if (open($dfh,">$dfilename")) {
255: print $dfh "$cmd\n";
256: close($dfh);
257: }
1.1 albertel 258: }
259: sleep 2;
260: my $wcmd='';
261: {
1.448 albertel 262: my $dfh;
263: if (open($dfh,"<$dfilename")) {
264: $wcmd=<$dfh>;
265: close($dfh);
266: }
1.1 albertel 267: }
268: chomp($wcmd);
1.7 www 269: if ($wcmd eq $cmd) {
1.672 albertel 270: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 271: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 272: &logperm("D:$server:$cmd");
273: return 'con_delayed';
274: } else {
1.672 albertel 275: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 276: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 277: &logperm("F:$server:$cmd");
278: return 'con_failed';
279: }
280: }
281: }
282: return $answer;
1.405 albertel 283: }
284:
1.755 albertel 285: # ------------------------------------------- check if return value is an error
286:
287: sub error {
288: my ($result) = @_;
1.756 albertel 289: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 290: if ($2 == 2) { return undef; }
291: return $1;
292: }
293: return undef;
294: }
295:
1.783 albertel 296: sub convert_and_load_session_env {
297: my ($lonidsdir,$handle)=@_;
298: my @profile;
299: {
300: open(my $idf,"$lonidsdir/$handle.id");
301: flock($idf,LOCK_SH);
302: @profile=<$idf>;
303: close($idf);
304: }
305: my %temp_env;
306: foreach my $line (@profile) {
1.786 albertel 307: if ($line !~ m/=/) {
308: return 0;
309: }
1.783 albertel 310: chomp($line);
311: my ($envname,$envvalue)=split(/=/,$line,2);
312: $temp_env{&unescape($envname)} = &unescape($envvalue);
313: }
314: unlink("$lonidsdir/$handle.id");
315: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
316: 0640)) {
317: %disk_env = %temp_env;
318: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
319: untie(%disk_env);
320: }
1.786 albertel 321: return 1;
1.783 albertel 322: }
323:
1.374 www 324: # ------------------------------------------- Transfer profile into environment
1.780 albertel 325: my $env_loaded;
326: sub transfer_profile_to_env {
1.788 albertel 327: my ($lonidsdir,$handle,$force_transfer) = @_;
328: if (!$force_transfer && $env_loaded) { return; }
1.374 www 329:
1.720 albertel 330: if (!defined($lonidsdir)) {
331: $lonidsdir = $perlvar{'lonIDsDir'};
332: }
333: if (!defined($handle)) {
334: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
335: }
336:
1.786 albertel 337: my $convert;
338: {
339: open(my $idf,"$lonidsdir/$handle.id");
340: flock($idf,LOCK_SH);
341: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
342: &GDBM_READER(),0640)) {
343: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
344: untie(%disk_env);
345: } else {
346: $convert = 1;
347: }
348: }
349: if ($convert) {
350: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
351: &logthis("Failed to load session, or convert session.");
352: }
1.374 www 353: }
1.783 albertel 354:
1.786 albertel 355: my %remove;
1.783 albertel 356: while ( my $envname = each(%env) ) {
1.433 matthew 357: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
358: if ($time < time-300) {
1.783 albertel 359: $remove{$key}++;
1.433 matthew 360: }
361: }
362: }
1.783 albertel 363:
1.619 albertel 364: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 365: $env_loaded=1;
1.783 albertel 366: foreach my $expired_key (keys(%remove)) {
1.433 matthew 367: &delenv($expired_key);
1.374 www 368: }
1.1 albertel 369: }
370:
1.5 www 371: # ---------------------------------------------------------- Append Environment
372:
373: sub appenv {
1.6 www 374: my %newenv=@_;
1.692 albertel 375: foreach my $key (keys(%newenv)) {
376: if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672 albertel 377: &logthis("<font color=\"blue\">WARNING: ".
1.692 albertel 378: "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151 www 379: .'</font>');
1.692 albertel 380: delete($newenv{$key});
1.35 www 381: } else {
1.692 albertel 382: $env{$key}=$newenv{$key};
1.35 www 383: }
1.191 harris41 384: }
1.783 albertel 385: if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
386: 0640)) {
387: while (my ($key,$value) = each(%newenv)) {
388: $disk_env{$key} = $value;
1.448 albertel 389: }
1.783 albertel 390: untie(%disk_env);
1.56 www 391: }
392: return 'ok';
393: }
394: # ----------------------------------------------------- Delete from Environment
395:
396: sub delenv {
397: my $delthis=shift;
398: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 399: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 400: "Attempt to delete from environment ".$delthis);
401: return 'error';
402: }
1.783 albertel 403: if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
404: 0640)) {
405: foreach my $key (keys(%disk_env)) {
406: if ($key=~/^$delthis/) {
1.619 albertel 407: delete($env{$key});
1.783 albertel 408: delete($disk_env{$key});
1.473 matthew 409: }
1.448 albertel 410: }
1.783 albertel 411: untie(%disk_env);
1.5 www 412: }
413: return 'ok';
1.369 albertel 414: }
415:
1.790 albertel 416: sub get_env_multiple {
417: my ($name) = @_;
418: my @values;
419: if (defined($env{$name})) {
420: # exists is it an array
421: if (ref($env{$name})) {
422: @values=@{ $env{$name} };
423: } else {
424: $values[0]=$env{$name};
425: }
426: }
427: return(@values);
428: }
429:
1.369 albertel 430: # ------------------------------------------ Find out current server userload
431: # there is a copy in lond
432: sub userload {
433: my $numusers=0;
434: {
435: opendir(LONIDS,$perlvar{'lonIDsDir'});
436: my $filename;
437: my $curtime=time;
438: while ($filename=readdir(LONIDS)) {
439: if ($filename eq '.' || $filename eq '..') {next;}
1.404 albertel 440: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 441: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 442: }
443: closedir(LONIDS);
444: }
445: my $userloadpercent=0;
446: my $maxuserload=$perlvar{'lonUserLoadLim'};
447: if ($maxuserload) {
1.371 albertel 448: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 449: }
1.372 albertel 450: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 451: return $userloadpercent;
1.283 www 452: }
453:
454: # ------------------------------------------ Fight off request when overloaded
455:
456: sub overloaderror {
457: my ($r,$checkserver)=@_;
458: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
459: my $loadavg;
460: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 461: open(my $loadfile,'/proc/loadavg');
1.283 www 462: $loadavg=<$loadfile>;
463: $loadavg =~ s/\s.*//g;
1.285 matthew 464: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 465: close($loadfile);
1.283 www 466: } else {
467: $loadavg=&reply('load',$checkserver);
468: }
1.285 matthew 469: my $overload=$loadavg-100;
1.283 www 470: if ($overload>0) {
1.285 matthew 471: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 472: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 473: return 413;
1.283 www 474: }
475: return '';
1.5 www 476: }
1.1 albertel 477:
478: # ------------------------------ Find server with least workload from spare.tab
1.11 www 479:
1.1 albertel 480: sub spareserver {
1.670 albertel 481: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 482: my $spare_server;
1.370 albertel 483: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 484: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
485: : $userloadpercent;
486:
487: foreach my $try_server (@{ $spareid{'primary'} }) {
488: ($spare_server, $lowest_load) =
489: &compare_server_load($try_server, $spare_server, $lowest_load);
490: }
491:
492: my $found_server = ($spare_server ne '' && $lowest_load < 100);
493:
494: if (!$found_server) {
495: foreach my $try_server (@{ $spareid{'default'} }) {
496: ($spare_server, $lowest_load) =
497: &compare_server_load($try_server, $spare_server, $lowest_load);
498: }
499: }
500:
501: if (!$want_server_name) {
502: $spare_server="http://$hostname{$spare_server}";
503: }
504: return $spare_server;
505: }
506:
507: sub compare_server_load {
508: my ($try_server, $spare_server, $lowest_load) = @_;
509:
510: my $loadans = &reply('load', $try_server);
511: my $userloadans = &reply('userload',$try_server);
512:
513: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
514: next; #didn't get a number from the server
515: }
516:
517: my $load;
518: if ($loadans =~ /\d/) {
519: if ($userloadans =~ /\d/) {
520: #both are numbers, pick the bigger one
521: $load = ($loadans > $userloadans) ? $loadans
522: : $userloadans;
1.411 albertel 523: } else {
1.784 albertel 524: $load = $loadans;
1.411 albertel 525: }
1.784 albertel 526: } else {
527: $load = $userloadans;
528: }
529:
530: if (($load =~ /\d/) && ($load < $lowest_load)) {
531: $spare_server = $try_server;
532: $lowest_load = $load;
1.370 albertel 533: }
1.784 albertel 534: return ($spare_server,$lowest_load);
1.202 matthew 535: }
536: # --------------------------------------------- Try to change a user's password
537:
538: sub changepass {
1.799 raeburn 539: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 540: $currentpass = &escape($currentpass);
541: $newpass = &escape($newpass);
1.799 raeburn 542: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202 matthew 543: $server);
544: if (! $answer) {
545: &logthis("No reply on password change request to $server ".
546: "by $uname in domain $udom.");
547: } elsif ($answer =~ "^ok") {
548: &logthis("$uname in $udom successfully changed their password ".
549: "on $server.");
550: } elsif ($answer =~ "^pwchange_failure") {
551: &logthis("$uname in $udom was unable to change their password ".
552: "on $server. The action was blocked by either lcpasswd ".
553: "or pwchange");
554: } elsif ($answer =~ "^non_authorized") {
555: &logthis("$uname in $udom did not get their password correct when ".
556: "attempting to change it on $server.");
557: } elsif ($answer =~ "^auth_mode_error") {
558: &logthis("$uname in $udom attempted to change their password despite ".
559: "not being locally or internally authenticated on $server.");
560: } elsif ($answer =~ "^unknown_user") {
561: &logthis("$uname in $udom attempted to change their password ".
562: "on $server but were unable to because $server is not ".
563: "their home server.");
564: } elsif ($answer =~ "^refused") {
565: &logthis("$server refused to change $uname in $udom password because ".
566: "it was sent an unencrypted request to change the password.");
567: }
568: return $answer;
1.1 albertel 569: }
570:
1.169 harris41 571: # ----------------------- Try to determine user's current authentication scheme
572:
573: sub queryauthenticate {
574: my ($uname,$udom)=@_;
1.456 albertel 575: my $uhome=&homeserver($uname,$udom);
576: if (!$uhome) {
577: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
578: return 'no_host';
579: }
580: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
581: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
582: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 583: }
1.456 albertel 584: return $answer;
1.169 harris41 585: }
586:
1.1 albertel 587: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 588:
1.1 albertel 589: sub authenticate {
590: my ($uname,$upass,$udom)=@_;
1.12 www 591: $upass=escape($upass);
1.199 www 592: $uname=~s/\W//g;
1.471 albertel 593: my $uhome=&homeserver($uname,$udom);
594: if (!$uhome) {
595: &logthis("User $uname at $udom is unknown in authenticate");
596: return 'no_host';
1.1 albertel 597: }
1.471 albertel 598: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
599: if ($answer eq 'authorized') {
600: &logthis("User $uname at $udom authorized by $uhome");
601: return $uhome;
602: }
603: if ($answer eq 'non_authorized') {
604: &logthis("User $uname at $udom rejected by $uhome");
605: return 'no_host';
1.9 www 606: }
1.471 albertel 607: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 608: return 'no_host';
609: }
610:
611: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 612:
1.599 albertel 613: my %homecache;
1.1 albertel 614: sub homeserver {
1.230 stredwic 615: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 616: my $index="$uname:$udom";
1.426 albertel 617:
1.599 albertel 618: if (exists($homecache{$index})) { return $homecache{$index}; }
1.1 albertel 619: my $tryserver;
620: foreach $tryserver (keys %libserv) {
1.230 stredwic 621: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 622: exists($badServerCache{$tryserver}));
1.1 albertel 623: if ($hostdom{$tryserver} eq $udom) {
624: my $answer=reply("home:$udom:$uname",$tryserver);
625: if ($answer eq 'found') {
1.599 albertel 626: return $homecache{$index}=$tryserver;
1.231 stredwic 627: } elsif ($answer eq 'no_host') {
628: $badServerCache{$tryserver}=1;
1.221 matthew 629: }
1.1 albertel 630: }
631: }
632: return 'no_host';
1.70 www 633: }
634:
635: # ------------------------------------- Find the usernames behind a list of IDs
636:
637: sub idget {
638: my ($udom,@ids)=@_;
639: my %returnhash=();
640:
641: my $tryserver;
642: foreach $tryserver (keys %libserv) {
643: if ($hostdom{$tryserver} eq $udom) {
644: my $idlist=join('&',@ids);
645: $idlist=~tr/A-Z/a-z/;
646: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
647: my @answer=();
1.76 www 648: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70 www 649: @answer=split(/\&/,$reply);
650: } ;
651: my $i;
652: for ($i=0;$i<=$#ids;$i++) {
653: if ($answer[$i]) {
654: $returnhash{$ids[$i]}=$answer[$i];
655: }
656: }
657: }
658: }
659: return %returnhash;
660: }
661:
662: # ------------------------------------- Find the IDs behind a list of usernames
663:
664: sub idrget {
665: my ($udom,@unames)=@_;
666: my %returnhash=();
1.800 albertel 667: foreach my $uname (@unames) {
668: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 669: }
1.70 www 670: return %returnhash;
671: }
672:
673: # ------------------------------- Store away a list of names and associated IDs
674:
675: sub idput {
676: my ($udom,%ids)=@_;
677: my %servers=();
1.800 albertel 678: foreach my $uname (keys(%ids)) {
679: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
680: my $uhom=&homeserver($uname,$udom);
1.70 www 681: if ($uhom ne 'no_host') {
1.800 albertel 682: my $id=&escape($ids{$uname});
1.70 www 683: $id=~tr/A-Z/a-z/;
1.800 albertel 684: my $esc_unam=&escape($uname);
1.70 www 685: if ($servers{$uhom}) {
1.800 albertel 686: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 687: } else {
1.800 albertel 688: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 689: }
690: }
1.191 harris41 691: }
1.800 albertel 692: foreach my $server (keys(%servers)) {
693: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 694: }
1.344 www 695: }
696:
697: # --------------------------------------------------- Assign a key to a student
698:
699: sub assign_access_key {
1.364 www 700: #
701: # a valid key looks like uname:udom#comments
702: # comments are being appended
703: #
1.498 www 704: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
705: $kdom=
1.620 albertel 706: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 707: $knum=
1.620 albertel 708: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 709: $cdom=
1.620 albertel 710: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 711: $cnum=
1.620 albertel 712: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
713: $udom=$env{'user.name'} unless (defined($udom));
714: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 715: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 716: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 717: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 718: # assigned to this person
719: # - this should not happen,
1.345 www 720: # unless something went wrong
721: # the first time around
722: # ready to assign
1.364 www 723: $logentry=$1.'; '.$logentry;
1.496 www 724: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 725: $kdom,$knum) eq 'ok') {
1.345 www 726: # key now belongs to user
1.346 www 727: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 728: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
729: &appenv('environment.'.$envkey => $ckey);
730: return 'ok';
731: } else {
732: return
733: 'error: Count not permanently assign key, will need to be re-entered later.';
734: }
735: } else {
736: return 'error: Could not assign key, try again later.';
737: }
1.364 www 738: } elsif (!$existing{$ckey}) {
1.345 www 739: # the key does not exist
740: return 'error: The key does not exist';
741: } else {
742: # the key is somebody else's
743: return 'error: The key is already in use';
744: }
1.344 www 745: }
746:
1.364 www 747: # ------------------------------------------ put an additional comment on a key
748:
749: sub comment_access_key {
750: #
751: # a valid key looks like uname:udom#comments
752: # comments are being appended
753: #
754: my ($ckey,$cdom,$cnum,$logentry)=@_;
755: $cdom=
1.620 albertel 756: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 757: $cnum=
1.620 albertel 758: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 759: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
760: if ($existing{$ckey}) {
761: $existing{$ckey}.='; '.$logentry;
762: # ready to assign
1.367 www 763: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 764: $cdom,$cnum) eq 'ok') {
765: return 'ok';
766: } else {
767: return 'error: Count not store comment.';
768: }
769: } else {
770: # the key does not exist
771: return 'error: The key does not exist';
772: }
773: }
774:
1.344 www 775: # ------------------------------------------------------ Generate a set of keys
776:
777: sub generate_access_keys {
1.364 www 778: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 779: $cdom=
1.620 albertel 780: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 781: $cnum=
1.620 albertel 782: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 783: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 784: unless (($cdom) && ($cnum)) { return 0; }
785: if ($number>10000) { return 0; }
786: sleep(2); # make sure don't get same seed twice
787: srand(time()^($$+($$<<15))); # from "Programming Perl"
788: my $total=0;
789: for (my $i=1;$i<=$number;$i++) {
790: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
791: sprintf("%lx",int(100000*rand)).'-'.
792: sprintf("%lx",int(100000*rand));
793: $newkey=~s/1/g/g; # folks mix up 1 and l
794: $newkey=~s/0/h/g; # and also 0 and O
795: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
796: if ($existing{$newkey}) {
797: $i--;
798: } else {
1.364 www 799: if (&put('accesskeys',
800: { $newkey => '# generated '.localtime().
1.620 albertel 801: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 802: '; '.$logentry },
803: $cdom,$cnum) eq 'ok') {
1.344 www 804: $total++;
805: }
806: }
807: }
1.620 albertel 808: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 809: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
810: return $total;
811: }
812:
813: # ------------------------------------------------------- Validate an accesskey
814:
815: sub validate_access_key {
816: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
817: $cdom=
1.620 albertel 818: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 819: $cnum=
1.620 albertel 820: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
821: $udom=$env{'user.domain'} unless (defined($udom));
822: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 823: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 824: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 825: }
826:
827: # ------------------------------------- Find the section of student in a course
1.652 albertel 828: sub devalidate_getsection_cache {
829: my ($udom,$unam,$courseid)=@_;
830: $courseid=~s/\_/\//g;
831: $courseid=~s/^(\w)/\/$1/;
832: my $hashid="$udom:$unam:$courseid";
833: &devalidate_cache_new('getsection',$hashid);
834: }
1.298 matthew 835:
836: sub getsection {
837: my ($udom,$unam,$courseid)=@_;
1.599 albertel 838: my $cachetime=1800;
1.298 matthew 839: $courseid=~s/\_/\//g;
840: $courseid=~s/^(\w)/\/$1/;
1.551 albertel 841:
842: my $hashid="$udom:$unam:$courseid";
1.599 albertel 843: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 844: if (defined($cached)) { return $result; }
845:
1.298 matthew 846: my %Pending;
847: my %Expired;
848: #
849: # Each role can either have not started yet (pending), be active,
850: # or have expired.
851: #
852: # If there is an active role, we are done.
853: #
854: # If there is more than one role which has not started yet,
855: # choose the one which will start sooner
856: # If there is one role which has not started yet, return it.
857: #
858: # If there is more than one expired role, choose the one which ended last.
859: # If there is a role which has expired, return it.
860: #
1.800 albertel 861: foreach my $line (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
862: &homeserver($unam,$udom)))) {
863: my ($key,$value)=split(/\=/,$line,2);
1.298 matthew 864: $key=&unescape($key);
1.479 albertel 865: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 866: my $section=$1;
867: if ($key eq $courseid.'_st') { $section=''; }
868: my ($dummy,$end,$start)=split(/\_/,&unescape($value));
869: my $now=time;
1.548 albertel 870: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 871: $Expired{$end}=$section;
872: next;
873: }
1.548 albertel 874: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 875: $Pending{$start}=$section;
876: next;
877: }
1.599 albertel 878: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 879: }
880: #
881: # Presumedly there will be few matching roles from the above
882: # loop and the sorting time will be negligible.
883: if (scalar(keys(%Pending))) {
884: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 885: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 886: }
887: if (scalar(keys(%Expired))) {
888: my @sorted = sort {$a <=> $b} keys(%Expired);
889: my $time = pop(@sorted);
1.599 albertel 890: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 891: }
1.599 albertel 892: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 893: }
1.70 www 894:
1.599 albertel 895: sub save_cache {
896: &purge_remembered();
1.722 albertel 897: #&Apache::loncommon::validate_page();
1.620 albertel 898: undef(%env);
1.780 albertel 899: undef($env_loaded);
1.599 albertel 900: }
1.452 albertel 901:
1.599 albertel 902: my $to_remember=-1;
903: my %remembered;
904: my %accessed;
905: my $kicks=0;
906: my $hits=0;
907: sub devalidate_cache_new {
908: my ($name,$id,$debug) = @_;
909: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
910: $id=&escape($name.':'.$id);
911: $memcache->delete($id);
912: delete($remembered{$id});
913: delete($accessed{$id});
914: }
915:
916: sub is_cached_new {
917: my ($name,$id,$debug) = @_;
918: $id=&escape($name.':'.$id);
919: if (exists($remembered{$id})) {
920: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
921: $accessed{$id}=[&gettimeofday()];
922: $hits++;
923: return ($remembered{$id},1);
924: }
925: my $value = $memcache->get($id);
926: if (!(defined($value))) {
927: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 928: return (undef,undef);
1.416 albertel 929: }
1.599 albertel 930: if ($value eq '__undef__') {
931: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
932: $value=undef;
933: }
934: &make_room($id,$value,$debug);
935: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
936: return ($value,1);
937: }
938:
939: sub do_cache_new {
940: my ($name,$id,$value,$time,$debug) = @_;
941: $id=&escape($name.':'.$id);
942: my $setvalue=$value;
943: if (!defined($setvalue)) {
944: $setvalue='__undef__';
945: }
1.623 albertel 946: if (!defined($time) ) {
947: $time=600;
948: }
1.599 albertel 949: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600 albertel 950: $memcache->set($id,$setvalue,$time);
951: # need to make a copy of $value
952: #&make_room($id,$value,$debug);
1.599 albertel 953: return $value;
954: }
955:
956: sub make_room {
957: my ($id,$value,$debug)=@_;
958: $remembered{$id}=$value;
959: if ($to_remember<0) { return; }
960: $accessed{$id}=[&gettimeofday()];
961: if (scalar(keys(%remembered)) <= $to_remember) { return; }
962: my $to_kick;
963: my $max_time=0;
964: foreach my $other (keys(%accessed)) {
965: if (&tv_interval($accessed{$other}) > $max_time) {
966: $to_kick=$other;
967: $max_time=&tv_interval($accessed{$other});
968: }
969: }
970: delete($remembered{$to_kick});
971: delete($accessed{$to_kick});
972: $kicks++;
973: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 974: return;
975: }
976:
1.599 albertel 977: sub purge_remembered {
1.604 albertel 978: #&logthis("Tossing ".scalar(keys(%remembered)));
979: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 980: undef(%remembered);
981: undef(%accessed);
1.428 albertel 982: }
1.70 www 983: # ------------------------------------- Read an entry from a user's environment
984:
985: sub userenvironment {
986: my ($udom,$unam,@what)=@_;
987: my %returnhash=();
988: my @answer=split(/\&/,
989: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
990: &homeserver($unam,$udom)));
991: my $i;
992: for ($i=0;$i<=$#what;$i++) {
993: $returnhash{$what[$i]}=&unescape($answer[$i]);
994: }
995: return %returnhash;
1.1 albertel 996: }
997:
1.617 albertel 998: # ---------------------------------------------------------- Get a studentphoto
999: sub studentphoto {
1000: my ($udom,$unam,$ext) = @_;
1001: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1002: if (defined($env{'request.course.id'})) {
1.708 raeburn 1003: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1004: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1005: return(&retrievestudentphoto($udom,$unam,$ext));
1006: } else {
1007: my ($result,$perm_reqd)=
1.707 albertel 1008: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1009: if ($result eq 'ok') {
1010: if (!($perm_reqd eq 'yes')) {
1011: return(&retrievestudentphoto($udom,$unam,$ext));
1012: }
1013: }
1014: }
1015: }
1016: } else {
1017: my ($result,$perm_reqd) =
1.707 albertel 1018: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1019: if ($result eq 'ok') {
1020: if (!($perm_reqd eq 'yes')) {
1021: return(&retrievestudentphoto($udom,$unam,$ext));
1022: }
1023: }
1024: }
1025: return '/adm/lonKaputt/lonlogo_broken.gif';
1026: }
1027:
1028: sub retrievestudentphoto {
1029: my ($udom,$unam,$ext,$type) = @_;
1030: my $home=&Apache::lonnet::homeserver($unam,$udom);
1031: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1032: if ($ret eq 'ok') {
1033: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1034: if ($type eq 'thumbnail') {
1035: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1036: }
1037: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1038: return $tokenurl;
1039: } else {
1040: if ($type eq 'thumbnail') {
1041: return '/adm/lonKaputt/genericstudent_tn.gif';
1042: } else {
1043: return '/adm/lonKaputt/lonlogo_broken.gif';
1044: }
1.617 albertel 1045: }
1046: }
1047:
1.263 www 1048: # -------------------------------------------------------------------- New chat
1049:
1050: sub chatsend {
1.724 raeburn 1051: my ($newentry,$anon,$group)=@_;
1.620 albertel 1052: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1053: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1054: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1055: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1056: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1057: &escape($newentry)).':'.$group,$chome);
1.292 www 1058: }
1059:
1060: # ------------------------------------------ Find current version of a resource
1061:
1062: sub getversion {
1063: my $fname=&clutter(shift);
1064: unless ($fname=~/^\/res\//) { return -1; }
1065: return ¤tversion(&filelocation('',$fname));
1066: }
1067:
1068: sub currentversion {
1069: my $fname=shift;
1.599 albertel 1070: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1071: if (defined($cached)) { return $result; }
1.292 www 1072: my $author=$fname;
1073: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1074: my ($udom,$uname)=split(/\//,$author);
1075: my $home=homeserver($uname,$udom);
1076: if ($home eq 'no_host') {
1077: return -1;
1078: }
1079: my $answer=reply("currentversion:$fname",$home);
1080: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1081: return -1;
1082: }
1.599 albertel 1083: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1084: }
1085:
1.1 albertel 1086: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1087:
1.1 albertel 1088: sub subscribe {
1089: my $fname=shift;
1.761 raeburn 1090: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1091: $fname=~s/[\n\r]//g;
1.1 albertel 1092: my $author=$fname;
1093: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1094: my ($udom,$uname)=split(/\//,$author);
1095: my $home=homeserver($uname,$udom);
1.335 albertel 1096: if ($home eq 'no_host') {
1097: return 'not_found';
1.1 albertel 1098: }
1099: my $answer=reply("sub:$fname",$home);
1.64 www 1100: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1101: $answer.=' by '.$home;
1102: }
1.1 albertel 1103: return $answer;
1104: }
1105:
1.8 www 1106: # -------------------------------------------------------------- Replicate file
1107:
1108: sub repcopy {
1109: my $filename=shift;
1.23 www 1110: $filename=~s/\/+/\//g;
1.607 raeburn 1111: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1112: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1113: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1114: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1115: return &repcopy_userfile($filename);
1116: }
1.532 albertel 1117: $filename=~s/[\n\r]//g;
1.8 www 1118: my $transname="$filename.in.transfer";
1.607 raeburn 1119: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1120: my $remoteurl=subscribe($filename);
1.64 www 1121: if ($remoteurl =~ /^con_lost by/) {
1122: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1123: return 'unavailable';
1.8 www 1124: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1125: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1126: return 'not_found';
1.64 www 1127: } elsif ($remoteurl =~ /^rejected by/) {
1128: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1129: return 'forbidden';
1.20 www 1130: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1131: return 'ok';
1.8 www 1132: } else {
1.290 www 1133: my $author=$filename;
1134: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1135: my ($udom,$uname)=split(/\//,$author);
1136: my $home=homeserver($uname,$udom);
1137: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1138: my @parts=split(/\//,$filename);
1139: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1140: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1141: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1142: return 'bad_request';
1.8 www 1143: }
1144: my $count;
1145: for ($count=5;$count<$#parts;$count++) {
1146: $path.="/$parts[$count]";
1147: if ((-e $path)!=1) {
1148: mkdir($path,0777);
1149: }
1150: }
1151: my $ua=new LWP::UserAgent;
1152: my $request=new HTTP::Request('GET',"$remoteurl");
1153: my $response=$ua->request($request,$transname);
1154: if ($response->is_error()) {
1155: unlink($transname);
1156: my $message=$response->status_line;
1.672 albertel 1157: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1158: ." LWP get: $message: $filename</font>");
1.607 raeburn 1159: return 'unavailable';
1.8 www 1160: } else {
1.16 www 1161: if ($remoteurl!~/\.meta$/) {
1162: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1163: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1164: if ($mresponse->is_error()) {
1165: unlink($filename.'.meta');
1166: &logthis(
1.672 albertel 1167: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1168: }
1169: }
1.8 www 1170: rename($transname,$filename);
1.607 raeburn 1171: return 'ok';
1.8 www 1172: }
1.290 www 1173: }
1.8 www 1174: }
1.330 www 1175: }
1176:
1177: # ------------------------------------------------ Get server side include body
1178: sub ssi_body {
1.381 albertel 1179: my ($filelink,%form)=@_;
1.606 matthew 1180: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1181: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1182: }
1.330 www 1183: my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381 albertel 1184: &ssi($filelink,%form));
1.778 albertel 1185: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1186: $output=~s/^.*?\<body[^\>]*\>//si;
1187: $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330 www 1188: return $output;
1.8 www 1189: }
1190:
1.15 www 1191: # --------------------------------------------------------- Server Side Include
1192:
1.782 albertel 1193: sub absolute_url {
1194: my ($host_name) = @_;
1195: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1196: if ($host_name eq '') {
1197: $host_name = $ENV{'SERVER_NAME'};
1198: }
1199: return $protocol.$host_name;
1200: }
1201:
1.15 www 1202: sub ssi {
1203:
1.23 www 1204: my ($fn,%form)=@_;
1.15 www 1205:
1206: my $ua=new LWP::UserAgent;
1.23 www 1207:
1208: my $request;
1.711 albertel 1209:
1210: $form{'no_update_last_known'}=1;
1211:
1.23 www 1212: if (%form) {
1.782 albertel 1213: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201 albertel 1214: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23 www 1215: } else {
1.782 albertel 1216: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1217: }
1218:
1.15 www 1219: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1220: my $response=$ua->request($request);
1221:
1.324 www 1222: return $response->content;
1223: }
1224:
1225: sub externalssi {
1226: my ($url)=@_;
1227: my $ua=new LWP::UserAgent;
1228: my $request=new HTTP::Request('GET',$url);
1229: my $response=$ua->request($request);
1.15 www 1230: return $response->content;
1231: }
1.254 www 1232:
1.492 albertel 1233: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1234:
1235: sub allowuploaded {
1236: my ($srcurl,$url)=@_;
1237: $url=&clutter(&declutter($url));
1238: my $dir=$url;
1239: $dir=~s/\/[^\/]+$//;
1240: my %httpref=();
1241: my $httpurl=&hreflocation('',$url);
1242: $httpref{'httpref.'.$httpurl}=$srcurl;
1243: &Apache::lonnet::appenv(%httpref);
1.254 www 1244: }
1.477 raeburn 1245:
1.478 albertel 1246: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1247: # input: action, courseID, current domain, intended
1.637 raeburn 1248: # path to file, source of file, instruction to parse file for objects,
1249: # ref to hash for embedded objects,
1250: # ref to hash for codebase of java objects.
1251: #
1.485 raeburn 1252: # output: url to file (if action was uploaddoc),
1253: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 1254: #
1.478 albertel 1255: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1256: # course.
1.477 raeburn 1257: #
1.478 albertel 1258: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1259: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1260: # course's home server.
1.477 raeburn 1261: #
1.478 albertel 1262: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1263: # be copied from $source (current location) to
1264: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1265: # and will then be copied to
1266: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1267: # course's home server.
1.485 raeburn 1268: #
1.481 raeburn 1269: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 1270: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 1271: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1272: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1273: # in course's home server.
1.637 raeburn 1274: #
1.477 raeburn 1275:
1276: sub process_coursefile {
1.638 albertel 1277: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 1278: my $fetchresult;
1.638 albertel 1279: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 1280: if ($action eq 'propagate') {
1.638 albertel 1281: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1282: $home);
1.481 raeburn 1283: } else {
1.477 raeburn 1284: my $fpath = '';
1285: my $fname = $file;
1.478 albertel 1286: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 1287: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 1288: my $filepath = &build_filepath($fpath);
1.481 raeburn 1289: if ($action eq 'copy') {
1290: if ($source eq '') {
1291: $fetchresult = 'no source file';
1292: return $fetchresult;
1293: } else {
1294: my $destination = $filepath.'/'.$fname;
1295: rename($source,$destination);
1296: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1297: $home);
1.481 raeburn 1298: }
1299: } elsif ($action eq 'uploaddoc') {
1300: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 1301: print $fh $env{'form.'.$source};
1.481 raeburn 1302: close($fh);
1.637 raeburn 1303: if ($parser eq 'parse') {
1304: my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
1305: unless ($parse_result eq 'ok') {
1306: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1307: }
1308: }
1.477 raeburn 1309: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1310: $home);
1.481 raeburn 1311: if ($fetchresult eq 'ok') {
1312: return '/uploaded/'.$fpath.'/'.$fname;
1313: } else {
1314: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1315: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 1316: return '/adm/notfound.html';
1317: }
1.477 raeburn 1318: }
1319: }
1.485 raeburn 1320: unless ( $fetchresult eq 'ok') {
1.477 raeburn 1321: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1322: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 1323: }
1324: return $fetchresult;
1325: }
1326:
1.637 raeburn 1327: sub build_filepath {
1328: my ($fpath) = @_;
1329: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1330: unless ($fpath eq '') {
1331: my @parts=split('/',$fpath);
1332: foreach my $part (@parts) {
1333: $filepath.= '/'.$part;
1334: if ((-e $filepath)!=1) {
1335: mkdir($filepath,0777);
1336: }
1337: }
1338: }
1339: return $filepath;
1340: }
1341:
1342: sub store_edited_file {
1.638 albertel 1343: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 1344: my $file = $primary_url;
1345: $file =~ s#^/uploaded/$docudom/$docuname/##;
1346: my $fpath = '';
1347: my $fname = $file;
1348: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1349: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1350: my $filepath = &build_filepath($fpath);
1351: open(my $fh,'>'.$filepath.'/'.$fname);
1352: print $fh $content;
1353: close($fh);
1.638 albertel 1354: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 1355: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1356: $home);
1.637 raeburn 1357: if ($$fetchresult eq 'ok') {
1358: return '/uploaded/'.$fpath.'/'.$fname;
1359: } else {
1.638 albertel 1360: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1361: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 1362: return '/adm/notfound.html';
1363: }
1364: }
1365:
1.531 albertel 1366: sub clean_filename {
1367: my ($fname)=@_;
1.315 www 1368: # Replace Windows backslashes by forward slashes
1.257 www 1369: $fname=~s/\\/\//g;
1.315 www 1370: # Get rid of everything but the actual filename
1.257 www 1371: $fname=~s/^.*\/([^\/]+)$/$1/;
1.315 www 1372: # Replace spaces by underscores
1373: $fname=~s/\s+/\_/g;
1374: # Replace all other weird characters by nothing
1.317 www 1375: $fname=~s/[^\w\.\-]//g;
1.540 albertel 1376: # Replace all .\d. sequences with _\d. so they no longer look like version
1377: # numbers
1378: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 1379: return $fname;
1380: }
1381:
1.608 albertel 1382: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 1383: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 1384: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 1385: # $coursedoc - if true up to the current course
1386: # if false
1387: # $subdir - directory in userfile to store the file into
1388: # $parser, $allfiles, $codebase - unknown
1389: #
1390: # output: url of file in userspace, or error: <message>
1391: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 1392:
1393:
1.531 albertel 1394: sub userfileupload {
1.719 banghart 1395: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531 albertel 1396: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 1397: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 1398: $fname=&clean_filename($fname);
1.315 www 1399: # See if there is anything left
1.257 www 1400: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 1401: chop($env{'form.'.$formname});
1.523 raeburn 1402: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
1403: my $now = time;
1404: my $filepath = 'tmp/helprequests/'.$now;
1405: my @parts=split(/\//,$filepath);
1406: my $fullpath = $perlvar{'lonDaemons'};
1407: for (my $i=0;$i<@parts;$i++) {
1408: $fullpath .= '/'.$parts[$i];
1409: if ((-e $fullpath)!=1) {
1410: mkdir($fullpath,0777);
1411: }
1412: }
1413: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 1414: print $fh $env{'form.'.$formname};
1.523 raeburn 1415: close($fh);
1.741 raeburn 1416: return $fullpath.'/'.$fname;
1417: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
1418: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
1419: '_'.$env{'user.domain'}.'/pending';
1420: my @parts=split(/\//,$filepath);
1421: my $fullpath = $perlvar{'lonDaemons'};
1422: for (my $i=0;$i<@parts;$i++) {
1423: $fullpath .= '/'.$parts[$i];
1424: if ((-e $fullpath)!=1) {
1425: mkdir($fullpath,0777);
1426: }
1427: }
1428: open(my $fh,'>'.$fullpath.'/'.$fname);
1429: print $fh $env{'form.'.$formname};
1430: close($fh);
1431: return $fullpath.'/'.$fname;
1.523 raeburn 1432: }
1.719 banghart 1433:
1.258 www 1434: # Create the directory if not present
1.493 albertel 1435: $fname="$subdir/$fname";
1.259 www 1436: if ($coursedoc) {
1.638 albertel 1437: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1438: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 1439: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 1440: return &finishuserfileupload($docuname,$docudom,
1441: $formname,$fname,$parser,$allfiles,
1442: $codebase);
1.481 raeburn 1443: } else {
1.620 albertel 1444: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 1445: return &process_coursefile('uploaddoc',$docuname,$docudom,
1446: $fname,$formname,$parser,
1447: $allfiles,$codebase);
1.481 raeburn 1448: }
1.719 banghart 1449: } elsif (defined($destuname)) {
1450: my $docuname=$destuname;
1451: my $docudom=$destudom;
1452: return &finishuserfileupload($docuname,$docudom,$formname,
1453: $fname,$parser,$allfiles,$codebase);
1454:
1.259 www 1455: } else {
1.638 albertel 1456: my $docuname=$env{'user.name'};
1457: my $docudom=$env{'user.domain'};
1.714 raeburn 1458: if (exists($env{'form.group'})) {
1459: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1460: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1461: }
1.638 albertel 1462: return &finishuserfileupload($docuname,$docudom,$formname,
1463: $fname,$parser,$allfiles,$codebase);
1.259 www 1464: }
1.271 www 1465: }
1466:
1467: sub finishuserfileupload {
1.638 albertel 1468: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477 raeburn 1469: my $path=$docudom.'/'.$docuname.'/';
1.258 www 1470: my $filepath=$perlvar{'lonDocRoot'};
1.494 albertel 1471: my ($fnamepath,$file);
1472: $file=$fname;
1473: if ($fname=~m|/|) {
1474: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
1475: $path.=$fnamepath.'/';
1476: }
1.259 www 1477: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 1478: my $count;
1479: for ($count=4;$count<=$#parts;$count++) {
1480: $filepath.="/$parts[$count]";
1481: if ((-e $filepath)!=1) {
1482: mkdir($filepath,0777);
1483: }
1484: }
1485: # Save the file
1486: {
1.701 albertel 1487: if (!open(FH,'>'.$filepath.'/'.$file)) {
1488: &logthis('Failed to create '.$filepath.'/'.$file);
1489: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
1490: return '/adm/notfound.html';
1491: }
1492: if (!print FH ($env{'form.'.$formname})) {
1493: &logthis('Failed to write to '.$filepath.'/'.$file);
1494: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
1495: return '/adm/notfound.html';
1496: }
1.570 albertel 1497: close(FH);
1.258 www 1498: }
1.637 raeburn 1499: if ($parser eq 'parse') {
1.638 albertel 1500: my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
1501: $codebase);
1.637 raeburn 1502: unless ($parse_result eq 'ok') {
1.638 albertel 1503: &logthis('Failed to parse '.$filepath.$file.
1504: ' for embedded media: '.$parse_result);
1.637 raeburn 1505: }
1506: }
1.259 www 1507: # Notify homeserver to grep it
1508: #
1.638 albertel 1509: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 1510: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 1511: if ($fetchresult eq 'ok') {
1.259 www 1512: #
1.258 www 1513: # Return the URL to it
1.494 albertel 1514: return '/uploaded/'.$path.$file;
1.263 www 1515: } else {
1.494 albertel 1516: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
1517: ': '.$fetchresult);
1.263 www 1518: return '/adm/notfound.html';
1519: }
1.493 albertel 1520: }
1521:
1.637 raeburn 1522: sub extract_embedded_items {
1.648 raeburn 1523: my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637 raeburn 1524: my @state = ();
1525: my %javafiles = (
1526: codebase => '',
1527: code => '',
1528: archive => ''
1529: );
1530: my %mediafiles = (
1531: src => '',
1532: movie => '',
1533: );
1.648 raeburn 1534: my $p;
1535: if ($content) {
1536: $p = HTML::LCParser->new($content);
1537: } else {
1538: $p = HTML::LCParser->new($filepath.'/'.$file);
1539: }
1.641 albertel 1540: while (my $t=$p->get_token()) {
1.640 albertel 1541: if ($t->[0] eq 'S') {
1542: my ($tagname, $attr) = ($t->[1],$t->[2]);
1543: push (@state, $tagname);
1.648 raeburn 1544: if (lc($tagname) eq 'allow') {
1545: &add_filetype($allfiles,$attr->{'src'},'src');
1546: }
1.640 albertel 1547: if (lc($tagname) eq 'img') {
1548: &add_filetype($allfiles,$attr->{'src'},'src');
1549: }
1.645 raeburn 1550: if (lc($tagname) eq 'script') {
1551: if ($attr->{'archive'} =~ /\.jar$/i) {
1552: &add_filetype($allfiles,$attr->{'archive'},'archive');
1553: } else {
1554: &add_filetype($allfiles,$attr->{'src'},'src');
1555: }
1556: }
1557: if (lc($tagname) eq 'link') {
1558: if (lc($attr->{'rel'}) eq 'stylesheet') {
1559: &add_filetype($allfiles,$attr->{'href'},'href');
1560: }
1561: }
1.640 albertel 1562: if (lc($tagname) eq 'object' ||
1563: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
1564: foreach my $item (keys(%javafiles)) {
1565: $javafiles{$item} = '';
1566: }
1567: }
1568: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
1569: my $name = lc($attr->{'name'});
1570: foreach my $item (keys(%javafiles)) {
1571: if ($name eq $item) {
1572: $javafiles{$item} = $attr->{'value'};
1573: last;
1574: }
1575: }
1576: foreach my $item (keys(%mediafiles)) {
1577: if ($name eq $item) {
1578: &add_filetype($allfiles, $attr->{'value'}, 'value');
1579: last;
1580: }
1581: }
1582: }
1583: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
1584: foreach my $item (keys(%javafiles)) {
1585: if ($attr->{$item}) {
1586: $javafiles{$item} = $attr->{$item};
1587: last;
1588: }
1589: }
1590: foreach my $item (keys(%mediafiles)) {
1591: if ($attr->{$item}) {
1592: &add_filetype($allfiles,$attr->{$item},$item);
1593: last;
1594: }
1595: }
1596: }
1597: } elsif ($t->[0] eq 'E') {
1598: my ($tagname) = ($t->[1]);
1599: if ($javafiles{'codebase'} ne '') {
1600: $javafiles{'codebase'} .= '/';
1601: }
1602: if (lc($tagname) eq 'applet' ||
1603: lc($tagname) eq 'object' ||
1604: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
1605: ) {
1606: foreach my $item (keys(%javafiles)) {
1607: if ($item ne 'codebase' && $javafiles{$item} ne '') {
1608: my $file=$javafiles{'codebase'}.$javafiles{$item};
1609: &add_filetype($allfiles,$file,$item);
1610: }
1611: }
1612: }
1613: pop @state;
1614: }
1615: }
1.637 raeburn 1616: return 'ok';
1617: }
1618:
1.639 albertel 1619: sub add_filetype {
1620: my ($allfiles,$file,$type)=@_;
1621: if (exists($allfiles->{$file})) {
1622: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
1623: push(@{$allfiles->{$file}}, &escape($type));
1624: }
1625: } else {
1626: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 1627: }
1628: }
1629:
1.493 albertel 1630: sub removeuploadedurl {
1631: my ($url)=@_;
1632: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 1633: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 1634: }
1635:
1636: sub removeuserfile {
1637: my ($docuname,$docudom,$fname)=@_;
1638: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 1639: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1640: if ($result eq 'ok') {
1641: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
1642: my $metafile = $fname.'.meta';
1643: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1644: }
1645: }
1646: return $result;
1.257 www 1647: }
1.15 www 1648:
1.530 albertel 1649: sub mkdiruserfile {
1650: my ($docuname,$docudom,$dir)=@_;
1651: my $home=&homeserver($docuname,$docudom);
1652: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
1653: }
1654:
1.531 albertel 1655: sub renameuserfile {
1656: my ($docuname,$docudom,$old,$new)=@_;
1657: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 1658: my $result = &reply("renameuserfile:$docudom:$docuname:".
1659: &escape("$old").':'.&escape("$new"),$home);
1660: if ($result eq 'ok') {
1661: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
1662: my $oldmeta = $old.'.meta';
1663: my $newmeta = $new.'.meta';
1664: my $metaresult =
1665: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1666: }
1667: }
1668: return $result;
1.531 albertel 1669: }
1670:
1.14 www 1671: # ------------------------------------------------------------------------- Log
1672:
1673: sub log {
1674: my ($dom,$nam,$hom,$what)=@_;
1.47 www 1675: return critical("log:$dom:$nam:$what",$hom);
1.157 www 1676: }
1677:
1678: # ------------------------------------------------------------------ Course Log
1.352 www 1679: #
1680: # This routine flushes several buffers of non-mission-critical nature
1681: #
1.157 www 1682:
1683: sub flushcourselogs {
1.352 www 1684: &logthis('Flushing log buffers');
1685: #
1686: # course logs
1687: # This is a log of all transactions in a course, which can be used
1688: # for data mining purposes
1689: #
1690: # It also collects the courseid database, which lists last transaction
1691: # times and course titles for all courseids
1692: #
1693: my %courseidbuffer=();
1.800 albertel 1694: foreach my $crsid (keys %courselogs) {
1.352 www 1695: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 1696: &escape($courselogs{$crsid}),
1697: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 1698: delete $courselogs{$crsid};
1699: } else {
1700: &logthis('Failed to flush log buffer for '.$crsid);
1701: if (length($courselogs{$crsid})>40000) {
1.672 albertel 1702: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 1703: " exceeded maximum size, deleting.</font>");
1704: delete $courselogs{$crsid};
1705: }
1.352 www 1706: }
1707: if ($courseidbuffer{$coursehombuf{$crsid}}) {
1708: $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516 raeburn 1709: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741 raeburn 1710: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352 www 1711: } else {
1712: $courseidbuffer{$coursehombuf{$crsid}}=
1.516 raeburn 1713: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741 raeburn 1714: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571 raeburn 1715: }
1.191 harris41 1716: }
1.352 www 1717: #
1718: # Write course id database (reverse lookup) to homeserver of courses
1719: # Is used in pickcourse
1720: #
1.800 albertel 1721: foreach my $crsid (keys(%courseidbuffer)) {
1722: &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
1.352 www 1723: }
1724: #
1725: # File accesses
1726: # Writes to the dynamic metadata of resources to get hit counts, etc.
1727: #
1.449 matthew 1728: foreach my $entry (keys(%accesshash)) {
1.458 matthew 1729: if ($entry =~ /___count$/) {
1730: my ($dom,$name);
1731: ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
1732: if (! defined($dom) || $dom eq '' ||
1733: ! defined($name) || $name eq '') {
1.620 albertel 1734: my $cid = $env{'request.course.id'};
1735: $dom = $env{'request.'.$cid.'.domain'};
1736: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 1737: }
1.450 matthew 1738: my $value = $accesshash{$entry};
1739: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
1740: my %temphash=($url => $value);
1.449 matthew 1741: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
1742: if ($result eq 'ok') {
1743: delete $accesshash{$entry};
1744: } elsif ($result eq 'unknown_cmd') {
1745: # Target server has old code running on it.
1.450 matthew 1746: my %temphash=($entry => $value);
1.449 matthew 1747: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1748: delete $accesshash{$entry};
1749: }
1750: }
1751: } else {
1.458 matthew 1752: my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450 matthew 1753: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 1754: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1755: delete $accesshash{$entry};
1756: }
1.185 www 1757: }
1.191 harris41 1758: }
1.352 www 1759: #
1760: # Roles
1761: # Reverse lookup of user roles for course faculty/staff and co-authorship
1762: #
1.800 albertel 1763: foreach my $entry (keys(%userrolehash)) {
1.351 www 1764: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 1765: split(/\:/,$entry);
1766: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 1767: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 1768: $rudom,$runame) eq 'ok') {
1769: delete $userrolehash{$entry};
1770: }
1771: }
1.662 raeburn 1772: #
1773: # Reverse lookup of domain roles (dc, ad, li, sc, au)
1774: #
1775: my %domrolebuffer = ();
1776: foreach my $entry (keys %domainrolehash) {
1777: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
1778: if ($domrolebuffer{$rudom}) {
1779: $domrolebuffer{$rudom}.='&'.&escape($entry).
1780: '='.&escape($domainrolehash{$entry});
1781: } else {
1782: $domrolebuffer{$rudom}.=&escape($entry).
1783: '='.&escape($domainrolehash{$entry});
1784: }
1785: delete $domainrolehash{$entry};
1786: }
1787: foreach my $dom (keys(%domrolebuffer)) {
1788: foreach my $tryserver (keys %libserv) {
1789: if ($hostdom{$tryserver} eq $dom) {
1790: unless (&reply('domroleput:'.$dom.':'.
1791: $domrolebuffer{$dom},$tryserver) eq 'ok') {
1792: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
1793: }
1794: }
1795: }
1796: }
1.186 www 1797: $dumpcount++;
1.157 www 1798: }
1799:
1800: sub courselog {
1801: my $what=shift;
1.158 www 1802: $what=time.':'.$what;
1.620 albertel 1803: unless ($env{'request.course.id'}) { return ''; }
1804: $coursedombuf{$env{'request.course.id'}}=
1805: $env{'course.'.$env{'request.course.id'}.'.domain'};
1806: $coursenumbuf{$env{'request.course.id'}}=
1807: $env{'course.'.$env{'request.course.id'}.'.num'};
1808: $coursehombuf{$env{'request.course.id'}}=
1809: $env{'course.'.$env{'request.course.id'}.'.home'};
1810: $coursedescrbuf{$env{'request.course.id'}}=
1811: $env{'course.'.$env{'request.course.id'}.'.description'};
1812: $courseinstcodebuf{$env{'request.course.id'}}=
1813: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
1814: $courseownerbuf{$env{'request.course.id'}}=
1815: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 1816: $coursetypebuf{$env{'request.course.id'}}=
1817: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 1818: if (defined $courselogs{$env{'request.course.id'}}) {
1819: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 1820: } else {
1.620 albertel 1821: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 1822: }
1.620 albertel 1823: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 1824: &flushcourselogs();
1825: }
1.158 www 1826: }
1827:
1828: sub courseacclog {
1829: my $fnsymb=shift;
1.620 albertel 1830: unless ($env{'request.course.id'}) { return ''; }
1831: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 1832: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 1833: $what.=':POST';
1.583 matthew 1834: # FIXME: Probably ought to escape things....
1.800 albertel 1835: foreach my $key (keys(%env)) {
1836: if ($key=~/^form\.(.*)/) {
1837: $what.=':'.$1.'='.$env{$key};
1.158 www 1838: }
1.191 harris41 1839: }
1.583 matthew 1840: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
1841: # FIXME: We should not be depending on a form parameter that someone
1842: # editing lonsearchcat.pm might change in the future.
1.620 albertel 1843: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 1844: $what.= ':POST';
1845: # FIXME: Probably ought to escape things....
1846: foreach my $element ('courseexp','crsfulltext','crsrelated',
1847: 'crsdiscuss') {
1.620 albertel 1848: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 1849: }
1850: }
1.158 www 1851: }
1852: &courselog($what);
1.149 www 1853: }
1854:
1.185 www 1855: sub countacc {
1856: my $url=&declutter(shift);
1.458 matthew 1857: return if (! defined($url) || $url eq '');
1.620 albertel 1858: unless ($env{'request.course.id'}) { return ''; }
1859: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 1860: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 1861: $accesshash{$key}++;
1.185 www 1862: }
1.349 www 1863:
1.361 www 1864: sub linklog {
1865: my ($from,$to)=@_;
1866: $from=&declutter($from);
1867: $to=&declutter($to);
1868: $accesshash{$from.'___'.$to.'___comefrom'}=1;
1869: $accesshash{$to.'___'.$from.'___goto'}=1;
1870: }
1871:
1.349 www 1872: sub userrolelog {
1873: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 1874: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 1875: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 1876: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1877: ($trole=~/^ta/)) {
1.350 www 1878: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
1879: $userrolehash
1880: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 1881: =$tend.':'.$tstart;
1.662 raeburn 1882: }
1883: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
1884: ($trole=~/^li/) || ($trole=~/^li/) ||
1885: ($trole=~/^au/) || ($trole=~/^dg/) ||
1886: ($trole=~/^sc/)) {
1887: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
1888: $domainrolehash
1889: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1890: = $tend.':'.$tstart;
1891: }
1.351 www 1892: }
1893:
1894: sub get_course_adv_roles {
1895: my $cid=shift;
1.620 albertel 1896: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 1897: my %coursehash=&coursedescription($cid);
1.470 www 1898: my %nothide=();
1.800 albertel 1899: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1900: $nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470 www 1901: }
1.351 www 1902: my %returnhash=();
1903: my %dumphash=
1904: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
1905: my $now=time;
1.800 albertel 1906: foreach my $entry (keys %dumphash) {
1907: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 1908: if (($tstart) && ($tstart<0)) { next; }
1909: if (($tend) && ($tend<$now)) { next; }
1910: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 1911: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 1912: if ($username eq '' || $domain eq '') { next; }
1.470 www 1913: if ((&privileged($username,$domain)) &&
1914: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 1915: if ($role eq 'cr') { next; }
1.351 www 1916: my $key=&plaintext($role);
1917: if ($section) { $key.=' (Sec/Grp '.$section.')'; }
1918: if ($returnhash{$key}) {
1919: $returnhash{$key}.=','.$username.':'.$domain;
1920: } else {
1921: $returnhash{$key}=$username.':'.$domain;
1922: }
1.400 www 1923: }
1924: return %returnhash;
1925: }
1926:
1927: sub get_my_roles {
1928: my ($uname,$udom)=@_;
1.620 albertel 1929: unless (defined($uname)) { $uname=$env{'user.name'}; }
1930: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400 www 1931: my %dumphash=
1932: &dump('nohist_userroles',$udom,$uname);
1933: my %returnhash=();
1934: my $now=time;
1.800 albertel 1935: foreach my $entry (keys(%dumphash)) {
1936: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400 www 1937: if (($tstart) && ($tstart<0)) { next; }
1938: if (($tend) && ($tend<$now)) { next; }
1939: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 1940: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.400 www 1941: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373 www 1942: }
1943: return %returnhash;
1.399 www 1944: }
1945:
1946: # ----------------------------------------------------- Frontpage Announcements
1947: #
1948: #
1949:
1950: sub postannounce {
1951: my ($server,$text)=@_;
1952: unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
1953: unless ($text=~/\w/) { $text=''; }
1954: return &reply('setannounce:'.&escape($text),$server);
1955: }
1956:
1957: sub getannounce {
1.448 albertel 1958:
1959: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 1960: my $announcement='';
1.800 albertel 1961: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 1962: close($fh);
1.399 www 1963: if ($announcement=~/\w/) {
1964: return
1965: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 1966: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 1967: } else {
1968: return '';
1969: }
1970: } else {
1971: return '';
1972: }
1.351 www 1973: }
1.353 www 1974:
1975: # ---------------------------------------------------------- Course ID routines
1976: # Deal with domain's nohist_courseid.db files
1977: #
1978:
1979: sub courseidput {
1980: my ($domain,$what,$coursehome)=@_;
1981: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
1982: }
1983:
1984: sub courseiddump {
1.791 raeburn 1985: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353 www 1986: my %returnhash=();
1.355 www 1987: unless ($domfilter) { $domfilter=''; }
1.353 www 1988: foreach my $tryserver (keys %libserv) {
1.511 raeburn 1989: if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506 raeburn 1990: if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.800 albertel 1991: foreach my $line (
1.506 raeburn 1992: split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571 raeburn 1993: $sincefilter.':'.&escape($descfilter).':'.
1.791 raeburn 1994: &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354 www 1995: $tryserver))) {
1.800 albertel 1996: my ($key,$value)=split(/\=/,$line,2);
1.506 raeburn 1997: if (($key) && ($value)) {
1.516 raeburn 1998: $returnhash{&unescape($key)}=$value;
1.506 raeburn 1999: }
1.353 www 2000: }
2001: }
2002: }
2003: }
2004: return %returnhash;
2005: }
2006:
1.658 raeburn 2007: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 2008:
2009: sub dcmailput {
1.685 raeburn 2010: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 2011: my $status = &Apache::lonnet::critical(
1.740 www 2012: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2013: &escape($message),$server);
1.662 raeburn 2014: return $status;
2015: }
2016:
1.658 raeburn 2017: sub dcmaildump {
2018: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 2019: my %returnhash=();
2020: if (exists($domain_primary{$dom})) {
2021: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2022: &escape($enddate).':';
2023: my @esc_senders=map { &escape($_)} @$senders;
2024: $cmd.=&escape(join('&',@esc_senders));
1.800 albertel 2025: foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
2026: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 2027: if (($key) && ($value)) {
2028: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 2029: }
2030: }
2031: }
2032: return %returnhash;
2033: }
1.662 raeburn 2034: # ---------------------------------------------------------- Domain roles
2035:
2036: sub get_domain_roles {
2037: my ($dom,$roles,$startdate,$enddate)=@_;
2038: if (undef($startdate) || $startdate eq '') {
2039: $startdate = '.';
2040: }
2041: if (undef($enddate) || $enddate eq '') {
2042: $enddate = '.';
2043: }
2044: my $rolelist = join(':',@{$roles});
2045: my %personnel = ();
2046: foreach my $tryserver (keys(%libserv)) {
2047: if ($hostdom{$tryserver} eq $dom) {
2048: %{$personnel{$tryserver}}=();
1.800 albertel 2049: foreach my $line (
1.662 raeburn 2050: split(/\&/,&reply('domrolesdump:'.$dom.':'.
2051: &escape($startdate).':'.&escape($enddate).':'.
2052: &escape($rolelist), $tryserver))) {
1.800 albertel 2053: my ($key,$value) = split(/\=/,$line,2);
1.662 raeburn 2054: if (($key) && ($value)) {
2055: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2056: }
2057: }
2058: }
2059: }
2060: return %personnel;
2061: }
1.658 raeburn 2062:
1.149 www 2063: # ----------------------------------------------------------- Check out an item
2064:
1.504 albertel 2065: sub get_first_access {
2066: my ($type,$argsymb)=@_;
1.790 albertel 2067: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2068: if ($argsymb) { $symb=$argsymb; }
2069: my ($map,$id,$res)=&decode_symb($symb);
1.588 albertel 2070: if ($type eq 'map') {
2071: $res=&symbread($map);
2072: } else {
2073: $res=$symb;
2074: }
2075: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2076: return $times{"$courseid\0$res"};
1.504 albertel 2077: }
2078:
2079: sub set_first_access {
2080: my ($type)=@_;
1.790 albertel 2081: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2082: my ($map,$id,$res)=&decode_symb($symb);
1.588 albertel 2083: if ($type eq 'map') {
2084: $res=&symbread($map);
2085: } else {
2086: $res=$symb;
2087: }
2088: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 2089: if (!$firstaccess) {
1.588 albertel 2090: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 2091: }
2092: return 'already_set';
1.504 albertel 2093: }
2094:
1.149 www 2095: sub checkout {
2096: my ($symb,$tuname,$tudom,$tcrsid)=@_;
2097: my $now=time;
2098: my $lonhost=$perlvar{'lonHostID'};
2099: my $infostr=&escape(
1.234 www 2100: 'CHECKOUTTOKEN&'.
1.149 www 2101: $tuname.'&'.
2102: $tudom.'&'.
2103: $tcrsid.'&'.
2104: $symb.'&'.
2105: $now.'&'.$ENV{'REMOTE_ADDR'});
2106: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 2107: if ($token=~/^error\:/) {
1.672 albertel 2108: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2109: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
2110: "</font>");
2111: return '';
2112: }
2113:
1.149 www 2114: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
2115: $token=~tr/a-z/A-Z/;
2116:
1.153 www 2117: my %infohash=('resource.0.outtoken' => $token,
2118: 'resource.0.checkouttime' => $now,
2119: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 2120:
2121: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2122: return '';
1.151 www 2123: } else {
1.672 albertel 2124: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2125: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
2126: "</font>");
1.149 www 2127: }
2128:
2129: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2130: &escape('Checkout '.$infostr.' - '.
2131: $token)) ne 'ok') {
2132: return '';
1.151 www 2133: } else {
1.672 albertel 2134: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2135: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
2136: "</font>");
1.149 www 2137: }
1.151 www 2138: return $token;
1.149 www 2139: }
2140:
2141: # ------------------------------------------------------------ Check in an item
2142:
2143: sub checkin {
2144: my $token=shift;
1.150 www 2145: my $now=time;
2146: my ($ta,$tb,$lonhost)=split(/\*/,$token);
2147: $lonhost=~tr/A-Z/a-z/;
1.595 albertel 2148: my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150 www 2149: $dtoken=~s/\W/\_/g;
1.234 www 2150: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 2151: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
2152:
1.154 www 2153: unless (($tuname) && ($tudom)) {
2154: &logthis('Check in '.$token.' ('.$dtoken.') failed');
2155: return '';
2156: }
2157:
2158: unless (&allowed('mgr',$tcrsid)) {
2159: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 2160: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 2161: return '';
2162: }
2163:
1.153 www 2164: my %infohash=('resource.0.intoken' => $token,
2165: 'resource.0.checkintime' => $now,
2166: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 2167:
2168: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2169: return '';
2170: }
2171:
2172: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2173: &escape('Checkin - '.$token)) ne 'ok') {
2174: return '';
2175: }
2176:
2177: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 2178: }
2179:
2180: # --------------------------------------------- Set Expire Date for Spreadsheet
2181:
2182: sub expirespread {
2183: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 2184: my $cid=$env{'request.course.id'};
1.110 www 2185: if ($cid) {
2186: my $now=time;
2187: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 2188: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
2189: $env{'course.'.$cid.'.num'}.
1.110 www 2190: ':nohist_expirationdates:'.
2191: &escape($key).'='.$now,
1.620 albertel 2192: $env{'course.'.$cid.'.home'})
1.110 www 2193: }
2194: return 'ok';
1.14 www 2195: }
2196:
1.109 www 2197: # ----------------------------------------------------- Devalidate Spreadsheets
2198:
2199: sub devalidate {
1.325 www 2200: my ($symb,$uname,$udom)=@_;
1.620 albertel 2201: my $cid=$env{'request.course.id'};
1.109 www 2202: if ($cid) {
1.391 matthew 2203: # delete the stored spreadsheets for
2204: # - the student level sheet of this user in course's homespace
2205: # - the assessment level sheet for this resource
2206: # for this user in user's homespace
1.553 albertel 2207: # - current conditional state info
1.325 www 2208: my $key=$uname.':'.$udom.':';
1.109 www 2209: my $status=
1.299 matthew 2210: &del('nohist_calculatedsheets',
1.391 matthew 2211: [$key.'studentcalc:'],
1.620 albertel 2212: $env{'course.'.$cid.'.domain'},
2213: $env{'course.'.$cid.'.num'})
1.133 albertel 2214: .' '.
2215: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 2216: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 2217: unless ($status eq 'ok ok') {
2218: &logthis('Could not devalidate spreadsheet '.
1.325 www 2219: $uname.' at '.$udom.' for '.
1.109 www 2220: $symb.': '.$status);
1.133 albertel 2221: }
1.553 albertel 2222: &delenv('user.state.'.$cid);
1.109 www 2223: }
2224: }
2225:
1.265 albertel 2226: sub get_scalar {
2227: my ($string,$end) = @_;
2228: my $value;
2229: if ($$string =~ s/^([^&]*?)($end)/$2/) {
2230: $value = $1;
2231: } elsif ($$string =~ s/^([^&]*?)&//) {
2232: $value = $1;
2233: }
2234: return &unescape($value);
2235: }
2236:
2237: sub array2str {
2238: my (@array) = @_;
2239: my $result=&arrayref2str(\@array);
2240: $result=~s/^__ARRAY_REF__//;
2241: $result=~s/__END_ARRAY_REF__$//;
2242: return $result;
2243: }
2244:
1.204 albertel 2245: sub arrayref2str {
2246: my ($arrayref) = @_;
1.265 albertel 2247: my $result='__ARRAY_REF__';
1.204 albertel 2248: foreach my $elem (@$arrayref) {
1.265 albertel 2249: if(ref($elem) eq 'ARRAY') {
2250: $result.=&arrayref2str($elem).'&';
2251: } elsif(ref($elem) eq 'HASH') {
2252: $result.=&hashref2str($elem).'&';
2253: } elsif(ref($elem)) {
2254: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 2255: } else {
2256: $result.=&escape($elem).'&';
2257: }
2258: }
2259: $result=~s/\&$//;
1.265 albertel 2260: $result .= '__END_ARRAY_REF__';
1.204 albertel 2261: return $result;
2262: }
2263:
1.168 albertel 2264: sub hash2str {
1.204 albertel 2265: my (%hash) = @_;
2266: my $result=&hashref2str(\%hash);
1.265 albertel 2267: $result=~s/^__HASH_REF__//;
2268: $result=~s/__END_HASH_REF__$//;
1.204 albertel 2269: return $result;
2270: }
2271:
2272: sub hashref2str {
2273: my ($hashref)=@_;
1.265 albertel 2274: my $result='__HASH_REF__';
1.800 albertel 2275: foreach my $key (sort(keys(%$hashref))) {
2276: if (ref($key) eq 'ARRAY') {
2277: $result.=&arrayref2str($key).'=';
2278: } elsif (ref($key) eq 'HASH') {
2279: $result.=&hashref2str($key).'=';
2280: } elsif (ref($key)) {
1.265 albertel 2281: $result.='=';
1.800 albertel 2282: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 2283: } else {
1.800 albertel 2284: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 2285: }
2286:
1.800 albertel 2287: if(ref($hashref->{$key}) eq 'ARRAY') {
2288: $result.=&arrayref2str($hashref->{$key}).'&';
2289: } elsif(ref($hashref->{$key}) eq 'HASH') {
2290: $result.=&hashref2str($hashref->{$key}).'&';
2291: } elsif(ref($hashref->{$key})) {
1.265 albertel 2292: $result.='&';
1.800 albertel 2293: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 2294: } else {
1.800 albertel 2295: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 2296: }
2297: }
1.168 albertel 2298: $result=~s/\&$//;
1.265 albertel 2299: $result .= '__END_HASH_REF__';
1.168 albertel 2300: return $result;
2301: }
2302:
2303: sub str2hash {
1.265 albertel 2304: my ($string)=@_;
2305: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
2306: return %$hash;
2307: }
2308:
2309: sub str2hashref {
1.168 albertel 2310: my ($string) = @_;
1.265 albertel 2311:
2312: my %hash;
2313:
2314: if($string !~ /^__HASH_REF__/) {
2315: if (! ($string eq '' || !defined($string))) {
2316: $hash{'error'}='Not hash reference';
2317: }
2318: return (\%hash, $string);
2319: }
2320:
2321: $string =~ s/^__HASH_REF__//;
2322:
2323: while($string !~ /^__END_HASH_REF__/) {
2324: #key
2325: my $key='';
2326: if($string =~ /^__HASH_REF__/) {
2327: ($key, $string)=&str2hashref($string);
2328: if(defined($key->{'error'})) {
2329: $hash{'error'}='Bad data';
2330: return (\%hash, $string);
2331: }
2332: } elsif($string =~ /^__ARRAY_REF__/) {
2333: ($key, $string)=&str2arrayref($string);
2334: if($key->[0] eq 'Array reference error') {
2335: $hash{'error'}='Bad data';
2336: return (\%hash, $string);
2337: }
2338: } else {
2339: $string =~ s/^(.*?)=//;
1.267 albertel 2340: $key=&unescape($1);
1.265 albertel 2341: }
2342: $string =~ s/^=//;
2343:
2344: #value
2345: my $value='';
2346: if($string =~ /^__HASH_REF__/) {
2347: ($value, $string)=&str2hashref($string);
2348: if(defined($value->{'error'})) {
2349: $hash{'error'}='Bad data';
2350: return (\%hash, $string);
2351: }
2352: } elsif($string =~ /^__ARRAY_REF__/) {
2353: ($value, $string)=&str2arrayref($string);
2354: if($value->[0] eq 'Array reference error') {
2355: $hash{'error'}='Bad data';
2356: return (\%hash, $string);
2357: }
2358: } else {
2359: $value=&get_scalar(\$string,'__END_HASH_REF__');
2360: }
2361: $string =~ s/^&//;
2362:
2363: $hash{$key}=$value;
1.204 albertel 2364: }
1.265 albertel 2365:
2366: $string =~ s/^__END_HASH_REF__//;
2367:
2368: return (\%hash, $string);
1.204 albertel 2369: }
2370:
2371: sub str2array {
1.265 albertel 2372: my ($string)=@_;
2373: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
2374: return @$array;
2375: }
2376:
2377: sub str2arrayref {
1.204 albertel 2378: my ($string) = @_;
1.265 albertel 2379: my @array;
2380:
2381: if($string !~ /^__ARRAY_REF__/) {
2382: if (! ($string eq '' || !defined($string))) {
2383: $array[0]='Array reference error';
2384: }
2385: return (\@array, $string);
2386: }
2387:
2388: $string =~ s/^__ARRAY_REF__//;
2389:
2390: while($string !~ /^__END_ARRAY_REF__/) {
2391: my $value='';
2392: if($string =~ /^__HASH_REF__/) {
2393: ($value, $string)=&str2hashref($string);
2394: if(defined($value->{'error'})) {
2395: $array[0] ='Array reference error';
2396: return (\@array, $string);
2397: }
2398: } elsif($string =~ /^__ARRAY_REF__/) {
2399: ($value, $string)=&str2arrayref($string);
2400: if($value->[0] eq 'Array reference error') {
2401: $array[0] ='Array reference error';
2402: return (\@array, $string);
2403: }
2404: } else {
2405: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
2406: }
2407: $string =~ s/^&//;
2408:
2409: push(@array, $value);
1.191 harris41 2410: }
1.265 albertel 2411:
2412: $string =~ s/^__END_ARRAY_REF__//;
2413:
2414: return (\@array, $string);
1.168 albertel 2415: }
2416:
1.167 albertel 2417: # -------------------------------------------------------------------Temp Store
2418:
1.168 albertel 2419: sub tmpreset {
2420: my ($symb,$namespace,$domain,$stuname) = @_;
2421: if (!$symb) {
2422: $symb=&symbread();
1.620 albertel 2423: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2424: }
2425: $symb=escape($symb);
2426:
1.620 albertel 2427: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 2428: $namespace=~s/\//\_/g;
2429: $namespace=~s/\W//g;
2430:
1.620 albertel 2431: if (!$domain) { $domain=$env{'user.domain'}; }
2432: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2433: if ($domain eq 'public' && $stuname eq 'public') {
2434: $stuname=$ENV{'REMOTE_ADDR'};
2435: }
1.168 albertel 2436: my $path=$perlvar{'lonDaemons'}.'/tmp';
2437: my %hash;
2438: if (tie(%hash,'GDBM_File',
2439: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2440: &GDBM_WRCREAT(),0640)) {
1.168 albertel 2441: foreach my $key (keys %hash) {
1.180 albertel 2442: if ($key=~ /:$symb/) {
1.168 albertel 2443: delete($hash{$key});
2444: }
2445: }
2446: }
2447: }
2448:
1.167 albertel 2449: sub tmpstore {
1.168 albertel 2450: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2451:
2452: if (!$symb) {
2453: $symb=&symbread();
1.620 albertel 2454: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2455: }
2456: $symb=escape($symb);
2457:
2458: if (!$namespace) {
2459: # I don't think we would ever want to store this for a course.
2460: # it seems this will only be used if we don't have a course.
1.620 albertel 2461: #$namespace=$env{'request.course.id'};
1.168 albertel 2462: #if (!$namespace) {
1.620 albertel 2463: $namespace=$env{'request.state'};
1.168 albertel 2464: #}
2465: }
2466: $namespace=~s/\//\_/g;
2467: $namespace=~s/\W//g;
1.620 albertel 2468: if (!$domain) { $domain=$env{'user.domain'}; }
2469: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2470: if ($domain eq 'public' && $stuname eq 'public') {
2471: $stuname=$ENV{'REMOTE_ADDR'};
2472: }
1.168 albertel 2473: my $now=time;
2474: my %hash;
2475: my $path=$perlvar{'lonDaemons'}.'/tmp';
2476: if (tie(%hash,'GDBM_File',
2477: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2478: &GDBM_WRCREAT(),0640)) {
1.168 albertel 2479: $hash{"version:$symb"}++;
2480: my $version=$hash{"version:$symb"};
2481: my $allkeys='';
2482: foreach my $key (keys(%$storehash)) {
2483: $allkeys.=$key.':';
1.591 albertel 2484: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 2485: }
2486: $hash{"$version:$symb:timestamp"}=$now;
2487: $allkeys.='timestamp';
2488: $hash{"$version:keys:$symb"}=$allkeys;
2489: if (untie(%hash)) {
2490: return 'ok';
2491: } else {
2492: return "error:$!";
2493: }
2494: } else {
2495: return "error:$!";
2496: }
2497: }
1.167 albertel 2498:
1.168 albertel 2499: # -----------------------------------------------------------------Temp Restore
1.167 albertel 2500:
1.168 albertel 2501: sub tmprestore {
2502: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 2503:
1.168 albertel 2504: if (!$symb) {
2505: $symb=&symbread();
1.620 albertel 2506: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2507: }
2508: $symb=escape($symb);
2509:
1.620 albertel 2510: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 2511:
1.620 albertel 2512: if (!$domain) { $domain=$env{'user.domain'}; }
2513: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2514: if ($domain eq 'public' && $stuname eq 'public') {
2515: $stuname=$ENV{'REMOTE_ADDR'};
2516: }
1.168 albertel 2517: my %returnhash;
2518: $namespace=~s/\//\_/g;
2519: $namespace=~s/\W//g;
2520: my %hash;
2521: my $path=$perlvar{'lonDaemons'}.'/tmp';
2522: if (tie(%hash,'GDBM_File',
2523: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2524: &GDBM_READER(),0640)) {
1.168 albertel 2525: my $version=$hash{"version:$symb"};
2526: $returnhash{'version'}=$version;
2527: my $scope;
2528: for ($scope=1;$scope<=$version;$scope++) {
2529: my $vkeys=$hash{"$scope:keys:$symb"};
2530: my @keys=split(/:/,$vkeys);
2531: my $key;
2532: $returnhash{"$scope:keys"}=$vkeys;
2533: foreach $key (@keys) {
1.591 albertel 2534: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
2535: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 2536: }
2537: }
1.168 albertel 2538: if (!(untie(%hash))) {
2539: return "error:$!";
2540: }
2541: } else {
2542: return "error:$!";
2543: }
2544: return %returnhash;
1.167 albertel 2545: }
2546:
1.9 www 2547: # ----------------------------------------------------------------------- Store
2548:
2549: sub store {
1.124 www 2550: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2551: my $home='';
2552:
1.168 albertel 2553: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2554:
1.213 www 2555: $symb=&symbclean($symb);
1.122 albertel 2556: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 2557:
1.620 albertel 2558: if (!$domain) { $domain=$env{'user.domain'}; }
2559: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 2560:
2561: &devalidate($symb,$stuname,$domain);
1.109 www 2562:
2563: $symb=escape($symb);
1.187 www 2564: if (!$namespace) {
1.620 albertel 2565: unless ($namespace=$env{'request.course.id'}) {
1.187 www 2566: return '';
2567: }
2568: }
1.620 albertel 2569: if (!$home) { $home=$env{'user.home'}; }
1.447 www 2570:
2571: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2572: $$storehash{'host'}=$perlvar{'lonHostID'};
2573:
1.12 www 2574: my $namevalue='';
1.800 albertel 2575: foreach my $key (keys(%$storehash)) {
2576: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 2577: }
1.12 www 2578: $namevalue=~s/\&$//;
1.187 www 2579: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 2580: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 2581: }
2582:
1.47 www 2583: # -------------------------------------------------------------- Critical Store
2584:
2585: sub cstore {
1.124 www 2586: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2587: my $home='';
2588:
1.168 albertel 2589: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2590:
1.213 www 2591: $symb=&symbclean($symb);
1.122 albertel 2592: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 2593:
1.620 albertel 2594: if (!$domain) { $domain=$env{'user.domain'}; }
2595: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 2596:
2597: &devalidate($symb,$stuname,$domain);
1.109 www 2598:
2599: $symb=escape($symb);
1.187 www 2600: if (!$namespace) {
1.620 albertel 2601: unless ($namespace=$env{'request.course.id'}) {
1.187 www 2602: return '';
2603: }
2604: }
1.620 albertel 2605: if (!$home) { $home=$env{'user.home'}; }
1.447 www 2606:
2607: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2608: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 2609:
1.47 www 2610: my $namevalue='';
1.800 albertel 2611: foreach my $key (keys(%$storehash)) {
2612: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 2613: }
1.47 www 2614: $namevalue=~s/\&$//;
1.187 www 2615: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 2616: return critical
2617: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 2618: }
2619:
1.9 www 2620: # --------------------------------------------------------------------- Restore
2621:
2622: sub restore {
1.124 www 2623: my ($symb,$namespace,$domain,$stuname) = @_;
2624: my $home='';
2625:
1.168 albertel 2626: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2627:
1.122 albertel 2628: if (!$symb) {
2629: unless ($symb=escape(&symbread())) { return ''; }
2630: } else {
1.213 www 2631: $symb=&escape(&symbclean($symb));
1.122 albertel 2632: }
1.188 www 2633: if (!$namespace) {
1.620 albertel 2634: unless ($namespace=$env{'request.course.id'}) {
1.188 www 2635: return '';
2636: }
2637: }
1.620 albertel 2638: if (!$domain) { $domain=$env{'user.domain'}; }
2639: if (!$stuname) { $stuname=$env{'user.name'}; }
2640: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 2641: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
2642:
1.12 www 2643: my %returnhash=();
1.800 albertel 2644: foreach my $line (split(/\&/,$answer)) {
2645: my ($name,$value)=split(/\=/,$line);
1.591 albertel 2646: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 2647: }
1.75 www 2648: my $version;
2649: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 2650: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
2651: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 2652: }
1.75 www 2653: }
1.13 www 2654: return %returnhash;
1.34 www 2655: }
2656:
2657: # ---------------------------------------------------------- Course Description
2658:
2659: sub coursedescription {
1.731 albertel 2660: my ($courseid,$args)=@_;
1.34 www 2661: $courseid=~s/^\///;
1.49 www 2662: $courseid=~s/\_/\//g;
1.34 www 2663: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 2664: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 2665: my $normalid=$cdomain.'_'.$cnum;
2666: # need to always cache even if we get errors otherwise we keep
2667: # trying and trying and trying to get the course description.
2668: my %envhash=();
2669: my %returnhash=();
1.731 albertel 2670:
2671: my $expiretime=600;
2672: if ($env{'request.course.id'} eq $normalid) {
2673: $expiretime=120;
2674: }
2675:
2676: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
2677: if (!$args->{'freshen_cache'}
2678: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
2679: foreach my $key (keys(%env)) {
2680: next if ($key !~ /^\Q$prefix\E(.*)/);
2681: my ($setting) = $1;
2682: $returnhash{$setting} = $env{$key};
2683: }
2684: return %returnhash;
2685: }
2686:
2687: # get the data agin
2688: if (!$args->{'one_time'}) {
2689: $envhash{'course.'.$normalid.'.last_cache'}=time;
2690: }
1.34 www 2691: if ($chome ne 'no_host') {
1.302 albertel 2692: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 2693: if (!exists($returnhash{'con_lost'})) {
2694: $returnhash{'home'}= $chome;
2695: $returnhash{'domain'} = $cdomain;
2696: $returnhash{'num'} = $cnum;
1.741 raeburn 2697: if (!defined($returnhash{'type'})) {
2698: $returnhash{'type'} = 'Course';
2699: }
1.130 albertel 2700: while (my ($name,$value) = each %returnhash) {
1.53 www 2701: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 2702: }
1.270 www 2703: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 2704: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 2705: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 2706: $envhash{'course.'.$normalid.'.home'}=$chome;
2707: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
2708: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 2709: }
2710: }
1.731 albertel 2711: if (!$args->{'one_time'}) {
2712: &appenv(%envhash);
2713: }
1.302 albertel 2714: return %returnhash;
1.461 www 2715: }
2716:
2717: # -------------------------------------------------See if a user is privileged
2718:
2719: sub privileged {
2720: my ($username,$domain)=@_;
2721: my $rolesdump=&reply("dump:$domain:$username:roles",
2722: &homeserver($username,$domain));
2723: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
2724: my $now=time;
2725: if ($rolesdump ne '') {
1.800 albertel 2726: foreach my $entry (split(/&/,$rolesdump)) {
2727: if ($entry!~/^rolesdef_/) {
2728: my ($area,$role)=split(/=/,$entry);
1.461 www 2729: $area=~s/\_\w\w$//;
2730: my ($trole,$tend,$tstart)=split(/_/,$role);
2731: if (($trole eq 'dc') || ($trole eq 'su')) {
2732: my $active=1;
2733: if ($tend) {
2734: if ($tend<$now) { $active=0; }
2735: }
2736: if ($tstart) {
2737: if ($tstart>$now) { $active=0; }
2738: }
2739: if ($active) { return 1; }
2740: }
2741: }
2742: }
2743: }
2744: return 0;
1.9 www 2745: }
1.1 albertel 2746:
1.103 harris41 2747: # -------------------------------------------------------- Get user privileges
1.11 www 2748:
2749: sub rolesinit {
2750: my ($domain,$username,$authhost)=@_;
2751: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12 www 2752: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11 www 2753: my %allroles=();
1.678 raeburn 2754: my %allgroups=();
1.11 www 2755: my $now=time;
1.743 albertel 2756: my %userroles = ('user.login.time' => $now);
1.678 raeburn 2757: my $group_privs;
1.11 www 2758:
2759: if ($rolesdump ne '') {
1.800 albertel 2760: foreach my $entry (split(/&/,$rolesdump)) {
2761: if ($entry!~/^rolesdef_/) {
2762: my ($area,$role)=split(/=/,$entry);
1.587 albertel 2763: $area=~s/\_\w\w$//;
1.678 raeburn 2764: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 2765: if ($role=~/^cr/) {
1.655 albertel 2766: if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
2767: ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
2768: ($tend,$tstart)=split('_',$trest);
2769: } else {
2770: $trole=$role;
2771: }
1.678 raeburn 2772: } elsif ($role =~ m|^gr/|) {
2773: ($trole,$tend,$tstart) = split(/_/,$role);
2774: ($trole,$group_privs) = split(/\//,$trole);
2775: $group_privs = &unescape($group_privs);
1.587 albertel 2776: } else {
2777: ($trole,$tend,$tstart)=split(/_/,$role);
2778: }
1.743 albertel 2779: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
2780: $username);
2781: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 2782: if (($tend!=0) && ($tend<$now)) { $trole=''; }
2783: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 2784: if (($area ne '') && ($trole ne '')) {
1.347 albertel 2785: my $spec=$trole.'.'.$area;
2786: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
2787: if ($trole =~ /^cr\//) {
1.567 raeburn 2788: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 2789: } elsif ($trole eq 'gr') {
2790: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 2791: } else {
1.567 raeburn 2792: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 2793: }
1.12 www 2794: }
1.662 raeburn 2795: }
1.191 harris41 2796: }
1.743 albertel 2797: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
2798: $userroles{'user.adv'} = $adv;
2799: $userroles{'user.author'} = $author;
1.620 albertel 2800: $env{'user.adv'}=$adv;
1.11 www 2801: }
1.743 albertel 2802: return \%userroles;
1.11 www 2803: }
2804:
1.567 raeburn 2805: sub set_arearole {
2806: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
2807: # log the associated role with the area
2808: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 2809: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 2810: }
2811:
2812: sub custom_roleprivs {
2813: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
2814: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
2815: my $homsvr=homeserver($rauthor,$rdomain);
2816: if ($hostname{$homsvr} ne '') {
2817: my ($rdummy,$roledef)=
2818: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
2819: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
2820: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
2821: if (defined($syspriv)) {
2822: $$allroles{'cm./'}.=':'.$syspriv;
2823: $$allroles{$spec.'./'}.=':'.$syspriv;
2824: }
2825: if ($tdomain ne '') {
2826: if (defined($dompriv)) {
2827: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
2828: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
2829: }
2830: if (($trest ne '') && (defined($coursepriv))) {
2831: $$allroles{'cm.'.$area}.=':'.$coursepriv;
2832: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
2833: }
2834: }
2835: }
2836: }
2837: }
2838:
1.678 raeburn 2839: sub group_roleprivs {
2840: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
2841: my $access = 1;
2842: my $now = time;
2843: if (($tend!=0) && ($tend<$now)) { $access = 0; }
2844: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
2845: if ($access) {
2846: my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
2847: $$allgroups{$course}{$group} .=':'.$group_privs;
2848: }
2849: }
1.567 raeburn 2850:
2851: sub standard_roleprivs {
2852: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
2853: if (defined($pr{$trole.':s'})) {
2854: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
2855: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
2856: }
2857: if ($tdomain ne '') {
2858: if (defined($pr{$trole.':d'})) {
2859: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
2860: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
2861: }
2862: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
2863: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
2864: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
2865: }
2866: }
2867: }
2868:
2869: sub set_userprivs {
1.678 raeburn 2870: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 2871: my $author=0;
2872: my $adv=0;
1.678 raeburn 2873: my %grouproles = ();
2874: if (keys(%{$allgroups}) > 0) {
2875: foreach my $role (keys %{$allroles}) {
1.681 raeburn 2876: my ($trole,$area,$sec,$extendedarea);
1.771 raeburn 2877: if ($role =~ m-^(\w+|cr/\w+/\w+/\w+)\.(/\w+/\w+)(/?\w*)-) {
1.678 raeburn 2878: $trole = $1;
2879: $area = $2;
1.681 raeburn 2880: $sec = $3;
2881: $extendedarea = $area.$sec;
2882: if (exists($$allgroups{$area})) {
2883: foreach my $group (keys(%{$$allgroups{$area}})) {
2884: my $spec = $trole.'.'.$extendedarea;
2885: $grouproles{$spec.'.'.$area.'/'.$group} =
2886: $$allgroups{$area}{$group};
1.678 raeburn 2887: }
2888: }
2889: }
2890: }
2891: }
1.800 albertel 2892: foreach my $group (keys(%grouproles)) {
2893: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 2894: }
1.800 albertel 2895: foreach my $role (keys(%{$allroles})) {
2896: my %thesepriv;
2897: if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
2898: foreach my $item (split(/:/,$$allroles{$role})) {
2899: if ($item ne '') {
2900: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 2901: if ($restrictions eq '') {
2902: $thesepriv{$privilege}='F';
2903: } elsif ($thesepriv{$privilege} ne 'F') {
2904: $thesepriv{$privilege}.=$restrictions;
2905: }
2906: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
2907: }
2908: }
2909: my $thesestr='';
1.800 albertel 2910: foreach my $priv (keys(%thesepriv)) {
2911: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
2912: }
2913: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 2914: }
2915: return ($author,$adv);
2916: }
2917:
1.12 www 2918: # --------------------------------------------------------------- get interface
2919:
2920: sub get {
1.131 albertel 2921: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 2922: my $items='';
1.800 albertel 2923: foreach my $item (@$storearr) {
2924: $items.=&escape($item).'&';
1.191 harris41 2925: }
1.12 www 2926: $items=~s/\&$//;
1.620 albertel 2927: if (!$udomain) { $udomain=$env{'user.domain'}; }
2928: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 2929: my $uhome=&homeserver($uname,$udomain);
2930:
1.133 albertel 2931: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 2932: my @pairs=split(/\&/,$rep);
1.273 albertel 2933: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2934: return @pairs;
2935: }
1.15 www 2936: my %returnhash=();
1.42 www 2937: my $i=0;
1.800 albertel 2938: foreach my $item (@$storearr) {
2939: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 2940: $i++;
1.191 harris41 2941: }
1.15 www 2942: return %returnhash;
1.27 www 2943: }
2944:
2945: # --------------------------------------------------------------- del interface
2946:
2947: sub del {
1.133 albertel 2948: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 2949: my $items='';
1.800 albertel 2950: foreach my $item (@$storearr) {
2951: $items.=&escape($item).'&';
1.191 harris41 2952: }
1.27 www 2953: $items=~s/\&$//;
1.620 albertel 2954: if (!$udomain) { $udomain=$env{'user.domain'}; }
2955: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 2956: my $uhome=&homeserver($uname,$udomain);
2957:
2958: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 2959: }
2960:
2961: # -------------------------------------------------------------- dump interface
2962:
2963: sub dump {
1.755 albertel 2964: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
2965: if (!$udomain) { $udomain=$env{'user.domain'}; }
2966: if (!$uname) { $uname=$env{'user.name'}; }
2967: my $uhome=&homeserver($uname,$udomain);
2968: if ($regexp) {
2969: $regexp=&escape($regexp);
2970: } else {
2971: $regexp='.';
2972: }
2973: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
2974: my @pairs=split(/\&/,$rep);
2975: my %returnhash=();
2976: foreach my $item (@pairs) {
2977: my ($key,$value)=split(/=/,$item,2);
2978: $key = &unescape($key);
2979: next if ($key =~ /^error: 2 /);
2980: $returnhash{$key}=&thaw_unescape($value);
2981: }
2982: return %returnhash;
1.407 www 2983: }
2984:
1.717 albertel 2985: # --------------------------------------------------------- dumpstore interface
2986:
2987: sub dumpstore {
2988: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
2989: return &dump($namespace,$udomain,$uname,$regexp,$range);
2990: }
2991:
1.407 www 2992: # -------------------------------------------------------------- keys interface
2993:
2994: sub getkeys {
2995: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 2996: if (!$udomain) { $udomain=$env{'user.domain'}; }
2997: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 2998: my $uhome=&homeserver($uname,$udomain);
2999: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3000: my @keyarray=();
1.800 albertel 3001: foreach my $key (split(/\&/,$rep)) {
3002: push(@keyarray,&unescape($key));
1.407 www 3003: }
3004: return @keyarray;
1.318 matthew 3005: }
3006:
1.319 matthew 3007: # --------------------------------------------------------------- currentdump
3008: sub currentdump {
1.328 matthew 3009: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 3010: $courseid = $env{'request.course.id'} if (! defined($courseid));
3011: $sdom = $env{'user.domain'} if (! defined($sdom));
3012: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 3013: my $uhome = &homeserver($sname,$sdom);
3014: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 3015: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 3016: #
1.318 matthew 3017: my %returnhash=();
1.319 matthew 3018: #
3019: if ($rep eq "unknown_cmd") {
3020: # an old lond will not know currentdump
3021: # Do a dump and make it look like a currentdump
1.326 matthew 3022: my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319 matthew 3023: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3024: my %hash = @tmp;
3025: @tmp=();
1.424 matthew 3026: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 3027: } else {
3028: my @pairs=split(/\&/,$rep);
1.800 albertel 3029: foreach my $pair (@pairs) {
3030: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 3031: my ($symb,$param) = split(/:/,$key);
3032: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 3033: &thaw_unescape($value);
1.319 matthew 3034: }
1.191 harris41 3035: }
1.12 www 3036: return %returnhash;
1.424 matthew 3037: }
3038:
3039: sub convert_dump_to_currentdump{
3040: my %hash = %{shift()};
3041: my %returnhash;
3042: # Code ripped from lond, essentially. The only difference
3043: # here is the unescaping done by lonnet::dump(). Conceivably
3044: # we might run in to problems with parameter names =~ /^v\./
3045: while (my ($key,$value) = each(%hash)) {
3046: my ($v,$symb,$param) = split(/:/,$key);
3047: next if ($v eq 'version' || $symb eq 'keys');
3048: next if (exists($returnhash{$symb}) &&
3049: exists($returnhash{$symb}->{$param}) &&
3050: $returnhash{$symb}->{'v.'.$param} > $v);
3051: $returnhash{$symb}->{$param}=$value;
3052: $returnhash{$symb}->{'v.'.$param}=$v;
3053: }
3054: #
3055: # Remove all of the keys in the hashes which keep track of
3056: # the version of the parameter.
3057: while (my ($symb,$param_hash) = each(%returnhash)) {
3058: # use a foreach because we are going to delete from the hash.
3059: foreach my $key (keys(%$param_hash)) {
3060: delete($param_hash->{$key}) if ($key =~ /^v\./);
3061: }
3062: }
3063: return \%returnhash;
1.12 www 3064: }
3065:
1.627 albertel 3066: # ------------------------------------------------------ critical inc interface
3067:
3068: sub cinc {
3069: return &inc(@_,'critical');
3070: }
3071:
1.449 matthew 3072: # --------------------------------------------------------------- inc interface
3073:
3074: sub inc {
1.627 albertel 3075: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 3076: if (!$udomain) { $udomain=$env{'user.domain'}; }
3077: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 3078: my $uhome=&homeserver($uname,$udomain);
3079: my $items='';
3080: if (! ref($store)) {
3081: # got a single value, so use that instead
3082: $items = &escape($store).'=&';
3083: } elsif (ref($store) eq 'SCALAR') {
3084: $items = &escape($$store).'=&';
3085: } elsif (ref($store) eq 'ARRAY') {
3086: $items = join('=&',map {&escape($_);} @{$store});
3087: } elsif (ref($store) eq 'HASH') {
3088: while (my($key,$value) = each(%{$store})) {
3089: $items.= &escape($key).'='.&escape($value).'&';
3090: }
3091: }
3092: $items=~s/\&$//;
1.627 albertel 3093: if ($critical) {
3094: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
3095: } else {
3096: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
3097: }
1.449 matthew 3098: }
3099:
1.12 www 3100: # --------------------------------------------------------------- put interface
3101:
3102: sub put {
1.134 albertel 3103: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3104: if (!$udomain) { $udomain=$env{'user.domain'}; }
3105: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3106: my $uhome=&homeserver($uname,$udomain);
1.12 www 3107: my $items='';
1.800 albertel 3108: foreach my $item (keys(%$storehash)) {
3109: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3110: }
1.12 www 3111: $items=~s/\&$//;
1.134 albertel 3112: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 3113: }
3114:
1.631 albertel 3115: # ------------------------------------------------------------ newput interface
3116:
3117: sub newput {
3118: my ($namespace,$storehash,$udomain,$uname)=@_;
3119: if (!$udomain) { $udomain=$env{'user.domain'}; }
3120: if (!$uname) { $uname=$env{'user.name'}; }
3121: my $uhome=&homeserver($uname,$udomain);
3122: my $items='';
3123: foreach my $key (keys(%$storehash)) {
3124: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3125: }
3126: $items=~s/\&$//;
3127: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
3128: }
3129:
3130: # --------------------------------------------------------- putstore interface
3131:
1.524 raeburn 3132: sub putstore {
1.715 albertel 3133: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 3134: if (!$udomain) { $udomain=$env{'user.domain'}; }
3135: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 3136: my $uhome=&homeserver($uname,$udomain);
3137: my $items='';
1.715 albertel 3138: foreach my $key (keys(%$storehash)) {
3139: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 3140: }
1.715 albertel 3141: $items=~s/\&$//;
1.716 albertel 3142: my $esc_symb=&escape($symb);
3143: my $esc_v=&escape($version);
1.715 albertel 3144: my $reply =
1.716 albertel 3145: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 3146: $uhome);
3147: if ($reply eq 'unknown_cmd') {
1.716 albertel 3148: # gfall back to way things use to be done
1.715 albertel 3149: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
3150: $uname);
1.524 raeburn 3151: }
1.715 albertel 3152: return $reply;
3153: }
3154:
3155: sub old_putstore {
1.716 albertel 3156: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3157: if (!$udomain) { $udomain=$env{'user.domain'}; }
3158: if (!$uname) { $uname=$env{'user.name'}; }
3159: my $uhome=&homeserver($uname,$udomain);
3160: my %newstorehash;
1.800 albertel 3161: foreach my $item (keys(%$storehash)) {
3162: my $key = $version.':'.&escape($symb).':'.$item;
3163: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 3164: }
3165: my $items='';
3166: my %allitems = ();
1.800 albertel 3167: foreach my $item (keys(%newstorehash)) {
3168: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 3169: my $key = $1.':keys:'.$2;
3170: $allitems{$key} .= $3.':';
3171: }
1.800 albertel 3172: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 3173: }
1.800 albertel 3174: foreach my $item (keys(%allitems)) {
3175: $allitems{$item} =~ s/\:$//;
3176: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 3177: }
3178: $items=~s/\&$//;
3179: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 3180: }
3181:
1.47 www 3182: # ------------------------------------------------------ critical put interface
3183:
3184: sub cput {
1.134 albertel 3185: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3186: if (!$udomain) { $udomain=$env{'user.domain'}; }
3187: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3188: my $uhome=&homeserver($uname,$udomain);
1.47 www 3189: my $items='';
1.800 albertel 3190: foreach my $item (keys(%$storehash)) {
3191: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3192: }
1.47 www 3193: $items=~s/\&$//;
1.134 albertel 3194: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3195: }
3196:
3197: # -------------------------------------------------------------- eget interface
3198:
3199: sub eget {
1.133 albertel 3200: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3201: my $items='';
1.800 albertel 3202: foreach my $item (@$storearr) {
3203: $items.=&escape($item).'&';
1.191 harris41 3204: }
1.12 www 3205: $items=~s/\&$//;
1.620 albertel 3206: if (!$udomain) { $udomain=$env{'user.domain'}; }
3207: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3208: my $uhome=&homeserver($uname,$udomain);
3209: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3210: my @pairs=split(/\&/,$rep);
3211: my %returnhash=();
1.42 www 3212: my $i=0;
1.800 albertel 3213: foreach my $item (@$storearr) {
3214: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3215: $i++;
1.191 harris41 3216: }
1.12 www 3217: return %returnhash;
3218: }
3219:
1.667 albertel 3220: # ------------------------------------------------------------ tmpput interface
3221: sub tmpput {
1.802 raeburn 3222: my ($storehash,$server,$context)=@_;
1.667 albertel 3223: my $items='';
1.800 albertel 3224: foreach my $item (keys(%$storehash)) {
3225: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 3226: }
3227: $items=~s/\&$//;
1.802 raeburn 3228: if (defined($context)) {
3229: $items .= ':'.&escape($context);
3230: }
1.667 albertel 3231: return &reply("tmpput:$items",$server);
3232: }
3233:
3234: # ------------------------------------------------------------ tmpget interface
3235: sub tmpget {
1.688 albertel 3236: my ($token,$server)=@_;
3237: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3238: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 3239: my %returnhash;
3240: foreach my $item (split(/\&/,$rep)) {
3241: my ($key,$value)=split(/=/,$item);
3242: $returnhash{&unescape($key)}=&thaw_unescape($value);
3243: }
3244: return %returnhash;
3245: }
3246:
1.688 albertel 3247: # ------------------------------------------------------------ tmpget interface
3248: sub tmpdel {
3249: my ($token,$server)=@_;
3250: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3251: return &reply("tmpdel:$token",$server);
3252: }
3253:
1.765 albertel 3254: # -------------------------------------------------- portfolio access checking
3255:
3256: sub portfolio_access {
1.766 albertel 3257: my ($requrl) = @_;
1.765 albertel 3258: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
3259: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
3260: if ($result eq 'ok') {
1.766 albertel 3261: return 'F';
1.765 albertel 3262: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 3263: return 'A';
1.765 albertel 3264: }
1.766 albertel 3265: return '';
1.765 albertel 3266: }
3267:
3268: sub get_portfolio_access {
1.767 albertel 3269: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
3270:
3271: if (!ref($access_hash)) {
3272: my $current_perms = &get_portfile_permissions($udom,$unum);
3273: my %access_controls = &get_access_controls($current_perms,$group,
3274: $file_name);
3275: $access_hash = $access_controls{$file_name};
3276: }
3277:
1.765 albertel 3278: my ($public,$guest,@domains,@users,@courses,@groups);
3279: my $now = time;
3280: if (ref($access_hash) eq 'HASH') {
3281: foreach my $key (keys(%{$access_hash})) {
3282: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
3283: if ($start > $now) {
3284: next;
3285: }
3286: if ($end && $end<$now) {
3287: next;
3288: }
3289: if ($scope eq 'public') {
3290: $public = $key;
3291: last;
3292: } elsif ($scope eq 'guest') {
3293: $guest = $key;
3294: } elsif ($scope eq 'domains') {
3295: push(@domains,$key);
3296: } elsif ($scope eq 'users') {
3297: push(@users,$key);
3298: } elsif ($scope eq 'course') {
3299: push(@courses,$key);
3300: } elsif ($scope eq 'group') {
3301: push(@groups,$key);
3302: }
3303: }
3304: if ($public) {
3305: return 'ok';
3306: }
3307: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3308: if ($guest) {
3309: return $guest;
3310: }
3311: } else {
3312: if (@domains > 0) {
3313: foreach my $domkey (@domains) {
3314: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
3315: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
3316: return 'ok';
3317: }
3318: }
3319: }
3320: }
3321: if (@users > 0) {
3322: foreach my $userkey (@users) {
3323: if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
3324: return 'ok';
3325: }
3326: }
3327: }
3328: my %roleshash;
3329: my @courses_and_groups = @courses;
3330: push(@courses_and_groups,@groups);
3331: if (@courses_and_groups > 0) {
3332: my (%allgroups,%allroles);
3333: my ($start,$end,$role,$sec,$group);
3334: foreach my $envkey (%env) {
3335: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
3336: my $cid = $2.'_'.$3;
3337: if ($1 eq 'gr') {
3338: $group = $4;
3339: $allgroups{$cid}{$group} = $env{$envkey};
3340: } else {
3341: if ($4 eq '') {
3342: $sec = 'none';
3343: } else {
3344: $sec = $4;
3345: }
3346: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3347: }
3348: } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
3349: my $cid = $2.'_'.$3;
3350: if ($4 eq '') {
3351: $sec = 'none';
3352: } else {
3353: $sec = $4;
3354: }
3355: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3356: }
3357: }
3358: if (keys(%allroles) == 0) {
3359: return;
3360: }
3361: foreach my $key (@courses_and_groups) {
3362: my %content = %{$$access_hash{$key}};
3363: my $cnum = $content{'number'};
3364: my $cdom = $content{'domain'};
3365: my $cid = $cdom.'_'.$cnum;
3366: if (!exists($allroles{$cid})) {
3367: next;
3368: }
3369: foreach my $role_id (keys(%{$content{'roles'}})) {
3370: my @sections = @{$content{'roles'}{$role_id}{'section'}};
3371: my @groups = @{$content{'roles'}{$role_id}{'group'}};
3372: my @status = @{$content{'roles'}{$role_id}{'access'}};
3373: my @roles = @{$content{'roles'}{$role_id}{'role'}};
3374: foreach my $role (keys(%{$allroles{$cid}})) {
3375: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
3376: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
3377: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
3378: if (grep/^all$/,@sections) {
3379: return 'ok';
3380: } else {
3381: if (grep/^$sec$/,@sections) {
3382: return 'ok';
3383: }
3384: }
3385: }
3386: }
3387: if (keys(%{$allgroups{$cid}}) == 0) {
3388: if (grep/^none$/,@groups) {
3389: return 'ok';
3390: }
3391: } else {
3392: if (grep/^all$/,@groups) {
3393: return 'ok';
3394: }
3395: foreach my $group (keys(%{$allgroups{$cid}})) {
3396: if (grep/^$group$/,@groups) {
3397: return 'ok';
3398: }
3399: }
3400: }
3401: }
3402: }
3403: }
3404: }
3405: }
3406: if ($guest) {
3407: return $guest;
3408: }
3409: }
3410: }
3411: return;
3412: }
3413:
3414: sub course_group_datechecker {
3415: my ($dates,$now,$status) = @_;
3416: my ($start,$end) = split(/\./,$dates);
3417: if (!$start && !$end) {
3418: return 'ok';
3419: }
3420: if (grep/^active$/,@{$status}) {
3421: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
3422: return 'ok';
3423: }
3424: }
3425: if (grep/^previous$/,@{$status}) {
3426: if ($end > $now ) {
3427: return 'ok';
3428: }
3429: }
3430: if (grep/^future$/,@{$status}) {
3431: if ($start > $now) {
3432: return 'ok';
3433: }
3434: }
3435: return;
3436: }
3437:
3438: sub parse_portfolio_url {
3439: my ($url) = @_;
3440:
3441: my ($type,$udom,$unum,$group,$file_name);
3442:
3443: if ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
3444: $type = 1;
3445: $udom = $1;
3446: $unum = $2;
3447: $file_name = $3;
3448: } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
3449: $type = 2;
3450: $udom = $1;
3451: $unum = $2;
3452: $group = $3;
3453: $file_name = $3.'/'.$4;
3454: }
3455: if (wantarray) {
3456: return ($type,$udom,$unum,$file_name,$group);
3457: }
3458: return $type;
3459: }
3460:
3461: sub is_portfolio_url {
3462: my ($url) = @_;
3463: return scalar(&parse_portfolio_url($url));
3464: }
3465:
1.798 raeburn 3466: sub is_portfolio_file {
3467: my ($file) = @_;
3468: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
3469: return 1;
3470: }
3471: return;
3472: }
3473:
3474:
1.341 www 3475: # ---------------------------------------------- Custom access rule evaluation
3476:
3477: sub customaccess {
3478: my ($priv,$uri)=@_;
1.620 albertel 3479: my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343 www 3480: $urealm=~s/^\W//;
3481: my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341 www 3482: my $access=0;
1.800 albertel 3483: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
3484: my ($effect,$realm,$role)=split(/\:/,$right);
1.343 www 3485: if ($role) {
3486: if ($role ne $urole) { next; }
3487: }
1.800 albertel 3488: foreach my $scope (split(/\s*\,\s*/,$realm)) {
3489: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343 www 3490: if ($tdom) {
3491: if ($tdom ne $udom) { next; }
3492: }
3493: if ($tcrs) {
3494: if ($tcrs ne $ucrs) { next; }
3495: }
3496: if ($tsec) {
3497: if ($tsec ne $usec) { next; }
3498: }
3499: $access=($effect eq 'allow');
3500: last;
1.342 www 3501: }
1.402 bowersj2 3502: if ($realm eq '' && $role eq '') {
3503: $access=($effect eq 'allow');
3504: }
1.341 www 3505: }
3506: return $access;
3507: }
3508:
1.103 harris41 3509: # ------------------------------------------------- Check for a user privilege
1.12 www 3510:
3511: sub allowed {
1.579 albertel 3512: my ($priv,$uri,$symb)=@_;
1.705 albertel 3513: my $ver_orguri=$uri;
1.439 www 3514: $uri=&deversion($uri);
1.152 www 3515: my $orguri=$uri;
1.52 www 3516: $uri=&declutter($uri);
1.545 banghart 3517:
1.620 albertel 3518: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 3519: # Free bre access to adm and meta resources
1.775 albertel 3520: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 3521: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
3522: && ($priv eq 'bre')) {
1.14 www 3523: return 'F';
1.159 www 3524: }
3525:
1.545 banghart 3526: # Free bre access to user's own portfolio contents
1.714 raeburn 3527: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 3528: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 3529: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545 banghart 3530: return 'F';
3531: }
3532:
1.762 raeburn 3533: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 3534: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
3535: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
3536: if (exists($env{'request.course.id'})) {
3537: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3538: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3539: if (($domain eq $cdom) && ($name eq $cnum)) {
3540: my $courseprivid=$env{'request.course.id'};
3541: $courseprivid=~s/\_/\//;
3542: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
3543: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
3544: return $1;
1.762 raeburn 3545: } else {
3546: if ($env{'request.course.sec'}) {
3547: $courseprivid.='/'.$env{'request.course.sec'};
3548: }
3549: if ($env{'user.priv.'.$env{'request.role'}.'./'.
3550: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
3551: return $2;
3552: }
1.714 raeburn 3553: }
3554: }
3555: }
3556: }
3557:
1.159 www 3558: # Free bre to public access
3559:
3560: if ($priv eq 'bre') {
1.238 www 3561: my $copyright=&metadata($uri,'copyright');
1.620 albertel 3562: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 3563: return 'F';
3564: }
1.238 www 3565: if ($copyright eq 'priv') {
3566: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 3567: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 3568: return '';
3569: }
3570: }
3571: if ($copyright eq 'domain') {
3572: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 3573: unless (($env{'user.domain'} eq $1) ||
3574: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 3575: return '';
3576: }
1.262 matthew 3577: }
1.620 albertel 3578: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 3579: # Library role, so allow browsing of resources in this domain.
3580: return 'F';
1.238 www 3581: }
1.341 www 3582: if ($copyright eq 'custom') {
3583: unless (&customaccess($priv,$uri)) { return ''; }
3584: }
1.14 www 3585: }
1.264 matthew 3586: # Domain coordinator is trying to create a course
1.620 albertel 3587: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 3588: # uri is the requested domain in this case.
3589: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 3590: # a role of dc for the domain in question.
1.620 albertel 3591: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 3592: }
1.29 www 3593:
1.52 www 3594: my $thisallowed='';
3595: my $statecond=0;
3596: my $courseprivid='';
3597:
3598: # Course
3599:
1.620 albertel 3600: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 3601: $thisallowed.=$1;
3602: }
1.29 www 3603:
1.52 www 3604: # Domain
3605:
1.620 albertel 3606: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 3607: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 3608: $thisallowed.=$1;
3609: }
1.52 www 3610:
3611: # Course: uri itself is a course
1.66 www 3612: my $courseuri=$uri;
3613: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 3614: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 3615:
1.620 albertel 3616: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 3617: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 3618: $thisallowed.=$1;
3619: }
1.29 www 3620:
1.665 albertel 3621: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 3622: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 3623: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 3624: $thisallowed='';
1.671 raeburn 3625: my ($match)=&is_on_map($uri);
3626: if ($match) {
3627: if ($env{'user.priv.'.$env{'request.role'}.'./'}
3628: =~/\Q$priv\E\&([^\:]*)/) {
3629: $thisallowed.=$1;
3630: }
3631: } else {
1.705 albertel 3632: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 3633: if ($refuri) {
3634: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 3635: $thisallowed='F';
1.671 raeburn 3636: } else {
3637: $refuri=&declutter($refuri);
3638: my ($match) = &is_on_map($refuri);
3639: if ($match) {
3640: $thisallowed='F';
3641: }
1.669 raeburn 3642: }
1.671 raeburn 3643: }
3644: }
1.314 www 3645: }
1.492 albertel 3646:
1.766 albertel 3647: if ($priv eq 'bre'
3648: && $thisallowed ne 'F'
3649: && $thisallowed ne '2'
3650: && &is_portfolio_url($uri)) {
3651: $thisallowed = &portfolio_access($uri);
3652: }
3653:
1.52 www 3654: # Full access at system, domain or course-wide level? Exit.
1.29 www 3655:
3656: if ($thisallowed=~/F/) {
3657: return 'F';
3658: }
3659:
1.52 www 3660: # If this is generating or modifying users, exit with special codes
1.29 www 3661:
1.643 www 3662: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
3663: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 3664: my ($audom,$auname)=split('/',$uri);
1.643 www 3665: # no author name given, so this just checks on the general right to make a co-author in this domain
3666: unless ($auname) { return $thisallowed; }
3667: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 3668: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
3669: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
3670: ($audom ne $env{'request.role.domain'}))) { return ''; }
3671: }
1.52 www 3672: return $thisallowed;
3673: }
3674: #
1.103 harris41 3675: # Gathered so far: system, domain and course wide privileges
1.52 www 3676: #
3677: # Course: See if uri or referer is an individual resource that is part of
3678: # the course
3679:
1.620 albertel 3680: if ($env{'request.course.id'}) {
1.232 www 3681:
1.620 albertel 3682: $courseprivid=$env{'request.course.id'};
3683: if ($env{'request.course.sec'}) {
3684: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 3685: }
3686: $courseprivid=~s/\_/\//;
3687: my $checkreferer=1;
1.232 www 3688: my ($match,$cond)=&is_on_map($uri);
3689: if ($match) {
3690: $statecond=$cond;
1.620 albertel 3691: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 3692: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 3693: $thisallowed.=$1;
3694: $checkreferer=0;
3695: }
1.29 www 3696: }
1.83 www 3697:
1.148 www 3698: if ($checkreferer) {
1.620 albertel 3699: my $refuri=$env{'httpref.'.$orguri};
1.148 www 3700: unless ($refuri) {
1.800 albertel 3701: foreach my $key (keys(%env)) {
3702: if ($key=~/^httpref\..*\*/) {
3703: my $pattern=$key;
1.156 www 3704: $pattern=~s/^httpref\.\/res\///;
1.148 www 3705: $pattern=~s/\*/\[\^\/\]\+/g;
3706: $pattern=~s/\//\\\//g;
1.152 www 3707: if ($orguri=~/$pattern/) {
1.800 albertel 3708: $refuri=$env{$key};
1.148 www 3709: }
3710: }
1.191 harris41 3711: }
1.148 www 3712: }
1.232 www 3713:
1.148 www 3714: if ($refuri) {
1.152 www 3715: $refuri=&declutter($refuri);
1.232 www 3716: my ($match,$cond)=&is_on_map($refuri);
3717: if ($match) {
3718: my $refstatecond=$cond;
1.620 albertel 3719: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 3720: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 3721: $thisallowed.=$1;
1.53 www 3722: $uri=$refuri;
3723: $statecond=$refstatecond;
1.52 www 3724: }
3725: }
1.148 www 3726: }
1.29 www 3727: }
1.52 www 3728: }
1.29 www 3729:
1.52 www 3730: #
1.103 harris41 3731: # Gathered now: all privileges that could apply, and condition number
1.52 www 3732: #
3733: #
3734: # Full or no access?
3735: #
1.29 www 3736:
1.52 www 3737: if ($thisallowed=~/F/) {
3738: return 'F';
3739: }
1.29 www 3740:
1.52 www 3741: unless ($thisallowed) {
3742: return '';
3743: }
1.29 www 3744:
1.52 www 3745: # Restrictions exist, deal with them
3746: #
3747: # C:according to course preferences
3748: # R:according to resource settings
3749: # L:unless locked
3750: # X:according to user session state
3751: #
3752:
3753: # Possibly locked functionality, check all courses
1.54 www 3754: # Locks might take effect only after 10 minutes cache expiration for other
3755: # courses, and 2 minutes for current course
1.52 www 3756:
3757: my $envkey;
3758: if ($thisallowed=~/L/) {
1.620 albertel 3759: foreach $envkey (keys %env) {
1.54 www 3760: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
3761: my $courseid=$2;
3762: my $roleid=$1.'.'.$2;
1.92 www 3763: $courseid=~s/^\///;
1.54 www 3764: my $expiretime=600;
1.620 albertel 3765: if ($env{'request.role'} eq $roleid) {
1.54 www 3766: $expiretime=120;
3767: }
3768: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
3769: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 3770: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 3771: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 3772: }
1.620 albertel 3773: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
3774: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
3775: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
3776: &log($env{'user.domain'},$env{'user.name'},
3777: $env{'user.home'},
1.57 www 3778: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 3779: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 3780: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 3781: return '';
3782: }
3783: }
1.620 albertel 3784: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
3785: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
3786: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
3787: &log($env{'user.domain'},$env{'user.name'},
3788: $env{'user.home'},
1.57 www 3789: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 3790: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 3791: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 3792: return '';
3793: }
3794: }
3795: }
1.29 www 3796: }
1.52 www 3797: }
3798:
3799: #
3800: # Rest of the restrictions depend on selected course
3801: #
3802:
1.620 albertel 3803: unless ($env{'request.course.id'}) {
1.766 albertel 3804: if ($thisallowed eq 'A') {
3805: return 'A';
3806: } else {
3807: return '1';
3808: }
1.52 www 3809: }
1.29 www 3810:
1.52 www 3811: #
3812: # Now user is definitely in a course
3813: #
1.53 www 3814:
3815:
3816: # Course preferences
3817:
3818: if ($thisallowed=~/C/) {
1.620 albertel 3819: my $rolecode=(split(/\./,$env{'request.role'}))[0];
3820: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
3821: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 3822: =~/\Q$rolecode\E/) {
1.689 albertel 3823: if ($priv ne 'pch') {
3824: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
3825: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
3826: $env{'request.course.id'});
3827: }
1.237 www 3828: return '';
3829: }
3830:
1.620 albertel 3831: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 3832: =~/\Q$unamedom\E/) {
1.689 albertel 3833: if ($priv ne 'pch') {
3834: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
3835: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
3836: $env{'request.course.id'});
3837: }
1.54 www 3838: return '';
3839: }
1.53 www 3840: }
3841:
3842: # Resource preferences
3843:
3844: if ($thisallowed=~/R/) {
1.620 albertel 3845: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 3846: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 3847: if ($priv ne 'pch') {
3848: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
3849: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
3850: }
3851: return '';
1.54 www 3852: }
1.53 www 3853: }
1.30 www 3854:
1.246 www 3855: # Restricted by state or randomout?
1.30 www 3856:
1.52 www 3857: if ($thisallowed=~/X/) {
1.620 albertel 3858: if ($env{'acc.randomout'}) {
1.579 albertel 3859: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 3860: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 3861: return '';
3862: }
1.247 www 3863: }
3864: if (&condval($statecond)) {
1.52 www 3865: return '2';
3866: } else {
3867: return '';
3868: }
3869: }
1.30 www 3870:
1.766 albertel 3871: if ($thisallowed eq 'A') {
3872: return 'A';
3873: }
1.52 www 3874: return 'F';
1.232 www 3875: }
3876:
1.710 albertel 3877: sub split_uri_for_cond {
3878: my $uri=&deversion(&declutter(shift));
3879: my @uriparts=split(/\//,$uri);
3880: my $filename=pop(@uriparts);
3881: my $pathname=join('/',@uriparts);
3882: return ($pathname,$filename);
3883: }
1.232 www 3884: # --------------------------------------------------- Is a resource on the map?
3885:
3886: sub is_on_map {
1.710 albertel 3887: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 3888: #Trying to find the conditional for the file
1.620 albertel 3889: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 3890: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 3891: if ($match) {
1.289 bowersj2 3892: return (1,$1);
3893: } else {
1.434 www 3894: return (0,0);
1.289 bowersj2 3895: }
1.12 www 3896: }
3897:
1.427 www 3898: # --------------------------------------------------------- Get symb from alias
3899:
3900: sub get_symb_from_alias {
3901: my $symb=shift;
3902: my ($map,$resid,$url)=&decode_symb($symb);
3903: # Already is a symb
3904: if ($url) { return $symb; }
3905: # Must be an alias
3906: my $aliassymb='';
3907: my %bighash;
1.620 albertel 3908: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 3909: &GDBM_READER(),0640)) {
3910: my $rid=$bighash{'mapalias_'.$symb};
3911: if ($rid) {
3912: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 3913: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
3914: $resid,$bighash{'src_'.$rid});
1.427 www 3915: }
3916: untie %bighash;
3917: }
3918: return $aliassymb;
3919: }
3920:
1.12 www 3921: # ----------------------------------------------------------------- Define Role
3922:
3923: sub definerole {
3924: if (allowed('mcr','/')) {
3925: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 3926: foreach my $role (split(':',$sysrole)) {
3927: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 3928: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
3929: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
3930: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 3931: return "refused:s:$crole&$cqual";
3932: }
3933: }
1.191 harris41 3934: }
1.800 albertel 3935: foreach my $role (split(':',$domrole)) {
3936: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 3937: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
3938: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
3939: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 3940: return "refused:d:$crole&$cqual";
3941: }
3942: }
1.191 harris41 3943: }
1.800 albertel 3944: foreach my $role (split(':',$courole)) {
3945: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 3946: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
3947: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
3948: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 3949: return "refused:c:$crole&$cqual";
3950: }
3951: }
1.191 harris41 3952: }
1.620 albertel 3953: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
3954: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 3955: "rolesdef_$rolename=".
3956: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 3957: return reply($command,$env{'user.home'});
1.12 www 3958: } else {
3959: return 'refused';
3960: }
1.105 harris41 3961: }
3962:
3963: # ---------------- Make a metadata query against the network of library servers
3964:
3965: sub metadata_query {
1.244 matthew 3966: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 3967: my %rhash;
1.244 matthew 3968: my @server_list = (defined($server_array) ? @$server_array
3969: : keys(%libserv) );
3970: for my $server (@server_list) {
1.118 harris41 3971: unless ($custom or $customshow) {
3972: my $reply=&reply("querysend:".&escape($query),$server);
3973: $rhash{$server}=$reply;
3974: }
3975: else {
3976: my $reply=&reply("querysend:".&escape($query).':'.
3977: &escape($custom).':'.&escape($customshow),
3978: $server);
3979: $rhash{$server}=$reply;
3980: }
1.112 harris41 3981: }
1.118 harris41 3982: return \%rhash;
1.240 www 3983: }
3984:
3985: # ----------------------------------------- Send log queries and wait for reply
3986:
3987: sub log_query {
3988: my ($uname,$udom,$query,%filters)=@_;
3989: my $uhome=&homeserver($uname,$udom);
3990: if ($uhome eq 'no_host') { return 'error: no_host'; }
3991: my $uhost=$hostname{$uhome};
1.800 albertel 3992: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 3993: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
3994: $uhome);
1.479 albertel 3995: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 3996: return get_query_reply($queryid);
3997: }
3998:
1.508 raeburn 3999: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 4000:
4001: sub fetch_enrollment_query {
1.511 raeburn 4002: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 4003: my $homeserver;
1.547 raeburn 4004: my $maxtries = 1;
1.508 raeburn 4005: if ($context eq 'automated') {
4006: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 4007: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 4008: } else {
4009: $homeserver = &homeserver($cnum,$dom);
4010: }
1.506 raeburn 4011: my $host=$hostname{$homeserver};
4012: my $cmd = '';
1.800 albertel 4013: foreach my $affiliate (keys %{$affiliatesref}) {
4014: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 4015: }
4016: $cmd =~ s/%%$//;
4017: $cmd = &escape($cmd);
4018: my $query = 'fetchenrollment';
1.620 albertel 4019: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 4020: unless ($queryid=~/^\Q$host\E\_/) {
4021: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
4022: return 'error: '.$queryid;
4023: }
1.506 raeburn 4024: my $reply = &get_query_reply($queryid);
1.547 raeburn 4025: my $tries = 1;
4026: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4027: $reply = &get_query_reply($queryid);
4028: $tries ++;
4029: }
1.526 raeburn 4030: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 4031: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 4032: } else {
1.515 raeburn 4033: my @responses = split/:/,$reply;
4034: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 4035: foreach my $line (@responses) {
4036: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 4037: $$replyref{$key} = $value;
4038: }
4039: } else {
1.506 raeburn 4040: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 4041: foreach my $line (@responses) {
4042: my ($key,$value) = split(/=/,$line);
1.506 raeburn 4043: $$replyref{$key} = $value;
4044: if ($value > 0) {
1.800 albertel 4045: foreach my $item (@{$$affiliatesref{$key}}) {
4046: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 4047: my $destname = $pathname.'/'.$filename;
4048: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 4049: if ($xml_classlist =~ /^error/) {
4050: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
4051: } else {
1.506 raeburn 4052: if ( open(FILE,">$destname") ) {
4053: print FILE &unescape($xml_classlist);
4054: close(FILE);
1.526 raeburn 4055: } else {
4056: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 4057: }
4058: }
4059: }
4060: }
4061: }
4062: }
4063: return 'ok';
4064: }
4065: return 'error';
4066: }
4067:
1.242 www 4068: sub get_query_reply {
4069: my $queryid=shift;
1.240 www 4070: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
4071: my $reply='';
4072: for (1..100) {
4073: sleep 2;
4074: if (-e $replyfile.'.end') {
1.448 albertel 4075: if (open(my $fh,$replyfile)) {
1.240 www 4076: $reply.=<$fh>;
1.448 albertel 4077: close($fh);
1.240 www 4078: } else { return 'error: reply_file_error'; }
1.242 www 4079: return &unescape($reply);
4080: }
1.240 www 4081: }
1.242 www 4082: return 'timeout:'.$queryid;
1.240 www 4083: }
4084:
4085: sub courselog_query {
1.241 www 4086: #
4087: # possible filters:
4088: # url: url or symb
4089: # username
4090: # domain
4091: # action: view, submit, grade
4092: # start: timestamp
4093: # end: timestamp
4094: #
1.240 www 4095: my (%filters)=@_;
1.620 albertel 4096: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 4097: if ($filters{'url'}) {
4098: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
4099: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
4100: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
4101: }
1.620 albertel 4102: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4103: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 4104: return &log_query($cname,$cdom,'courselog',%filters);
4105: }
4106:
4107: sub userlog_query {
4108: my ($uname,$udom,%filters)=@_;
4109: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 4110: }
4111:
1.506 raeburn 4112: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
4113:
4114: sub auto_run {
1.508 raeburn 4115: my ($cnum,$cdom) = @_;
4116: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 4117: my $response = &reply('autorun:'.$cdom,$homeserver);
1.506 raeburn 4118: return $response;
4119: }
1.776 albertel 4120:
1.506 raeburn 4121: sub auto_get_sections {
1.508 raeburn 4122: my ($cnum,$cdom,$inst_coursecode) = @_;
4123: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 4124: my @secs = ();
1.511 raeburn 4125: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 4126: unless ($response eq 'refused') {
4127: @secs = split/:/,$response;
4128: }
4129: return @secs;
4130: }
1.776 albertel 4131:
1.506 raeburn 4132: sub auto_new_course {
1.508 raeburn 4133: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
4134: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 4135: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 4136: return $response;
4137: }
1.776 albertel 4138:
1.506 raeburn 4139: sub auto_validate_courseID {
1.508 raeburn 4140: my ($cnum,$cdom,$inst_course_id) = @_;
4141: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 4142: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 4143: return $response;
4144: }
1.776 albertel 4145:
1.506 raeburn 4146: sub auto_create_password {
1.508 raeburn 4147: my ($cnum,$cdom,$authparam) = @_;
4148: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 4149: my $create_passwd = 0;
4150: my $authchk = '';
1.511 raeburn 4151: my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506 raeburn 4152: if ($response eq 'refused') {
4153: $authchk = 'refused';
4154: } else {
4155: ($authparam,$create_passwd,$authchk) = split/:/,$response;
4156: }
4157: return ($authparam,$create_passwd,$authchk);
4158: }
4159:
1.706 raeburn 4160: sub auto_photo_permission {
4161: my ($cnum,$cdom,$students) = @_;
4162: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 4163: my ($outcome,$perm_reqd,$conditions) =
4164: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 4165: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4166: return (undef,undef);
4167: }
1.706 raeburn 4168: return ($outcome,$perm_reqd,$conditions);
4169: }
4170:
4171: sub auto_checkphotos {
4172: my ($uname,$udom,$pid) = @_;
4173: my $homeserver = &homeserver($uname,$udom);
4174: my ($result,$resulttype);
4175: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 4176: &escape($uname).':'.&escape($pid),
4177: $homeserver));
1.709 albertel 4178: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4179: return (undef,undef);
4180: }
1.706 raeburn 4181: if ($outcome) {
4182: ($result,$resulttype) = split(/:/,$outcome);
4183: }
4184: return ($result,$resulttype);
4185: }
4186:
4187: sub auto_photochoice {
4188: my ($cnum,$cdom) = @_;
4189: my $homeserver = &homeserver($cnum,$cdom);
4190: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 4191: &escape($cdom),
4192: $homeserver)));
1.709 albertel 4193: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4194: return (undef,undef);
4195: }
1.706 raeburn 4196: return ($update,$comment);
4197: }
4198:
4199: sub auto_photoupdate {
4200: my ($affiliatesref,$dom,$cnum,$photo) = @_;
4201: my $homeserver = &homeserver($cnum,$dom);
4202: my $host=$hostname{$homeserver};
4203: my $cmd = '';
4204: my $maxtries = 1;
1.800 albertel 4205: foreach my $affiliate (keys(%{$affiliatesref})) {
4206: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 4207: }
4208: $cmd =~ s/%%$//;
4209: $cmd = &escape($cmd);
4210: my $query = 'institutionalphotos';
4211: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
4212: unless ($queryid=~/^\Q$host\E\_/) {
4213: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
4214: return 'error: '.$queryid;
4215: }
4216: my $reply = &get_query_reply($queryid);
4217: my $tries = 1;
4218: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4219: $reply = &get_query_reply($queryid);
4220: $tries ++;
4221: }
4222: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
4223: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
4224: } else {
4225: my @responses = split(/:/,$reply);
4226: my $outcome = shift(@responses);
4227: foreach my $item (@responses) {
4228: my ($key,$value) = split(/=/,$item);
4229: $$photo{$key} = $value;
4230: }
4231: return $outcome;
4232: }
4233: return 'error';
4234: }
4235:
1.521 raeburn 4236: sub auto_instcode_format {
1.793 albertel 4237: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
4238: $cat_order) = @_;
1.521 raeburn 4239: my $courses = '';
1.772 raeburn 4240: my @homeservers;
1.521 raeburn 4241: if ($caller eq 'global') {
1.793 albertel 4242: foreach my $tryserver (keys(%libserv)) {
1.584 raeburn 4243: if ($hostdom{$tryserver} eq $codedom) {
1.793 albertel 4244: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.772 raeburn 4245: push(@homeservers,$tryserver);
4246: }
1.584 raeburn 4247: }
4248: }
1.521 raeburn 4249: } else {
1.772 raeburn 4250: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 4251: }
1.793 albertel 4252: foreach my $code (keys(%{$instcodes})) {
4253: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 4254: }
4255: chop($courses);
1.772 raeburn 4256: my $ok_response = 0;
4257: my $response;
4258: while (@homeservers > 0 && $ok_response == 0) {
4259: my $server = shift(@homeservers);
4260: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
4261: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
4262: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.793 albertel 4263: split/:/,$response;
1.772 raeburn 4264: %{$codes} = (%{$codes},&str2hash($codes_str));
4265: push(@{$codetitles},&str2array($codetitles_str));
4266: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
4267: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
4268: $ok_response = 1;
4269: }
4270: }
4271: if ($ok_response) {
1.521 raeburn 4272: return 'ok';
1.772 raeburn 4273: } else {
4274: return $response;
1.521 raeburn 4275: }
4276: }
4277:
1.792 raeburn 4278: sub auto_instcode_defaults {
4279: my ($domain,$returnhash,$code_order) = @_;
4280: my @homeservers;
1.793 albertel 4281: foreach my $tryserver (keys(%libserv)) {
1.792 raeburn 4282: if ($hostdom{$tryserver} eq $domain) {
1.793 albertel 4283: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.792 raeburn 4284: push(@homeservers,$tryserver);
4285: }
4286: }
4287: }
4288: my $ok_response = 0;
4289: my $response;
4290: while (@homeservers > 0 && $ok_response == 0) {
4291: my $server = shift(@homeservers);
4292: $response=&reply('autoinstcodedefaults:'.$domain,$server);
4293: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
1.793 albertel 4294: foreach my $pair (split(/\&/,$response)) {
4295: my ($name,$value)=split(/\=/,$pair);
1.792 raeburn 4296: if ($name eq 'code_order') {
1.796 raeburn 4297: @{$code_order} = split(/\&/,&unescape($value));
1.792 raeburn 4298: } else {
1.796 raeburn 4299: $returnhash->{&unescape($name)}=&unescape($value);
1.792 raeburn 4300: }
4301: }
1.804 ! raeburn 4302: $ok_response = 1;
1.792 raeburn 4303: }
4304: }
4305: if ($ok_response) {
4306: return 'ok';
4307: } else {
4308: return $response;
4309: }
4310: }
4311:
1.777 albertel 4312: sub auto_validate_class_sec {
1.773 raeburn 4313: my ($cdom,$cnum,$owner,$inst_class) = @_;
4314: my $homeserver = &homeserver($cnum,$cdom);
4315: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774 banghart 4316: &escape($owner).':'.$cdom,$homeserver);
1.773 raeburn 4317: return $response;
4318: }
4319:
1.679 raeburn 4320: # ------------------------------------------------------- Course Group routines
4321:
4322: sub get_coursegroups {
1.683 raeburn 4323: my ($cdom,$cnum,$group) = @_;
4324: return(&dump('coursegroups',$cdom,$cnum,$group));
1.679 raeburn 4325: }
4326:
4327: sub modify_coursegroup {
4328: my ($cdom,$cnum,$groupsettings) = @_;
4329: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
4330: }
4331:
4332: sub modify_group_roles {
4333: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
4334: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
4335: my $role = 'gr/'.&escape($userprivs);
4336: my ($uname,$udom) = split(/:/,$user);
4337: my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684 raeburn 4338: if ($result eq 'ok') {
4339: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
4340: }
1.679 raeburn 4341: return $result;
4342: }
4343:
4344: sub modify_coursegroup_membership {
4345: my ($cdom,$cnum,$membership) = @_;
4346: my $result = &put('groupmembership',$membership,$cdom,$cnum);
4347: return $result;
4348: }
4349:
1.682 raeburn 4350: sub get_active_groups {
4351: my ($udom,$uname,$cdom,$cnum) = @_;
4352: my $now = time;
4353: my %groups = ();
4354: foreach my $key (keys(%env)) {
4355: if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
4356: my ($start,$end) = split(/\./,$env{$key});
4357: if (($end!=0) && ($end<$now)) { next; }
4358: if (($start!=0) && ($start>$now)) { next; }
4359: if ($1 eq $cdom && $2 eq $cnum) {
4360: $groups{$3} = $env{$key} ;
4361: }
4362: }
4363: }
4364: return %groups;
4365: }
4366:
1.683 raeburn 4367: sub get_group_membership {
4368: my ($cdom,$cnum,$group) = @_;
4369: return(&dump('groupmembership',$cdom,$cnum,$group));
4370: }
4371:
4372: sub get_users_groups {
4373: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 4374: my @usersgroups;
1.683 raeburn 4375: my $cachetime=1800;
4376: $courseid=~s/\_/\//g;
4377: $courseid=~s/^(\w)/\/$1/;
4378:
4379: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 4380: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
4381: if (defined($cached)) {
1.734 albertel 4382: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 4383: } else {
4384: $grouplist = '';
4385: my %roleshash = &dump('roles',$udom,$uname,$courseid);
4386: my ($tmp) = keys(%roleshash);
4387: if ($tmp=~/^error:/) {
4388: &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
4389: } else {
4390: my $access_end = $env{'course.'.$courseid.
4391: '.default_enrollment_end_date'};
4392: my $now = time;
1.734 albertel 4393: foreach my $key (keys(%roleshash)) {
1.733 raeburn 4394: if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
4395: my $group = $1;
4396: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
4397: my $start = $2;
4398: my $end = $1;
4399: if ($start == -1) { next; } # deleted from group
4400: if (($start!=0) && ($start>$now)) { next; }
4401: if (($end!=0) && ($end<$now)) {
4402: if ($access_end && $access_end < $now) {
4403: if ($access_end - $end < 86400) {
4404: push(@usersgroups,$group);
4405: }
4406: }
4407: next;
4408: }
4409: push(@usersgroups,$group);
4410: }
1.683 raeburn 4411: }
4412: }
1.733 raeburn 4413: @usersgroups = &sort_course_groups($courseid,@usersgroups);
4414: $grouplist = join(':',@usersgroups);
4415: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 4416: }
4417: }
1.733 raeburn 4418: return @usersgroups;
1.683 raeburn 4419: }
4420:
4421: sub devalidate_getgroups_cache {
4422: my ($udom,$uname,$cdom,$cnum)=@_;
4423: my $courseid = $cdom.'_'.$cnum;
4424: $courseid=~s/\_/\//g;
4425: $courseid=~s/^(\w)/\/$1/;
4426: my $hashid="$udom:$uname:$courseid";
4427: &devalidate_cache_new('getgroups',$hashid);
4428: }
4429:
1.12 www 4430: # ------------------------------------------------------------------ Plain Text
4431:
4432: sub plaintext {
1.742 raeburn 4433: my ($short,$type,$cid) = @_;
1.758 albertel 4434: if ($short =~ /^cr/) {
4435: return (split('/',$short))[-1];
4436: }
1.742 raeburn 4437: if (!defined($cid)) {
4438: $cid = $env{'request.course.id'};
4439: }
4440: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
4441: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
4442: '.plaintext'});
4443: }
4444: my %rolenames = (
4445: Course => 'std',
4446: Group => 'alt1',
4447: );
4448: if (defined($type) &&
4449: defined($rolenames{$type}) &&
4450: defined($prp{$short}{$rolenames{$type}})) {
4451: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
4452: } else {
4453: return &Apache::lonlocal::mt($prp{$short}{'std'});
4454: }
1.12 www 4455: }
4456:
4457: # ----------------------------------------------------------------- Assign Role
4458:
4459: sub assignrole {
1.357 www 4460: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21 www 4461: my $mrole;
4462: if ($role =~ /^cr\//) {
1.393 www 4463: my $cwosec=$url;
4464: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
4465: unless (&allowed('ccr',$cwosec)) {
1.104 www 4466: &logthis('Refused custom assignrole: '.
4467: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 4468: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 4469: return 'refused';
4470: }
1.21 www 4471: $mrole='cr';
1.678 raeburn 4472: } elsif ($role =~ /^gr\//) {
4473: my $cwogrp=$url;
4474: $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
4475: unless (&allowed('mdg',$cwogrp)) {
4476: &logthis('Refused group assignrole: '.
4477: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4478: $env{'user.name'}.' at '.$env{'user.domain'});
4479: return 'refused';
4480: }
4481: $mrole='gr';
1.21 www 4482: } else {
1.82 www 4483: my $cwosec=$url;
1.83 www 4484: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373 www 4485: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
1.104 www 4486: &logthis('Refused assignrole: '.
4487: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 4488: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 4489: return 'refused';
4490: }
1.21 www 4491: $mrole=$role;
4492: }
1.620 albertel 4493: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 4494: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 4495: if ($end) { $command.='_'.$end; }
1.21 www 4496: if ($start) {
4497: if ($end) {
1.81 www 4498: $command.='_'.$start;
1.21 www 4499: } else {
1.81 www 4500: $command.='_0_'.$start;
1.21 www 4501: }
4502: }
1.739 raeburn 4503: my $origstart = $start;
4504: my $origend = $end;
1.357 www 4505: # actually delete
4506: if ($deleteflag) {
1.373 www 4507: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 4508: # modify command to delete the role
1.620 albertel 4509: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 4510: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 4511: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 4512: # set start and finish to negative values for userrolelog
4513: $start=-1;
4514: $end=-1;
4515: }
4516: }
4517: # send command
1.349 www 4518: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 4519: # log new user role if status is ok
1.349 www 4520: if ($answer eq 'ok') {
1.663 raeburn 4521: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 4522: # for course roles, perform group memberships changes triggered by role change.
4523: unless ($role =~ /^gr/) {
4524: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
4525: $origstart);
4526: }
1.349 www 4527: }
4528: return $answer;
1.169 harris41 4529: }
4530:
4531: # -------------------------------------------------- Modify user authentication
1.197 www 4532: # Overrides without validation
4533:
1.169 harris41 4534: sub modifyuserauth {
4535: my ($udom,$uname,$umode,$upass)=@_;
4536: my $uhome=&homeserver($uname,$udom);
1.197 www 4537: unless (&allowed('mau',$udom)) { return 'refused'; }
4538: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 4539: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4540: ' in domain '.$env{'request.role.domain'});
1.169 harris41 4541: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
4542: &escape($upass),$uhome);
1.620 albertel 4543: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 4544: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
4545: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
4546: &log($udom,,$uname,$uhome,
1.620 albertel 4547: 'Authentication changed by '.$env{'user.domain'}.', '.
4548: $env{'user.name'}.', '.$umode.
1.197 www 4549: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 4550: unless ($reply eq 'ok') {
1.197 www 4551: &logthis('Authentication mode error: '.$reply);
1.169 harris41 4552: return 'error: '.$reply;
4553: }
1.170 harris41 4554: return 'ok';
1.80 www 4555: }
4556:
1.81 www 4557: # --------------------------------------------------------------- Modify a user
1.80 www 4558:
1.81 www 4559: sub modifyuser {
1.206 matthew 4560: my ($udom, $uname, $uid,
4561: $umode, $upass, $first,
4562: $middle, $last, $gene,
1.387 www 4563: $forceid, $desiredhome, $email)=@_;
1.198 www 4564: $udom=~s/\W//g;
4565: $uname=~s/\W//g;
1.81 www 4566: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 4567: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 4568: $last.', '.$gene.'(forceid: '.$forceid.')'.
4569: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
4570: ' desiredhome not specified').
1.620 albertel 4571: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4572: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 4573: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 4574: # ----------------------------------------------------------------- Create User
1.406 albertel 4575: if (($uhome eq 'no_host') &&
4576: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 4577: my $unhome='';
1.209 matthew 4578: if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) {
4579: $unhome = $desiredhome;
1.620 albertel 4580: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
4581: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 4582: } else { # load balancing routine for determining $unhome
1.80 www 4583: my $tryserver;
1.81 www 4584: my $loadm=10000000;
1.80 www 4585: foreach $tryserver (keys %libserv) {
4586: if ($hostdom{$tryserver} eq $udom) {
4587: my $answer=reply('load',$tryserver);
4588: if (($answer=~/\d+/) && ($answer<$loadm)) {
4589: $loadm=$answer;
4590: $unhome=$tryserver;
4591: }
4592: }
4593: }
4594: }
4595: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 4596: return 'error: unable to find a home server for '.$uname.
4597: ' in domain '.$udom;
1.80 www 4598: }
4599: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
4600: &escape($upass),$unhome);
4601: unless ($reply eq 'ok') {
4602: return 'error: '.$reply;
4603: }
1.230 stredwic 4604: $uhome=&homeserver($uname,$udom,'true');
1.80 www 4605: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 4606: return 'error: unable verify users home machine.';
1.80 www 4607: }
1.209 matthew 4608: } # End of creation of new user
1.80 www 4609: # ---------------------------------------------------------------------- Add ID
4610: if ($uid) {
4611: $uid=~tr/A-Z/a-z/;
4612: my %uidhash=&idrget($udom,$uname);
1.196 www 4613: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
4614: && (!$forceid)) {
1.80 www 4615: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 4616: return 'error: user id "'.$uid.'" does not match '.
4617: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 4618: }
4619: } else {
4620: &idput($udom,($uname => $uid));
4621: }
4622: }
4623: # -------------------------------------------------------------- Add names, etc
1.313 matthew 4624: my @tmp=&get('environment',
1.134 albertel 4625: ['firstname','middlename','lastname','generation'],
4626: $udom,$uname);
1.313 matthew 4627: my %names;
4628: if ($tmp[0] =~ m/^error:.*/) {
4629: %names=();
4630: } else {
4631: %names = @tmp;
4632: }
1.388 www 4633: #
4634: # Make sure to not trash student environment if instructor does not bother
4635: # to supply name and email information
4636: #
4637: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 4638: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 4639: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 4640: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 4641: if ($email) {
4642: $email=~s/[^\w\@\.\-\,]//gs;
4643: if ($email=~/\@/) { $names{'notification'} = $email;
4644: $names{'critnotification'} = $email;
4645: $names{'permanentemail'} = $email; }
4646: }
1.134 albertel 4647: my $reply = &put('environment', \%names, $udom,$uname);
4648: if ($reply ne 'ok') { return 'error: '.$reply; }
1.680 www 4649: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81 www 4650: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 4651: $umode.', '.$first.', '.$middle.', '.
4652: $last.', '.$gene.' by '.
1.620 albertel 4653: $env{'user.name'}.' at '.$env{'user.domain'});
1.134 albertel 4654: return 'ok';
1.80 www 4655: }
4656:
1.81 www 4657: # -------------------------------------------------------------- Modify student
1.80 www 4658:
1.81 www 4659: sub modifystudent {
4660: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515 raeburn 4661: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455 albertel 4662: if (!$cid) {
1.620 albertel 4663: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 4664: return 'not_in_class';
4665: }
1.80 www 4666: }
4667: # --------------------------------------------------------------- Make the user
1.81 www 4668: my $reply=&modifyuser
1.209 matthew 4669: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 4670: $desiredhome,$email);
1.80 www 4671: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 4672: # This will cause &modify_student_enrollment to get the uid from the
4673: # students environment
4674: $uid = undef if (!$forceid);
1.455 albertel 4675: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515 raeburn 4676: $gene,$usec,$end,$start,$type,$locktype,$cid);
1.297 matthew 4677: return $reply;
4678: }
4679:
4680: sub modify_student_enrollment {
1.515 raeburn 4681: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455 albertel 4682: my ($cdom,$cnum,$chome);
4683: if (!$cid) {
1.620 albertel 4684: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 4685: return 'not_in_class';
4686: }
1.620 albertel 4687: $cdom=$env{'course.'.$cid.'.domain'};
4688: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 4689: } else {
4690: ($cdom,$cnum)=split(/_/,$cid);
4691: }
1.620 albertel 4692: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 4693: if (!$chome) {
1.457 raeburn 4694: $chome=&homeserver($cnum,$cdom);
1.297 matthew 4695: }
1.455 albertel 4696: if (!$chome) { return 'unknown_course'; }
1.297 matthew 4697: # Make sure the user exists
1.81 www 4698: my $uhome=&homeserver($uname,$udom);
4699: if (($uhome eq '') || ($uhome eq 'no_host')) {
4700: return 'error: no such user';
4701: }
1.297 matthew 4702: # Get student data if we were not given enough information
4703: if (!defined($first) || $first eq '' ||
4704: !defined($last) || $last eq '' ||
4705: !defined($uid) || $uid eq '' ||
4706: !defined($middle) || $middle eq '' ||
4707: !defined($gene) || $gene eq '') {
1.294 matthew 4708: # They did not supply us with enough data to enroll the student, so
4709: # we need to pick up more information.
1.297 matthew 4710: my %tmp = &get('environment',
1.294 matthew 4711: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 4712: ,$udom,$uname);
4713:
1.800 albertel 4714: #foreach my $key (keys(%tmp)) {
4715: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 4716: #}
1.294 matthew 4717: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
4718: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
4719: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 4720: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 4721: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
4722: }
1.556 albertel 4723: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 4724: my $reply=cput('classlist',
4725: {"$uname:$udom" =>
1.515 raeburn 4726: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 4727: $cdom,$cnum);
1.81 www 4728: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
4729: return 'error: '.$reply;
1.652 albertel 4730: } else {
4731: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 4732: }
1.297 matthew 4733: # Add student role to user
1.83 www 4734: my $uurl='/'.$cid;
1.81 www 4735: $uurl=~s/\_/\//g;
4736: if ($usec) {
4737: $uurl.='/'.$usec;
4738: }
4739: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21 www 4740: }
4741:
1.556 albertel 4742: sub format_name {
4743: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
4744: my $name;
4745: if ($first ne 'lastname') {
4746: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
4747: } else {
4748: if ($lastname=~/\S/) {
4749: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
4750: $name=~s/\s+,/,/;
4751: } else {
4752: $name.= $firstname.' '.$middlename.' '.$generation;
4753: }
4754: }
4755: $name=~s/^\s+//;
4756: $name=~s/\s+$//;
4757: $name=~s/\s+/ /g;
4758: return $name;
4759: }
4760:
1.84 www 4761: # ------------------------------------------------- Write to course preferences
4762:
4763: sub writecoursepref {
4764: my ($courseid,%prefs)=@_;
4765: $courseid=~s/^\///;
4766: $courseid=~s/\_/\//g;
4767: my ($cdomain,$cnum)=split(/\//,$courseid);
4768: my $chome=homeserver($cnum,$cdomain);
4769: if (($chome eq '') || ($chome eq 'no_host')) {
4770: return 'error: no such course';
4771: }
4772: my $cstring='';
1.800 albertel 4773: foreach my $pref (keys(%prefs)) {
4774: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 4775: }
1.84 www 4776: $cstring=~s/\&$//;
4777: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
4778: }
4779:
4780: # ---------------------------------------------------------- Make/modify course
4781:
4782: sub createcourse {
1.741 raeburn 4783: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
4784: $course_owner,$crstype)=@_;
1.84 www 4785: $url=&declutter($url);
4786: my $cid='';
1.264 matthew 4787: unless (&allowed('ccc',$udom)) {
1.84 www 4788: return 'refused';
4789: }
4790: # ------------------------------------------------------------------- Create ID
1.674 www 4791: my $uname=int(1+rand(9)).
4792: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
4793: substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84 www 4794: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
4795: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 4796: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 4797: unless (($uhome eq '') || ($uhome eq 'no_host')) {
4798: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
4799: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 4800: $uhome=&homeserver($uname,$udom,'true');
1.84 www 4801: unless (($uhome eq '') || ($uhome eq 'no_host')) {
4802: return 'error: unable to generate unique course-ID';
4803: }
4804: }
1.264 matthew 4805: # ------------------------------------------------ Check supplied server name
1.620 albertel 4806: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264 matthew 4807: if (! exists($libserv{$course_server})) {
4808: return 'error:bad server name '.$course_server;
4809: }
1.84 www 4810: # ------------------------------------------------------------- Make the course
4811: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 4812: $course_server);
1.84 www 4813: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 4814: $uhome=&homeserver($uname,$udom,'true');
1.84 www 4815: if (($uhome eq '') || ($uhome eq 'no_host')) {
4816: return 'error: no such course';
4817: }
1.271 www 4818: # ----------------------------------------------------------------- Course made
1.516 raeburn 4819: # log existence
4820: &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741 raeburn 4821: ':'.&escape($inst_code).':'.&escape($course_owner).':'.
4822: &escape($crstype),$uhome);
1.358 www 4823: &flushcourselogs();
4824: # set toplevel url
1.271 www 4825: my $topurl=$url;
4826: unless ($nonstandard) {
4827: # ------------------------------------------ For standard courses, make top url
4828: my $mapurl=&clutter($url);
1.278 www 4829: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 4830: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 4831: <map>
4832: <resource id="1" type="start"></resource>
4833: <resource id="2" src="$mapurl"></resource>
4834: <resource id="3" type="finish"></resource>
4835: <link index="1" from="1" to="2"></link>
4836: <link index="2" from="2" to="3"></link>
4837: </map>
4838: ENDINITMAP
4839: $topurl=&declutter(
1.638 albertel 4840: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 4841: );
4842: }
4843: # ----------------------------------------------------------- Write preferences
1.84 www 4844: &writecoursepref($udom.'_'.$uname,
4845: ('description' => $description,
1.271 www 4846: 'url' => $topurl));
1.84 www 4847: return '/'.$udom.'/'.$uname;
4848: }
4849:
1.21 www 4850: # ---------------------------------------------------------- Assign Custom Role
4851:
4852: sub assigncustomrole {
1.357 www 4853: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21 www 4854: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357 www 4855: $end,$start,$deleteflag);
1.21 www 4856: }
4857:
4858: # ----------------------------------------------------------------- Revoke Role
4859:
4860: sub revokerole {
1.357 www 4861: my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21 www 4862: my $now=time;
1.357 www 4863: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21 www 4864: }
4865:
4866: # ---------------------------------------------------------- Revoke Custom Role
4867:
4868: sub revokecustomrole {
1.357 www 4869: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21 www 4870: my $now=time;
1.357 www 4871: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
4872: $deleteflag);
1.17 www 4873: }
4874:
1.533 banghart 4875: # ------------------------------------------------------------ Disk usage
1.535 albertel 4876: sub diskusage {
1.533 banghart 4877: my ($udom,$uname,$directoryRoot)=@_;
4878: $directoryRoot =~ s/\/$//;
1.535 albertel 4879: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514 albertel 4880: return $listing;
1.512 banghart 4881: }
4882:
1.566 banghart 4883: sub is_locked {
4884: my ($file_name, $domain, $user) = @_;
4885: my @check;
4886: my $is_locked;
4887: push @check, $file_name;
1.613 albertel 4888: my %locked = &get('file_permissions',\@check,
1.620 albertel 4889: $env{'user.domain'},$env{'user.name'});
1.615 albertel 4890: my ($tmp)=keys(%locked);
4891: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 4892:
1.566 banghart 4893: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 4894: $is_locked = 'false';
4895: foreach my $entry (@{$locked{$file_name}}) {
4896: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 4897: $is_locked = 'true';
4898: last;
1.745 raeburn 4899: }
4900: }
1.566 banghart 4901: } else {
4902: $is_locked = 'false';
4903: }
4904: }
4905:
1.759 albertel 4906: sub declutter_portfile {
4907: my ($file) = @_;
4908: &logthis("got $file");
4909: $file =~ s-^(/portfolio/|portfolio/)-/-;
4910: &logthis("ret $file");
4911: return $file;
4912: }
4913:
1.559 banghart 4914: # ------------------------------------------------------------- Mark as Read Only
4915:
4916: sub mark_as_readonly {
4917: my ($domain,$user,$files,$what) = @_;
1.613 albertel 4918: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 4919: my ($tmp)=keys(%current_permissions);
4920: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 4921: foreach my $file (@{$files}) {
1.759 albertel 4922: $file = &declutter_portfile($file);
1.561 banghart 4923: push(@{$current_permissions{$file}},$what);
1.559 banghart 4924: }
1.613 albertel 4925: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 4926: return;
4927: }
4928:
1.572 banghart 4929: # ------------------------------------------------------------Save Selected Files
4930:
4931: sub save_selected_files {
4932: my ($user, $path, @files) = @_;
4933: my $filename = $user."savedfiles";
1.573 banghart 4934: my @other_files = &files_not_in_path($user, $path);
1.574 banghart 4935: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 4936: foreach my $file (@files) {
1.620 albertel 4937: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 4938: }
4939: foreach my $file (@other_files) {
1.574 banghart 4940: print (OUT $file."\n");
1.572 banghart 4941: }
1.574 banghart 4942: close (OUT);
1.572 banghart 4943: return 'ok';
4944: }
4945:
1.574 banghart 4946: sub clear_selected_files {
4947: my ($user) = @_;
4948: my $filename = $user."savedfiles";
4949: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
4950: print (OUT undef);
4951: close (OUT);
4952: return ("ok");
4953: }
4954:
1.572 banghart 4955: sub files_in_path {
4956: my ($user, $path) = @_;
4957: my $filename = $user."savedfiles";
4958: my %return_files;
1.574 banghart 4959: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 4960: while (my $line_in = <IN>) {
1.574 banghart 4961: chomp ($line_in);
4962: my @paths_and_file = split (m!/!, $line_in);
4963: my $file_part = pop (@paths_and_file);
4964: my $path_part = join ('/', @paths_and_file);
1.573 banghart 4965: $path_part.='/';
4966: my $path_and_file = $path_part.$file_part;
4967: if ($path_part eq $path) {
4968: $return_files{$file_part}= 'selected';
4969: }
4970: }
1.574 banghart 4971: close (IN);
4972: return (\%return_files);
1.572 banghart 4973: }
4974:
4975: # called in portfolio select mode, to show files selected NOT in current directory
4976: sub files_not_in_path {
4977: my ($user, $path) = @_;
4978: my $filename = $user."savedfiles";
4979: my @return_files;
4980: my $path_part;
1.800 albertel 4981: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
4982: while (my $line = <IN>) {
1.572 banghart 4983: #ok, I know it's clunky, but I want it to work
1.800 albertel 4984: my @paths_and_file = split(m|/|, $line);
4985: my $file_part = pop(@paths_and_file);
4986: chomp($file_part);
4987: my $path_part = join('/', @paths_and_file);
1.572 banghart 4988: $path_part .= '/';
4989: my $path_and_file = $path_part.$file_part;
4990: if ($path_part ne $path) {
1.800 albertel 4991: push(@return_files, ($path_and_file));
1.572 banghart 4992: }
4993: }
1.800 albertel 4994: close(OUT);
1.574 banghart 4995: return (@return_files);
1.572 banghart 4996: }
4997:
1.745 raeburn 4998: #----------------------------------------------Get portfolio file permissions
1.629 banghart 4999:
1.745 raeburn 5000: sub get_portfile_permissions {
5001: my ($domain,$user) = @_;
1.613 albertel 5002: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5003: my ($tmp)=keys(%current_permissions);
5004: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 5005: return \%current_permissions;
5006: }
5007:
5008: #---------------------------------------------Get portfolio file access controls
5009:
1.749 raeburn 5010: sub get_access_controls {
1.745 raeburn 5011: my ($current_permissions,$group,$file) = @_;
1.769 albertel 5012: my %access;
5013: my $real_file = $file;
5014: $file =~ s/\.meta$//;
1.745 raeburn 5015: if (defined($file)) {
1.749 raeburn 5016: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
5017: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 5018: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 5019: }
5020: }
1.745 raeburn 5021: } else {
1.749 raeburn 5022: foreach my $key (keys(%{$current_permissions})) {
5023: if ($key =~ /\0accesscontrol$/) {
5024: if (defined($group)) {
5025: if ($key !~ m-^\Q$group\E/-) {
5026: next;
5027: }
5028: }
5029: my ($fullpath) = split(/\0/,$key);
5030: if (ref($$current_permissions{$key}) eq 'HASH') {
5031: foreach my $control (keys(%{$$current_permissions{$key}})) {
5032: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
5033: }
5034: }
5035: }
5036: }
5037: }
5038: return %access;
5039: }
5040:
5041: sub modify_access_controls {
5042: my ($file_name,$changes,$domain,$user)=@_;
5043: my ($outcome,$deloutcome);
5044: my %store_permissions;
5045: my %new_values;
5046: my %new_control;
5047: my %translation;
5048: my @deletions = ();
5049: my $now = time;
5050: if (exists($$changes{'activate'})) {
5051: if (ref($$changes{'activate'}) eq 'HASH') {
5052: my @newitems = sort(keys(%{$$changes{'activate'}}));
5053: my $numnew = scalar(@newitems);
5054: for (my $i=0; $i<$numnew; $i++) {
5055: my $newkey = $newitems[$i];
5056: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 5057: if ($newkey =~ /^\d+:/) {
5058: $newkey =~ s/^(\d+)/$newid/;
5059: $translation{$1} = $newid;
5060: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
5061: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
5062: $translation{$1} = $newid;
5063: }
1.749 raeburn 5064: $new_values{$file_name."\0".$newkey} =
5065: $$changes{'activate'}{$newitems[$i]};
5066: $new_control{$newkey} = $now;
5067: }
5068: }
5069: }
5070: my %todelete;
5071: my %changed_items;
5072: foreach my $action ('delete','update') {
5073: if (exists($$changes{$action})) {
5074: if (ref($$changes{$action}) eq 'HASH') {
5075: foreach my $key (keys(%{$$changes{$action}})) {
5076: my ($itemnum) = ($key =~ /^([^:]+):/);
5077: if ($action eq 'delete') {
5078: $todelete{$itemnum} = 1;
5079: } else {
5080: $changed_items{$itemnum} = $key;
5081: }
5082: }
1.745 raeburn 5083: }
5084: }
1.749 raeburn 5085: }
5086: # get lock on access controls for file.
5087: my $lockhash = {
5088: $file_name."\0".'locked_access_records' => $env{'user.name'}.
5089: ':'.$env{'user.domain'},
5090: };
5091: my $tries = 0;
5092: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5093:
5094: while (($gotlock ne 'ok') && $tries <3) {
5095: $tries ++;
5096: sleep 1;
5097: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5098: }
5099: if ($gotlock eq 'ok') {
5100: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
5101: my ($tmp)=keys(%curr_permissions);
5102: if ($tmp=~/^error:/) { undef(%curr_permissions); }
5103: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
5104: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
5105: if (ref($curr_controls) eq 'HASH') {
5106: foreach my $control_item (keys(%{$curr_controls})) {
5107: my ($itemnum) = ($control_item =~ /^([^:]+):/);
5108: if (defined($todelete{$itemnum})) {
5109: push(@deletions,$file_name."\0".$control_item);
5110: } else {
5111: if (defined($changed_items{$itemnum})) {
5112: $new_control{$changed_items{$itemnum}} = $now;
5113: push(@deletions,$file_name."\0".$control_item);
5114: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
5115: } else {
5116: $new_control{$control_item} = $$curr_controls{$control_item};
5117: }
5118: }
1.745 raeburn 5119: }
5120: }
5121: }
1.749 raeburn 5122: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
5123: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
5124: $outcome = &put('file_permissions',\%new_values,$domain,$user);
5125: # remove lock
5126: my @del_lock = ($file_name."\0".'locked_access_records');
5127: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
5128: } else {
5129: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 5130: }
1.749 raeburn 5131: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 5132: }
5133:
5134: #------------------------------------------------------Get Marked as Read Only
5135:
5136: sub get_marked_as_readonly {
5137: my ($domain,$user,$what,$group) = @_;
5138: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 5139: my @readonly_files;
1.629 banghart 5140: my $cmp1=$what;
5141: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 5142: while (my ($file_name,$value) = each(%{$current_permissions})) {
5143: if (defined($group)) {
5144: if ($file_name !~ m-^\Q$group\E/-) {
5145: next;
5146: }
5147: }
1.561 banghart 5148: if (ref($value) eq "ARRAY"){
5149: foreach my $stored_what (@{$value}) {
1.629 banghart 5150: my $cmp2=$stored_what;
1.759 albertel 5151: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 5152: $cmp2=join('',@{$stored_what});
1.745 raeburn 5153: }
1.629 banghart 5154: if ($cmp1 eq $cmp2) {
1.561 banghart 5155: push(@readonly_files, $file_name);
1.745 raeburn 5156: last;
1.563 banghart 5157: } elsif (!defined($what)) {
5158: push(@readonly_files, $file_name);
1.745 raeburn 5159: last;
1.561 banghart 5160: }
5161: }
1.745 raeburn 5162: }
1.561 banghart 5163: }
5164: return @readonly_files;
5165: }
1.577 banghart 5166: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 5167:
1.577 banghart 5168: sub get_marked_as_readonly_hash {
1.745 raeburn 5169: my ($current_permissions,$group,$what) = @_;
1.577 banghart 5170: my %readonly_files;
1.745 raeburn 5171: while (my ($file_name,$value) = each(%{$current_permissions})) {
5172: if (defined($group)) {
5173: if ($file_name !~ m-^\Q$group\E/-) {
5174: next;
5175: }
5176: }
1.577 banghart 5177: if (ref($value) eq "ARRAY"){
5178: foreach my $stored_what (@{$value}) {
1.745 raeburn 5179: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 5180: foreach my $lock_descriptor(@{$stored_what}) {
5181: if ($lock_descriptor eq 'graded') {
5182: $readonly_files{$file_name} = 'graded';
5183: } elsif ($lock_descriptor eq 'handback') {
5184: $readonly_files{$file_name} = 'handback';
5185: } else {
5186: if (!exists($readonly_files{$file_name})) {
5187: $readonly_files{$file_name} = 'locked';
5188: }
5189: }
1.745 raeburn 5190: }
1.750 banghart 5191: }
1.577 banghart 5192: }
5193: }
5194: }
5195: return %readonly_files;
5196: }
1.559 banghart 5197: # ------------------------------------------------------------ Unmark as Read Only
5198:
5199: sub unmark_as_readonly {
1.629 banghart 5200: # unmarks $file_name (if $file_name is defined), or all files locked by $what
5201: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 5202: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 5203: $file_name = &declutter_portfile($file_name);
1.634 albertel 5204: my $symb_crs = $what;
5205: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 5206: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 5207: my ($tmp)=keys(%current_permissions);
5208: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 5209: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 5210: foreach my $file (@readonly_files) {
1.759 albertel 5211: my $clean_file = &declutter_portfile($file);
5212: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 5213: my $current_locks = $current_permissions{$file};
1.563 banghart 5214: my @new_locks;
5215: my @del_keys;
5216: if (ref($current_locks) eq "ARRAY"){
5217: foreach my $locker (@{$current_locks}) {
1.632 albertel 5218: my $compare=$locker;
1.749 raeburn 5219: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 5220: $compare=join('',@{$locker});
1.746 raeburn 5221: if ($compare ne $symb_crs) {
5222: push(@new_locks, $locker);
5223: }
1.563 banghart 5224: }
5225: }
1.650 albertel 5226: if (scalar(@new_locks) > 0) {
1.563 banghart 5227: $current_permissions{$file} = \@new_locks;
5228: } else {
5229: push(@del_keys, $file);
1.613 albertel 5230: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 5231: delete($current_permissions{$file});
1.563 banghart 5232: }
5233: }
1.561 banghart 5234: }
1.613 albertel 5235: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 5236: return;
5237: }
1.512 banghart 5238:
1.17 www 5239: # ------------------------------------------------------------ Directory lister
5240:
5241: sub dirlist {
1.253 stredwic 5242: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
5243:
1.18 www 5244: $uri=~s/^\///;
5245: $uri=~s/\/$//;
1.253 stredwic 5246: my ($udom, $uname);
5247: (undef,$udom,$uname)=split(/\//,$uri);
5248: if(defined($userdomain)) {
5249: $udom = $userdomain;
5250: }
5251: if(defined($username)) {
5252: $uname = $username;
5253: }
5254:
5255: my $dirRoot = $perlvar{'lonDocRoot'};
5256: if(defined($alternateDirectoryRoot)) {
5257: $dirRoot = $alternateDirectoryRoot;
5258: $dirRoot =~ s/\/$//;
1.751 banghart 5259: }
1.253 stredwic 5260:
5261: if($udom) {
5262: if($uname) {
1.800 albertel 5263: my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
5264: &homeserver($uname,$udom));
1.605 matthew 5265: my @listing_results;
5266: if ($listing eq 'unknown_cmd') {
1.800 albertel 5267: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
5268: &homeserver($uname,$udom));
1.605 matthew 5269: @listing_results = split(/:/,$listing);
5270: } else {
5271: @listing_results = map { &unescape($_); } split(/:/,$listing);
5272: }
5273: return @listing_results;
1.253 stredwic 5274: } elsif(!defined($alternateDirectoryRoot)) {
1.800 albertel 5275: my %allusers;
5276: foreach my $tryserver (keys(%libserv)) {
1.253 stredwic 5277: if($hostdom{$tryserver} eq $udom) {
1.800 albertel 5278: my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
5279: $udom, $tryserver);
1.605 matthew 5280: my @listing_results;
5281: if ($listing eq 'unknown_cmd') {
1.800 albertel 5282: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
5283: $udom, $tryserver);
1.605 matthew 5284: @listing_results = split(/:/,$listing);
5285: } else {
5286: @listing_results =
5287: map { &unescape($_); } split(/:/,$listing);
5288: }
5289: if ($listing_results[0] ne 'no_such_dir' &&
5290: $listing_results[0] ne 'empty' &&
5291: $listing_results[0] ne 'con_lost') {
1.800 albertel 5292: foreach my $line (@listing_results) {
5293: my ($entry) = split(/&/,$line,2);
5294: $allusers{$entry} = 1;
1.253 stredwic 5295: }
5296: }
1.191 harris41 5297: }
1.253 stredwic 5298: }
5299: my $alluserstr='';
1.800 albertel 5300: foreach my $user (sort(keys(%allusers))) {
5301: $alluserstr.=$user.'&user:';
1.253 stredwic 5302: }
5303: $alluserstr=~s/:$//;
5304: return split(/:/,$alluserstr);
5305: } else {
1.800 albertel 5306: return ('missing user name');
1.253 stredwic 5307: }
5308: } elsif(!defined($alternateDirectoryRoot)) {
5309: my $tryserver;
5310: my %alldom=();
1.800 albertel 5311: foreach $tryserver (keys(%libserv)) {
1.253 stredwic 5312: $alldom{$hostdom{$tryserver}}=1;
5313: }
5314: my $alldomstr='';
1.800 albertel 5315: foreach my $domain (sort(keys(%alldom))) {
5316: $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
1.253 stredwic 5317: }
5318: $alldomstr=~s/:$//;
5319: return split(/:/,$alldomstr);
5320: } else {
1.800 albertel 5321: return ('missing domain');
1.275 stredwic 5322: }
5323: }
5324:
5325: # --------------------------------------------- GetFileTimestamp
5326: # This function utilizes dirlist and returns the date stamp for
5327: # when it was last modified. It will also return an error of -1
5328: # if an error occurs
5329:
1.410 matthew 5330: ##
5331: ## FIXME: This subroutine assumes its caller knows something about the
5332: ## directory structure of the home server for the student ($root).
5333: ## Not a good assumption to make. Since this is for looking up files
5334: ## in user directories, the full path should be constructed by lond, not
5335: ## whatever machine we request data from.
5336: ##
1.275 stredwic 5337: sub GetFileTimestamp {
5338: my ($studentDomain,$studentName,$filename,$root)=@_;
5339: $studentDomain=~s/\W//g;
5340: $studentName=~s/\W//g;
5341: my $subdir=$studentName.'__';
5342: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
5343: my $proname="$studentDomain/$subdir/$studentName";
5344: $proname .= '/'.$filename;
1.375 matthew 5345: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
5346: $studentName, $root);
1.275 stredwic 5347: my @stats = split('&', $fileStat);
5348: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 5349: # @stats contains first the filename, then the stat output
5350: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 5351: } else {
5352: return -1;
1.253 stredwic 5353: }
1.26 www 5354: }
5355:
1.712 albertel 5356: sub stat_file {
5357: my ($uri) = @_;
1.787 albertel 5358: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 5359:
1.712 albertel 5360: my ($udom,$uname,$file,$dir);
5361: if ($uri =~ m-^/(uploaded|editupload)/-) {
5362: ($udom,$uname,$file) =
5363: ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
5364: $file = 'userfiles/'.$file;
1.740 www 5365: $dir = &propath($udom,$uname);
1.712 albertel 5366: }
5367: if ($uri =~ m-^/res/-) {
5368: ($udom,$uname) =
5369: ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
5370: $file = $uri;
5371: }
5372:
5373: if (!$udom || !$uname || !$file) {
5374: # unable to handle the uri
5375: return ();
5376: }
5377:
5378: my ($result) = &dirlist($file,$udom,$uname,$dir);
5379: my @stats = split('&', $result);
1.721 banghart 5380:
1.712 albertel 5381: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
5382: shift(@stats); #filename is first
5383: return @stats;
5384: }
5385: return ();
5386: }
5387:
1.26 www 5388: # -------------------------------------------------------- Value of a Condition
5389:
1.713 albertel 5390: # gets the value of a specific preevaluated condition
5391: # stored in the string $env{user.state.<cid>}
5392: # or looks up a condition reference in the bighash and if if hasn't
5393: # already been evaluated recurses into docondval to get the value of
5394: # the condition, then memoizing it to
5395: # $env{user.state.<cid>.<condition>}
1.40 www 5396: sub directcondval {
5397: my $number=shift;
1.620 albertel 5398: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 5399: &Apache::lonuserstate::evalstate();
5400: }
1.713 albertel 5401: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
5402: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
5403: } elsif ($number =~ /^_/) {
5404: my $sub_condition;
5405: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5406: &GDBM_READER(),0640)) {
5407: $sub_condition=$bighash{'conditions'.$number};
5408: untie(%bighash);
5409: }
5410: my $value = &docondval($sub_condition);
5411: &appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
5412: return $value;
5413: }
1.620 albertel 5414: if ($env{'user.state.'.$env{'request.course.id'}}) {
5415: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 5416: } else {
5417: return 2;
5418: }
5419: }
5420:
1.713 albertel 5421: # get the collection of conditions for this resource
1.26 www 5422: sub condval {
5423: my $condidx=shift;
1.54 www 5424: my $allpathcond='';
1.713 albertel 5425: foreach my $cond (split(/\|/,$condidx)) {
5426: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
5427: $allpathcond.=
5428: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
5429: }
1.191 harris41 5430: }
1.54 www 5431: $allpathcond=~s/\|$//;
1.713 albertel 5432: return &docondval($allpathcond);
5433: }
5434:
5435: #evaluates an expression of conditions
5436: sub docondval {
5437: my ($allpathcond) = @_;
5438: my $result=0;
5439: if ($env{'request.course.id'}
5440: && defined($allpathcond)) {
5441: my $operand='|';
5442: my @stack;
5443: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
5444: if ($chunk eq '(') {
5445: push @stack,($operand,$result);
5446: } elsif ($chunk eq ')') {
5447: my $before=pop @stack;
5448: if (pop @stack eq '&') {
5449: $result=$result>$before?$before:$result;
5450: } else {
5451: $result=$result>$before?$result:$before;
5452: }
5453: } elsif (($chunk eq '&') || ($chunk eq '|')) {
5454: $operand=$chunk;
5455: } else {
5456: my $new=directcondval($chunk);
5457: if ($operand eq '&') {
5458: $result=$result>$new?$new:$result;
5459: } else {
5460: $result=$result>$new?$result:$new;
5461: }
5462: }
5463: }
1.26 www 5464: }
5465: return $result;
1.421 albertel 5466: }
5467:
5468: # ---------------------------------------------------- Devalidate courseresdata
5469:
5470: sub devalidatecourseresdata {
5471: my ($coursenum,$coursedomain)=@_;
5472: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 5473: &devalidate_cache_new('courseres',$hashid);
1.28 www 5474: }
5475:
1.763 www 5476:
1.200 www 5477: # --------------------------------------------------- Course Resourcedata Query
5478:
1.624 albertel 5479: sub get_courseresdata {
5480: my ($coursenum,$coursedomain)=@_;
1.200 www 5481: my $coursehom=&homeserver($coursenum,$coursedomain);
5482: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 5483: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 5484: my %dumpreply;
1.417 albertel 5485: unless (defined($cached)) {
1.624 albertel 5486: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 5487: $result=\%dumpreply;
1.251 albertel 5488: my ($tmp) = keys(%dumpreply);
5489: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 5490: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 5491: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
5492: return $tmp;
1.416 albertel 5493: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 5494: $result=undef;
1.599 albertel 5495: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 5496: }
5497: }
1.624 albertel 5498: return $result;
5499: }
5500:
1.633 albertel 5501: sub devalidateuserresdata {
5502: my ($uname,$udom)=@_;
5503: my $hashid="$udom:$uname";
5504: &devalidate_cache_new('userres',$hashid);
5505: }
5506:
1.624 albertel 5507: sub get_userresdata {
5508: my ($uname,$udom)=@_;
5509: #most student don\'t have any data set, check if there is some data
5510: if (&EXT_cache_status($udom,$uname)) { return undef; }
5511:
5512: my $hashid="$udom:$uname";
5513: my ($result,$cached)=&is_cached_new('userres',$hashid);
5514: if (!defined($cached)) {
5515: my %resourcedata=&dump('resourcedata',$udom,$uname);
5516: $result=\%resourcedata;
5517: &do_cache_new('userres',$hashid,$result,600);
5518: }
5519: my ($tmp)=keys(%$result);
5520: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
5521: return $result;
5522: }
5523: #error 2 occurs when the .db doesn't exist
5524: if ($tmp!~/error: 2 /) {
1.672 albertel 5525: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 5526: " Trying to get resource data for ".
5527: $uname." at ".$udom.": ".
5528: $tmp."</font>");
5529: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 5530: #&EXT_cache_set($udom,$uname);
5531: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 5532: undef($tmp); # not really an error so don't send it back
1.624 albertel 5533: }
5534: return $tmp;
5535: }
5536:
5537: sub resdata {
5538: my ($name,$domain,$type,@which)=@_;
5539: my $result;
5540: if ($type eq 'course') {
5541: $result=&get_courseresdata($name,$domain);
5542: } elsif ($type eq 'user') {
5543: $result=&get_userresdata($name,$domain);
5544: }
5545: if (!ref($result)) { return $result; }
1.251 albertel 5546: foreach my $item (@which) {
1.417 albertel 5547: if (defined($result->{$item})) {
5548: return $result->{$item};
1.251 albertel 5549: }
1.250 albertel 5550: }
1.291 albertel 5551: return undef;
1.200 www 5552: }
5553:
1.379 matthew 5554: #
5555: # EXT resource caching routines
5556: #
5557:
5558: sub clear_EXT_cache_status {
1.383 albertel 5559: &delenv('cache.EXT.');
1.379 matthew 5560: }
5561:
5562: sub EXT_cache_status {
5563: my ($target_domain,$target_user) = @_;
1.383 albertel 5564: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 5565: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 5566: # We know already the user has no data
5567: return 1;
5568: } else {
5569: return 0;
5570: }
5571: }
5572:
5573: sub EXT_cache_set {
5574: my ($target_domain,$target_user) = @_;
1.383 albertel 5575: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633 albertel 5576: #&appenv($cachename => time);
1.379 matthew 5577: }
5578:
1.28 www 5579: # --------------------------------------------------------- Value of a Variable
1.58 www 5580: sub EXT {
1.715 albertel 5581:
1.395 albertel 5582: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 5583: unless ($varname) { return ''; }
1.218 albertel 5584: #get real user name/domain, courseid and symb
5585: my $courseid;
1.359 albertel 5586: my $publicuser;
1.427 www 5587: if ($symbparm) {
5588: $symbparm=&get_symb_from_alias($symbparm);
5589: }
1.218 albertel 5590: if (!($uname && $udom)) {
1.790 albertel 5591: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 5592: if (!$symbparm) { $symbparm=$cursymb; }
5593: } else {
1.620 albertel 5594: $courseid=$env{'request.course.id'};
1.218 albertel 5595: }
1.48 www 5596: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
5597: my $rest;
1.320 albertel 5598: if (defined($therest[0])) {
1.48 www 5599: $rest=join('.',@therest);
5600: } else {
5601: $rest='';
5602: }
1.320 albertel 5603:
1.57 www 5604: my $qualifierrest=$qualifier;
5605: if ($rest) { $qualifierrest.='.'.$rest; }
5606: my $spacequalifierrest=$space;
5607: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 5608: if ($realm eq 'user') {
1.48 www 5609: # --------------------------------------------------------------- user.resource
5610: if ($space eq 'resource') {
1.651 albertel 5611: if ( (defined($Apache::lonhomework::parsing_a_problem)
5612: || defined($Apache::lonhomework::parsing_a_task))
5613: &&
1.744 albertel 5614: ($symbparm eq &symbread()) ) {
5615: # if we are in the middle of processing the resource the
5616: # get the value we are planning on committing
5617: if (defined($Apache::lonhomework::results{$qualifierrest})) {
5618: return $Apache::lonhomework::results{$qualifierrest};
5619: } else {
5620: return $Apache::lonhomework::history{$qualifierrest};
5621: }
1.335 albertel 5622: } else {
1.359 albertel 5623: my %restored;
1.620 albertel 5624: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 5625: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
5626: } else {
5627: %restored=&restore($symbparm,$courseid,$udom,$uname);
5628: }
1.335 albertel 5629: return $restored{$qualifierrest};
5630: }
1.48 www 5631: # ----------------------------------------------------------------- user.access
5632: } elsif ($space eq 'access') {
1.218 albertel 5633: # FIXME - not supporting calls for a specific user
1.48 www 5634: return &allowed($qualifier,$rest);
5635: # ------------------------------------------ user.preferences, user.environment
5636: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 5637: if (($uname eq $env{'user.name'}) &&
5638: ($udom eq $env{'user.domain'})) {
5639: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 5640: } else {
1.359 albertel 5641: my %returnhash;
5642: if (!$publicuser) {
5643: %returnhash=&userenvironment($udom,$uname,
5644: $qualifierrest);
5645: }
1.218 albertel 5646: return $returnhash{$qualifierrest};
5647: }
1.48 www 5648: # ----------------------------------------------------------------- user.course
5649: } elsif ($space eq 'course') {
1.218 albertel 5650: # FIXME - not supporting calls for a specific user
1.620 albertel 5651: return $env{join('.',('request.course',$qualifier))};
1.48 www 5652: # ------------------------------------------------------------------- user.role
5653: } elsif ($space eq 'role') {
1.218 albertel 5654: # FIXME - not supporting calls for a specific user
1.620 albertel 5655: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 5656: if ($qualifier eq 'value') {
5657: return $role;
5658: } elsif ($qualifier eq 'extent') {
5659: return $where;
5660: }
5661: # ----------------------------------------------------------------- user.domain
5662: } elsif ($space eq 'domain') {
1.218 albertel 5663: return $udom;
1.48 www 5664: # ------------------------------------------------------------------- user.name
5665: } elsif ($space eq 'name') {
1.218 albertel 5666: return $uname;
1.48 www 5667: # ---------------------------------------------------- Any other user namespace
1.29 www 5668: } else {
1.359 albertel 5669: my %reply;
5670: if (!$publicuser) {
5671: %reply=&get($space,[$qualifierrest],$udom,$uname);
5672: }
5673: return $reply{$qualifierrest};
1.48 www 5674: }
1.236 www 5675: } elsif ($realm eq 'query') {
5676: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 5677: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
5678: [$spacequalifierrest]);
1.620 albertel 5679: return $env{'form.'.$spacequalifierrest};
1.236 www 5680: } elsif ($realm eq 'request') {
1.48 www 5681: # ------------------------------------------------------------- request.browser
5682: if ($space eq 'browser') {
1.430 www 5683: if ($qualifier eq 'textremote') {
1.676 albertel 5684: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 5685: return 1;
5686: } else {
5687: return 0;
5688: }
5689: } else {
1.620 albertel 5690: return $env{'browser.'.$qualifier};
1.430 www 5691: }
1.57 www 5692: # ------------------------------------------------------------ request.filename
5693: } else {
1.620 albertel 5694: return $env{'request.'.$spacequalifierrest};
1.29 www 5695: }
1.28 www 5696: } elsif ($realm eq 'course') {
1.48 www 5697: # ---------------------------------------------------------- course.description
1.620 albertel 5698: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 5699: } elsif ($realm eq 'resource') {
1.165 www 5700:
1.620 albertel 5701: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 5702: if (!$symbparm) { $symbparm=&symbread(); }
5703: }
1.693 albertel 5704:
5705: if ($space eq 'title') {
5706: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
5707: return &gettitle($symbparm);
5708: }
5709:
5710: if ($space eq 'map') {
5711: my ($map) = &decode_symb($symbparm);
5712: return &symbread($map);
5713: }
5714:
5715: my ($section, $group, @groups);
1.593 albertel 5716: my ($courselevelm,$courselevel);
1.539 albertel 5717: if ($symbparm && defined($courseid) &&
1.620 albertel 5718: $courseid eq $env{'request.course.id'}) {
1.165 www 5719:
1.218 albertel 5720: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 5721:
1.60 www 5722: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 5723: my $symbp=$symbparm;
1.735 albertel 5724: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 5725:
5726: my $symbparm=$symbp.'.'.$spacequalifierrest;
5727: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
5728:
1.620 albertel 5729: if (($env{'user.name'} eq $uname) &&
5730: ($env{'user.domain'} eq $udom)) {
5731: $section=$env{'request.course.sec'};
1.733 raeburn 5732: @groups = split(/:/,$env{'request.course.groups'});
5733: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 5734: } else {
1.539 albertel 5735: if (! defined($usection)) {
1.551 albertel 5736: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 5737: } else {
5738: $section = $usection;
5739: }
1.733 raeburn 5740: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 5741: }
5742:
5743: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
5744: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
5745: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
5746:
1.593 albertel 5747: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 5748: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 5749: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 5750:
1.60 www 5751: # ----------------------------------------------------------- first, check user
1.624 albertel 5752:
5753: my $userreply=&resdata($uname,$udom,'user',
5754: ($courselevelr,$courselevelm,
5755: $courselevel));
5756: if (defined($userreply)) { return $userreply; }
1.95 www 5757:
1.594 albertel 5758: # ------------------------------------------------ second, check some of course
1.684 raeburn 5759: my $coursereply;
1.691 raeburn 5760: if (@groups > 0) {
5761: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
5762: $mapparm,$spacequalifierrest);
1.684 raeburn 5763: if (defined($coursereply)) { return $coursereply; }
5764: }
1.96 www 5765:
1.684 raeburn 5766: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624 albertel 5767: $env{'course.'.$courseid.'.domain'},
5768: 'course',
5769: ($seclevelr,$seclevelm,$seclevel,
5770: $courselevelr));
1.287 albertel 5771: if (defined($coursereply)) { return $coursereply; }
1.200 www 5772:
1.60 www 5773: # ------------------------------------------------------ third, check map parms
1.218 albertel 5774: my %parmhash=();
5775: my $thisparm='';
5776: if (tie(%parmhash,'GDBM_File',
1.620 albertel 5777: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 5778: &GDBM_READER(),0640)) {
1.218 albertel 5779: $thisparm=$parmhash{$symbparm};
5780: untie(%parmhash);
5781: }
5782: if ($thisparm) { return $thisparm; }
5783: }
1.594 albertel 5784: # ------------------------------------------ fourth, look in resource metadata
1.71 www 5785:
1.218 albertel 5786: $spacequalifierrest=~s/\./\_/;
1.282 albertel 5787: my $filename;
5788: if (!$symbparm) { $symbparm=&symbread(); }
5789: if ($symbparm) {
1.409 www 5790: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 5791: } else {
1.620 albertel 5792: $filename=$env{'request.filename'};
1.282 albertel 5793: }
5794: my $metadata=&metadata($filename,$spacequalifierrest);
1.288 albertel 5795: if (defined($metadata)) { return $metadata; }
1.282 albertel 5796: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288 albertel 5797: if (defined($metadata)) { return $metadata; }
1.142 www 5798:
1.594 albertel 5799: # ---------------------------------------------- fourth, look in rest pf course
1.593 albertel 5800: if ($symbparm && defined($courseid) &&
1.620 albertel 5801: $courseid eq $env{'request.course.id'}) {
1.624 albertel 5802: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
5803: $env{'course.'.$courseid.'.domain'},
5804: 'course',
5805: ($courselevelm,$courselevel));
1.593 albertel 5806: if (defined($coursereply)) { return $coursereply; }
5807: }
1.145 www 5808: # ------------------------------------------------------------------ Cascade up
1.218 albertel 5809: unless ($space eq '0') {
1.336 albertel 5810: my @parts=split(/_/,$space);
5811: my $id=pop(@parts);
5812: my $part=join('_',@parts);
5813: if ($part eq '') { $part='0'; }
5814: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 5815: $symbparm,$udom,$uname,$section,1);
1.337 albertel 5816: if (defined($partgeneral)) { return $partgeneral; }
1.218 albertel 5817: }
1.395 albertel 5818: if ($recurse) { return undef; }
5819: my $pack_def=&packages_tab_default($filename,$varname);
5820: if (defined($pack_def)) { return $pack_def; }
1.71 www 5821:
1.48 www 5822: # ---------------------------------------------------- Any other user namespace
5823: } elsif ($realm eq 'environment') {
5824: # ----------------------------------------------------------------- environment
1.620 albertel 5825: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
5826: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 5827: } else {
1.770 albertel 5828: if ($uname eq 'anonymous' && $udom eq '') {
5829: return '';
5830: }
1.219 albertel 5831: my %returnhash=&userenvironment($udom,$uname,
5832: $spacequalifierrest);
5833: return $returnhash{$spacequalifierrest};
5834: }
1.28 www 5835: } elsif ($realm eq 'system') {
1.48 www 5836: # ----------------------------------------------------------------- system.time
5837: if ($space eq 'time') {
5838: return time;
5839: }
1.696 albertel 5840: } elsif ($realm eq 'server') {
5841: # ----------------------------------------------------------------- system.time
5842: if ($space eq 'name') {
5843: return $ENV{'SERVER_NAME'};
5844: }
1.28 www 5845: }
1.48 www 5846: return '';
1.61 www 5847: }
5848:
1.691 raeburn 5849: sub check_group_parms {
5850: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
5851: my @groupitems = ();
5852: my $resultitem;
5853: my @levels = ($symbparm,$mapparm,$what);
5854: foreach my $group (@{$groups}) {
5855: foreach my $level (@levels) {
5856: my $item = $courseid.'.['.$group.'].'.$level;
5857: push(@groupitems,$item);
5858: }
5859: }
5860: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
5861: $env{'course.'.$courseid.'.domain'},
5862: 'course',@groupitems);
5863: return $coursereply;
5864: }
5865:
5866: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 5867: my ($courseid,@groups) = @_;
5868: @groups = sort(@groups);
1.691 raeburn 5869: return @groups;
5870: }
5871:
1.395 albertel 5872: sub packages_tab_default {
5873: my ($uri,$varname)=@_;
5874: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 5875:
5876: my (@extension,@specifics,$do_default);
5877: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 5878: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 5879: if ($pack_type eq 'default') {
5880: $do_default=1;
5881: } elsif ($pack_type eq 'extension') {
5882: push(@extension,[$package,$pack_type,$pack_part]);
5883: } else {
5884: push(@specifics,[$package,$pack_type,$pack_part]);
5885: }
5886: }
5887: # first look for a package that matches the requested part id
5888: foreach my $package (@specifics) {
5889: my (undef,$pack_type,$pack_part)=@{$package};
5890: next if ($pack_part ne $part);
5891: if (defined($packagetab{"$pack_type&$name&default"})) {
5892: return $packagetab{"$pack_type&$name&default"};
5893: }
5894: }
5895: # look for any possible matching non extension_ package
5896: foreach my $package (@specifics) {
5897: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 5898: if (defined($packagetab{"$pack_type&$name&default"})) {
5899: return $packagetab{"$pack_type&$name&default"};
5900: }
1.585 albertel 5901: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 5902: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
5903: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 5904: }
5905: }
1.738 albertel 5906: # look for any posible extension_ match
5907: foreach my $package (@extension) {
5908: my ($package,$pack_type)=@{$package};
5909: if (defined($packagetab{"$pack_type&$name&default"})) {
5910: return $packagetab{"$pack_type&$name&default"};
5911: }
5912: if (defined($packagetab{$package."&$name&default"})) {
5913: return $packagetab{$package."&$name&default"};
5914: }
5915: }
5916: # look for a global default setting
5917: if ($do_default && defined($packagetab{"default&$name&default"})) {
5918: return $packagetab{"default&$name&default"};
5919: }
1.395 albertel 5920: return undef;
5921: }
5922:
1.334 albertel 5923: sub add_prefix_and_part {
5924: my ($prefix,$part)=@_;
5925: my $keyroot;
5926: if (defined($prefix) && $prefix !~ /^__/) {
5927: # prefix that has a part already
5928: $keyroot=$prefix;
5929: } elsif (defined($prefix)) {
5930: # prefix that is missing a part
5931: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
5932: } else {
5933: # no prefix at all
5934: if (defined($part)) { $keyroot='_'.$part; }
5935: }
5936: return $keyroot;
5937: }
5938:
1.71 www 5939: # ---------------------------------------------------------------- Get metadata
5940:
1.599 albertel 5941: my %metaentry;
1.71 www 5942: sub metadata {
1.176 www 5943: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 5944: $uri=&declutter($uri);
1.288 albertel 5945: # if it is a non metadata possible uri return quickly
1.529 albertel 5946: if (($uri eq '') ||
5947: (($uri =~ m|^/*adm/|) &&
1.698 albertel 5948: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423 albertel 5949: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489 albertel 5950: ($uri =~ m|home/[^/]+/public_html/|)) {
1.468 albertel 5951: return undef;
1.288 albertel 5952: }
1.73 www 5953: my $filename=$uri;
5954: $uri=~s/\.meta$//;
1.172 www 5955: #
5956: # Is the metadata already cached?
1.177 www 5957: # Look at timestamp of caching
1.172 www 5958: # Everything is cached by the main uri, libraries are never directly cached
5959: #
1.428 albertel 5960: if (!defined($liburi)) {
1.599 albertel 5961: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 5962: if (defined($cached)) { return $result->{':'.$what}; }
5963: }
5964: {
1.172 www 5965: #
5966: # Is this a recursive call for a library?
5967: #
1.599 albertel 5968: # if (! exists($metacache{$uri})) {
5969: # $metacache{$uri}={};
5970: # }
1.171 www 5971: if ($liburi) {
5972: $liburi=&declutter($liburi);
5973: $filename=$liburi;
1.401 bowersj2 5974: } else {
1.599 albertel 5975: &devalidate_cache_new('meta',$uri);
5976: undef(%metaentry);
1.401 bowersj2 5977: }
1.140 www 5978: my %metathesekeys=();
1.73 www 5979: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 5980: my $metastring;
1.768 albertel 5981: if ($uri !~ m -^(editupload)/-) {
1.543 albertel 5982: my $file=&filelocation('',&clutter($filename));
1.599 albertel 5983: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 5984: $metastring=&getfile($file);
1.489 albertel 5985: }
1.208 albertel 5986: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 5987: my $token;
1.140 www 5988: undef %metathesekeys;
1.71 www 5989: while ($token=$parser->get_token) {
1.339 albertel 5990: if ($token->[0] eq 'S') {
5991: if (defined($token->[2]->{'package'})) {
1.172 www 5992: #
5993: # This is a package - get package info
5994: #
1.339 albertel 5995: my $package=$token->[2]->{'package'};
5996: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
5997: if (defined($token->[2]->{'id'})) {
5998: $keyroot.='_'.$token->[2]->{'id'};
5999: }
1.599 albertel 6000: if ($metaentry{':packages'}) {
6001: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 6002: } else {
1.599 albertel 6003: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 6004: }
1.736 albertel 6005: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 6006: my $part=$keyroot;
6007: $part=~s/^\_//;
1.736 albertel 6008: if ($pack_entry=~/^\Q$package\E\&/ ||
6009: $pack_entry=~/^\Q$package\E_0\&/) {
6010: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 6011: # ignore package.tab specified default values
6012: # here &package_tab_default() will fetch those
6013: if ($subp eq 'default') { next; }
1.736 albertel 6014: my $value=$packagetab{$pack_entry};
1.432 albertel 6015: my $unikey;
6016: if ($pack =~ /_0$/) {
6017: $unikey='parameter_0_'.$name;
6018: $part=0;
6019: } else {
6020: $unikey='parameter'.$keyroot.'_'.$name;
6021: }
1.339 albertel 6022: if ($subp eq 'display') {
6023: $value.=' [Part: '.$part.']';
6024: }
1.599 albertel 6025: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 6026: $metathesekeys{$unikey}=1;
1.599 albertel 6027: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6028: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 6029: }
1.599 albertel 6030: if (defined($metaentry{':'.$unikey.'.default'})) {
6031: $metaentry{':'.$unikey}=
6032: $metaentry{':'.$unikey.'.default'};
1.356 albertel 6033: }
1.339 albertel 6034: }
6035: }
6036: } else {
1.172 www 6037: #
6038: # This is not a package - some other kind of start tag
1.339 albertel 6039: #
6040: my $entry=$token->[1];
6041: my $unikey;
6042: if ($entry eq 'import') {
6043: $unikey='';
6044: } else {
6045: $unikey=$entry;
6046: }
6047: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6048:
6049: if (defined($token->[2]->{'id'})) {
6050: $unikey.='_'.$token->[2]->{'id'};
6051: }
1.175 www 6052:
1.339 albertel 6053: if ($entry eq 'import') {
1.175 www 6054: #
6055: # Importing a library here
1.339 albertel 6056: #
6057: if ($depthcount<20) {
6058: my $location=$parser->get_text('/import');
6059: my $dir=$filename;
6060: $dir=~s|[^/]*$||;
6061: $location=&filelocation($dir,$location);
1.736 albertel 6062: my $metadata =
6063: &metadata($uri,'keys', $location,$unikey,
6064: $depthcount+1);
6065: foreach my $meta (split(',',$metadata)) {
6066: $metaentry{':'.$meta}=$metaentry{':'.$meta};
6067: $metathesekeys{$meta}=1;
1.339 albertel 6068: }
6069: }
6070: } else {
6071:
6072: if (defined($token->[2]->{'name'})) {
6073: $unikey.='_'.$token->[2]->{'name'};
6074: }
6075: $metathesekeys{$unikey}=1;
1.736 albertel 6076: foreach my $param (@{$token->[3]}) {
6077: $metaentry{':'.$unikey.'.'.$param} =
6078: $token->[2]->{$param};
1.339 albertel 6079: }
6080: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 6081: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 6082: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
6083: # only ws inside the tag, and not in default, so use default
6084: # as value
1.599 albertel 6085: $metaentry{':'.$unikey}=$default;
1.339 albertel 6086: } else {
1.321 albertel 6087: # either something interesting inside the tag or default
6088: # uninteresting
1.599 albertel 6089: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 6090: }
1.172 www 6091: # end of not-a-package not-a-library import
1.339 albertel 6092: }
1.172 www 6093: # end of not-a-package start tag
1.339 albertel 6094: }
1.172 www 6095: # the next is the end of "start tag"
1.339 albertel 6096: }
6097: }
1.483 albertel 6098: my ($extension) = ($uri =~ /\.(\w+)$/);
1.737 albertel 6099: foreach my $key (keys(%packagetab)) {
1.483 albertel 6100: #no specific packages #how's our extension
6101: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 6102: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 6103: \%metathesekeys);
6104: }
1.599 albertel 6105: if (!exists($metaentry{':packages'})) {
1.737 albertel 6106: foreach my $key (keys(%packagetab)) {
1.483 albertel 6107: #no specific packages well let's get default then
6108: if ($key!~/^default&/) { next; }
1.488 albertel 6109: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 6110: \%metathesekeys);
6111: }
6112: }
1.338 www 6113: # are there custom rights to evaluate
1.599 albertel 6114: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 6115:
1.338 www 6116: #
6117: # Importing a rights file here
1.339 albertel 6118: #
6119: unless ($depthcount) {
1.599 albertel 6120: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 6121: my $dir=$filename;
6122: $dir=~s|[^/]*$||;
6123: $location=&filelocation($dir,$location);
1.736 albertel 6124: my $rights_metadata =
6125: &metadata($uri,'keys',$location,'_rights',
6126: $depthcount+1);
6127: foreach my $rights (split(',',$rights_metadata)) {
6128: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
6129: $metathesekeys{$rights}=1;
1.339 albertel 6130: }
6131: }
6132: }
1.737 albertel 6133: # uniqifiy package listing
6134: my %seen;
6135: my @uniq_packages =
6136: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
6137: $metaentry{':packages'} = join(',',@uniq_packages);
6138:
6139: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 6140: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
6141: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699 albertel 6142: &do_cache_new('meta',$uri,\%metaentry,60*60);
1.177 www 6143: # this is the end of "was not already recently cached
1.71 www 6144: }
1.599 albertel 6145: return $metaentry{':'.$what};
1.261 albertel 6146: }
6147:
1.488 albertel 6148: sub metadata_create_package_def {
1.483 albertel 6149: my ($uri,$key,$package,$metathesekeys)=@_;
6150: my ($pack,$name,$subp)=split(/\&/,$key);
6151: if ($subp eq 'default') { next; }
6152:
1.599 albertel 6153: if (defined($metaentry{':packages'})) {
6154: $metaentry{':packages'}.=','.$package;
1.483 albertel 6155: } else {
1.599 albertel 6156: $metaentry{':packages'}=$package;
1.483 albertel 6157: }
6158: my $value=$packagetab{$key};
6159: my $unikey;
6160: $unikey='parameter_0_'.$name;
1.599 albertel 6161: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 6162: $$metathesekeys{$unikey}=1;
1.599 albertel 6163: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6164: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 6165: }
1.599 albertel 6166: if (defined($metaentry{':'.$unikey.'.default'})) {
6167: $metaentry{':'.$unikey}=
6168: $metaentry{':'.$unikey.'.default'};
1.483 albertel 6169: }
6170: }
6171:
1.261 albertel 6172: sub metadata_generate_part0 {
6173: my ($metadata,$metacache,$uri) = @_;
6174: my %allnames;
1.737 albertel 6175: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 6176: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 6177: my $part=$$metacache{':'.$metakey.'.part'};
6178: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 6179: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 6180: $allnames{$name}=$part;
6181: }
6182: }
6183: }
6184: foreach my $name (keys(%allnames)) {
6185: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 6186: my $key=":parameter_0_$name";
1.261 albertel 6187: $$metacache{"$key.part"}='0';
6188: $$metacache{"$key.name"}=$name;
1.428 albertel 6189: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 6190: $allnames{$name}.'_'.$name.
6191: '.type'};
1.428 albertel 6192: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 6193: '.display'};
1.644 www 6194: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 6195: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 6196: $$metacache{"$key.display"}=$olddis;
6197: }
1.71 www 6198: }
6199:
1.764 albertel 6200: # ------------------------------------------------------ Devalidate title cache
6201:
6202: sub devalidate_title_cache {
6203: my ($url)=@_;
6204: if (!$env{'request.course.id'}) { return; }
6205: my $symb=&symbread($url);
6206: if (!$symb) { return; }
6207: my $key=$env{'request.course.id'}."\0".$symb;
6208: &devalidate_cache_new('title',$key);
6209: }
6210:
1.301 www 6211: # ------------------------------------------------- Get the title of a resource
6212:
6213: sub gettitle {
6214: my $urlsymb=shift;
6215: my $symb=&symbread($urlsymb);
1.534 albertel 6216: if ($symb) {
1.620 albertel 6217: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 6218: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 6219: if (defined($cached)) {
6220: return $result;
6221: }
1.534 albertel 6222: my ($map,$resid,$url)=&decode_symb($symb);
6223: my $title='';
6224: my %bighash;
1.620 albertel 6225: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534 albertel 6226: &GDBM_READER(),0640)) {
6227: my $mapid=$bighash{'map_pc_'.&clutter($map)};
6228: $title=$bighash{'title_'.$mapid.'.'.$resid};
6229: untie %bighash;
6230: }
6231: $title=~s/\&colon\;/\:/gs;
6232: if ($title) {
1.599 albertel 6233: return &do_cache_new('title',$key,$title,600);
1.534 albertel 6234: }
6235: $urlsymb=$url;
6236: }
6237: my $title=&metadata($urlsymb,'title');
6238: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
6239: return $title;
1.301 www 6240: }
1.613 albertel 6241:
1.614 albertel 6242: sub get_slot {
6243: my ($which,$cnum,$cdom)=@_;
6244: if (!$cnum || !$cdom) {
1.790 albertel 6245: (undef,my $courseid)=&whichuser();
1.620 albertel 6246: $cdom=$env{'course.'.$courseid.'.domain'};
6247: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 6248: }
1.703 albertel 6249: my $key=join("\0",'slots',$cdom,$cnum,$which);
6250: my %slotinfo;
6251: if (exists($remembered{$key})) {
6252: $slotinfo{$which} = $remembered{$key};
6253: } else {
6254: %slotinfo=&get('slots',[$which],$cdom,$cnum);
6255: &Apache::lonhomework::showhash(%slotinfo);
6256: my ($tmp)=keys(%slotinfo);
6257: if ($tmp=~/^error:/) { return (); }
6258: $remembered{$key} = $slotinfo{$which};
6259: }
1.616 albertel 6260: if (ref($slotinfo{$which}) eq 'HASH') {
6261: return %{$slotinfo{$which}};
6262: }
6263: return $slotinfo{$which};
1.614 albertel 6264: }
1.31 www 6265: # ------------------------------------------------- Update symbolic store links
6266:
6267: sub symblist {
6268: my ($mapname,%newhash)=@_;
1.438 www 6269: $mapname=&deversion(&declutter($mapname));
1.31 www 6270: my %hash;
1.620 albertel 6271: if (($env{'request.course.fn'}) && (%newhash)) {
6272: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 6273: &GDBM_WRCREAT(),0640)) {
1.711 albertel 6274: foreach my $url (keys %newhash) {
6275: next if ($url eq 'last_known'
6276: && $env{'form.no_update_last_known'});
6277: $hash{declutter($url)}=&encode_symb($mapname,
6278: $newhash{$url}->[1],
6279: $newhash{$url}->[0]);
1.191 harris41 6280: }
1.31 www 6281: if (untie(%hash)) {
6282: return 'ok';
6283: }
6284: }
6285: }
6286: return 'error';
1.212 www 6287: }
6288:
6289: # --------------------------------------------------------------- Verify a symb
6290:
6291: sub symbverify {
1.510 www 6292: my ($symb,$thisurl)=@_;
6293: my $thisfn=$thisurl;
1.439 www 6294: $thisfn=&declutter($thisfn);
1.215 www 6295: # direct jump to resource in page or to a sequence - will construct own symbs
6296: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
6297: # check URL part
1.409 www 6298: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 6299:
1.431 www 6300: unless ($url eq $thisfn) { return 0; }
1.213 www 6301:
1.216 www 6302: $symb=&symbclean($symb);
1.510 www 6303: $thisurl=&deversion($thisurl);
1.439 www 6304: $thisfn=&deversion($thisfn);
1.213 www 6305:
6306: my %bighash;
6307: my $okay=0;
1.431 www 6308:
1.620 albertel 6309: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 6310: &GDBM_READER(),0640)) {
1.510 www 6311: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 6312: unless ($ids) {
1.510 www 6313: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 6314: }
6315: if ($ids) {
6316: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 6317: foreach my $id (split(/\,/,$ids)) {
6318: my ($mapid,$resid)=split(/\./,$id);
1.216 www 6319: if (
6320: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
6321: eq $symb) {
1.620 albertel 6322: if (($env{'request.role.adv'}) ||
1.800 albertel 6323: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 6324: $okay=1;
6325: }
6326: }
1.216 www 6327: }
6328: }
1.213 www 6329: untie(%bighash);
6330: }
6331: return $okay;
1.31 www 6332: }
6333:
1.210 www 6334: # --------------------------------------------------------------- Clean-up symb
6335:
6336: sub symbclean {
6337: my $symb=shift;
1.568 albertel 6338: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 6339: # remove version from map
6340: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 6341:
1.210 www 6342: # remove version from URL
6343: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 6344:
1.507 www 6345: # remove wrapper
6346:
1.510 www 6347: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 6348: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 6349: return $symb;
1.409 www 6350: }
6351:
6352: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 6353:
6354: sub encode_symb {
6355: my ($map,$resid,$url)=@_;
6356: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
6357: }
1.409 www 6358:
6359: sub decode_symb {
1.568 albertel 6360: my $symb=shift;
6361: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
6362: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 6363: return (&fixversion($map),$resid,&fixversion($url));
6364: }
6365:
6366: sub fixversion {
6367: my $fn=shift;
1.609 banghart 6368: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 6369: my %bighash;
6370: my $uri=&clutter($fn);
1.620 albertel 6371: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 6372: # is this cached?
1.599 albertel 6373: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 6374: if (defined($cached)) { return $result; }
6375: # unfortunately not cached, or expired
1.620 albertel 6376: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 6377: &GDBM_READER(),0640)) {
6378: if ($bighash{'version_'.$uri}) {
6379: my $version=$bighash{'version_'.$uri};
1.444 www 6380: unless (($version eq 'mostrecent') ||
6381: ($version==&getversion($uri))) {
1.440 www 6382: $uri=~s/\.(\w+)$/\.$version\.$1/;
6383: }
6384: }
6385: untie %bighash;
1.413 www 6386: }
1.599 albertel 6387: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 6388: }
6389:
6390: sub deversion {
6391: my $url=shift;
6392: $url=~s/\.\d+\.(\w+)$/\.$1/;
6393: return $url;
1.210 www 6394: }
6395:
1.31 www 6396: # ------------------------------------------------------ Return symb list entry
6397:
6398: sub symbread {
1.249 www 6399: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 6400: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 6401: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 6402: # no filename provided? try from environment
1.44 www 6403: unless ($thisfn) {
1.620 albertel 6404: if ($env{'request.symb'}) {
6405: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 6406: }
1.620 albertel 6407: $thisfn=$env{'request.filename'};
1.44 www 6408: }
1.569 albertel 6409: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 6410: # is that filename actually a symb? Verify, clean, and return
6411: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 6412: if (&symbverify($thisfn,$1)) {
1.620 albertel 6413: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 6414: }
1.242 www 6415: }
1.44 www 6416: $thisfn=declutter($thisfn);
1.31 www 6417: my %hash;
1.37 www 6418: my %bighash;
6419: my $syval='';
1.620 albertel 6420: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 6421: my $targetfn = $thisfn;
1.609 banghart 6422: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 6423: $targetfn = 'adm/wrapper/'.$thisfn;
6424: }
1.687 albertel 6425: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
6426: $targetfn=$1;
6427: }
1.620 albertel 6428: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 6429: &GDBM_READER(),0640)) {
1.481 raeburn 6430: $syval=$hash{$targetfn};
1.37 www 6431: untie(%hash);
6432: }
6433: # ---------------------------------------------------------- There was an entry
6434: if ($syval) {
1.601 albertel 6435: #unless ($syval=~/\_\d+$/) {
1.620 albertel 6436: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601 albertel 6437: #&appenv('request.ambiguous' => $thisfn);
1.620 albertel 6438: #return $env{$cache_str}='';
1.601 albertel 6439: #}
6440: #$syval.=$1;
6441: #}
1.37 www 6442: } else {
6443: # ------------------------------------------------------- Was not in symb table
1.620 albertel 6444: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 6445: &GDBM_READER(),0640)) {
1.37 www 6446: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 6447: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 6448: unless ($ids) {
6449: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 6450: }
6451: unless ($ids) {
6452: # alias?
6453: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 6454: }
1.37 www 6455: if ($ids) {
6456: # ------------------------------------------------------------------- Has ID(s)
6457: my @possibilities=split(/\,/,$ids);
1.39 www 6458: if ($#possibilities==0) {
6459: # ----------------------------------------------- There is only one possibility
1.37 www 6460: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 6461: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6462: $resid,$thisfn);
1.249 www 6463: } elsif (!$donotrecurse) {
1.39 www 6464: # ------------------------------------------ There is more than one possibility
6465: my $realpossible=0;
1.800 albertel 6466: foreach my $id (@possibilities) {
6467: my $file=$bighash{'src_'.$id};
1.39 www 6468: if (&allowed('bre',$file)) {
1.800 albertel 6469: my ($mapid,$resid)=split(/\./,$id);
1.39 www 6470: if ($bighash{'map_type_'.$mapid} ne 'page') {
6471: $realpossible++;
1.626 albertel 6472: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6473: $resid,$thisfn);
1.39 www 6474: }
6475: }
1.191 harris41 6476: }
1.39 www 6477: if ($realpossible!=1) { $syval=''; }
1.249 www 6478: } else {
6479: $syval='';
1.37 www 6480: }
6481: }
6482: untie(%bighash)
1.481 raeburn 6483: }
1.31 www 6484: }
1.62 www 6485: if ($syval) {
1.620 albertel 6486: return $env{$cache_str}=$syval;
1.62 www 6487: }
1.31 www 6488: }
1.44 www 6489: &appenv('request.ambiguous' => $thisfn);
1.620 albertel 6490: return $env{$cache_str}='';
1.31 www 6491: }
6492:
6493: # ---------------------------------------------------------- Return random seed
6494:
1.32 www 6495: sub numval {
6496: my $txt=shift;
6497: $txt=~tr/A-J/0-9/;
6498: $txt=~tr/a-j/0-9/;
6499: $txt=~tr/K-T/0-9/;
6500: $txt=~tr/k-t/0-9/;
6501: $txt=~tr/U-Z/0-5/;
6502: $txt=~tr/u-z/0-5/;
6503: $txt=~s/\D//g;
1.564 albertel 6504: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 6505: return int($txt);
1.368 albertel 6506: }
6507:
1.484 albertel 6508: sub numval2 {
6509: my $txt=shift;
6510: $txt=~tr/A-J/0-9/;
6511: $txt=~tr/a-j/0-9/;
6512: $txt=~tr/K-T/0-9/;
6513: $txt=~tr/k-t/0-9/;
6514: $txt=~tr/U-Z/0-5/;
6515: $txt=~tr/u-z/0-5/;
6516: $txt=~s/\D//g;
6517: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6518: my $total;
6519: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 6520: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 6521: return int($total);
6522: }
6523:
1.575 albertel 6524: sub numval3 {
6525: use integer;
6526: my $txt=shift;
6527: $txt=~tr/A-J/0-9/;
6528: $txt=~tr/a-j/0-9/;
6529: $txt=~tr/K-T/0-9/;
6530: $txt=~tr/k-t/0-9/;
6531: $txt=~tr/U-Z/0-5/;
6532: $txt=~tr/u-z/0-5/;
6533: $txt=~s/\D//g;
6534: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6535: my $total;
6536: foreach my $val (@txts) { $total+=$val; }
6537: if ($_64bit) { $total=(($total<<32)>>32); }
6538: return $total;
6539: }
6540:
1.675 albertel 6541: sub digest {
6542: my ($data)=@_;
6543: my $digest=&Digest::MD5::md5($data);
6544: my ($a,$b,$c,$d)=unpack("iiii",$digest);
6545: my ($e,$f);
6546: {
6547: use integer;
6548: $e=($a+$b);
6549: $f=($c+$d);
6550: if ($_64bit) {
6551: $e=(($e<<32)>>32);
6552: $f=(($f<<32)>>32);
6553: }
6554: }
6555: if (wantarray) {
6556: return ($e,$f);
6557: } else {
6558: my $g;
6559: {
6560: use integer;
6561: $g=($e+$f);
6562: if ($_64bit) {
6563: $g=(($g<<32)>>32);
6564: }
6565: }
6566: return $g;
6567: }
6568: }
6569:
1.368 albertel 6570: sub latest_rnd_algorithm_id {
1.675 albertel 6571: return '64bit5';
1.366 albertel 6572: }
1.32 www 6573:
1.503 albertel 6574: sub get_rand_alg {
6575: my ($courseid)=@_;
1.790 albertel 6576: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 6577: if ($courseid) {
1.620 albertel 6578: return $env{"course.$courseid.rndseed"};
1.503 albertel 6579: }
6580: return &latest_rnd_algorithm_id();
6581: }
6582:
1.562 albertel 6583: sub validCODE {
6584: my ($CODE)=@_;
6585: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
6586: return 0;
6587: }
6588:
1.491 albertel 6589: sub getCODE {
1.620 albertel 6590: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 6591: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
6592: defined($Apache::lonhomework::parsing_a_task) ) &&
6593: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 6594: return $Apache::lonhomework::history{'resource.CODE'};
6595: }
6596: return undef;
6597: }
6598:
1.31 www 6599: sub rndseed {
1.155 albertel 6600: my ($symb,$courseid,$domain,$username)=@_;
1.366 albertel 6601:
1.790 albertel 6602: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155 albertel 6603: if (!$symb) {
1.366 albertel 6604: unless ($symb=$wsymb) { return time; }
6605: }
6606: if (!$courseid) { $courseid=$wcourseid; }
6607: if (!$domain) { $domain=$wdomain; }
6608: if (!$username) { $username=$wusername }
1.503 albertel 6609: my $which=&get_rand_alg();
1.803 albertel 6610:
1.491 albertel 6611: if (defined(&getCODE())) {
1.675 albertel 6612: if ($which eq '64bit5') {
6613: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
6614: } elsif ($which eq '64bit4') {
1.575 albertel 6615: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
6616: } else {
6617: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
6618: }
1.675 albertel 6619: } elsif ($which eq '64bit5') {
6620: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 6621: } elsif ($which eq '64bit4') {
6622: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 6623: } elsif ($which eq '64bit3') {
6624: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 6625: } elsif ($which eq '64bit2') {
6626: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 6627: } elsif ($which eq '64bit') {
6628: return &rndseed_64bit($symb,$courseid,$domain,$username);
6629: }
6630: return &rndseed_32bit($symb,$courseid,$domain,$username);
6631: }
6632:
6633: sub rndseed_32bit {
6634: my ($symb,$courseid,$domain,$username)=@_;
6635: {
6636: use integer;
6637: my $symbchck=unpack("%32C*",$symb) << 27;
6638: my $symbseed=numval($symb) << 22;
6639: my $namechck=unpack("%32C*",$username) << 17;
6640: my $nameseed=numval($username) << 12;
6641: my $domainseed=unpack("%32C*",$domain) << 7;
6642: my $courseseed=unpack("%32C*",$courseid);
6643: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 6644: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6645: #&logthis("rndseed :$num:$symb");
1.564 albertel 6646: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 6647: return $num;
6648: }
6649: }
6650:
6651: sub rndseed_64bit {
6652: my ($symb,$courseid,$domain,$username)=@_;
6653: {
6654: use integer;
6655: my $symbchck=unpack("%32S*",$symb) << 21;
6656: my $symbseed=numval($symb) << 10;
6657: my $namechck=unpack("%32S*",$username);
6658:
6659: my $nameseed=numval($username) << 21;
6660: my $domainseed=unpack("%32S*",$domain) << 10;
6661: my $courseseed=unpack("%32S*",$courseid);
6662:
6663: my $num1=$symbchck+$symbseed+$namechck;
6664: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 6665: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6666: #&logthis("rndseed :$num:$symb");
1.564 albertel 6667: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 6668: return "$num1,$num2";
1.155 albertel 6669: }
1.366 albertel 6670: }
6671:
1.443 albertel 6672: sub rndseed_64bit2 {
6673: my ($symb,$courseid,$domain,$username)=@_;
6674: {
6675: use integer;
6676: # strings need to be an even # of cahracters long, it it is odd the
6677: # last characters gets thrown away
6678: my $symbchck=unpack("%32S*",$symb.' ') << 21;
6679: my $symbseed=numval($symb) << 10;
6680: my $namechck=unpack("%32S*",$username.' ');
6681:
6682: my $nameseed=numval($username) << 21;
1.501 albertel 6683: my $domainseed=unpack("%32S*",$domain.' ') << 10;
6684: my $courseseed=unpack("%32S*",$courseid.' ');
6685:
6686: my $num1=$symbchck+$symbseed+$namechck;
6687: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 6688: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6689: #&logthis("rndseed :$num:$symb");
1.803 albertel 6690: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 6691: return "$num1,$num2";
6692: }
6693: }
6694:
6695: sub rndseed_64bit3 {
6696: my ($symb,$courseid,$domain,$username)=@_;
6697: {
6698: use integer;
6699: # strings need to be an even # of cahracters long, it it is odd the
6700: # last characters gets thrown away
6701: my $symbchck=unpack("%32S*",$symb.' ') << 21;
6702: my $symbseed=numval2($symb) << 10;
6703: my $namechck=unpack("%32S*",$username.' ');
6704:
6705: my $nameseed=numval2($username) << 21;
1.443 albertel 6706: my $domainseed=unpack("%32S*",$domain.' ') << 10;
6707: my $courseseed=unpack("%32S*",$courseid.' ');
6708:
6709: my $num1=$symbchck+$symbseed+$namechck;
6710: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 6711: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6712: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 6713: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
6714:
1.503 albertel 6715: return "$num1:$num2";
1.443 albertel 6716: }
6717: }
6718:
1.575 albertel 6719: sub rndseed_64bit4 {
6720: my ($symb,$courseid,$domain,$username)=@_;
6721: {
6722: use integer;
6723: # strings need to be an even # of cahracters long, it it is odd the
6724: # last characters gets thrown away
6725: my $symbchck=unpack("%32S*",$symb.' ') << 21;
6726: my $symbseed=numval3($symb) << 10;
6727: my $namechck=unpack("%32S*",$username.' ');
6728:
6729: my $nameseed=numval3($username) << 21;
6730: my $domainseed=unpack("%32S*",$domain.' ') << 10;
6731: my $courseseed=unpack("%32S*",$courseid.' ');
6732:
6733: my $num1=$symbchck+$symbseed+$namechck;
6734: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 6735: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6736: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 6737: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
6738:
6739: return "$num1:$num2";
6740: }
6741: }
6742:
1.675 albertel 6743: sub rndseed_64bit5 {
6744: my ($symb,$courseid,$domain,$username)=@_;
6745: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
6746: return "$num1:$num2";
6747: }
6748:
1.366 albertel 6749: sub rndseed_CODE_64bit {
6750: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 6751: {
1.366 albertel 6752: use integer;
1.443 albertel 6753: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 6754: my $symbseed=numval2($symb);
1.491 albertel 6755: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
6756: my $CODEseed=numval(&getCODE());
1.443 albertel 6757: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 6758: my $num1=$symbseed+$CODEchck;
6759: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 6760: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
6761: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 6762: if ($_64bit) { $num1=(($num1<<32)>>32); }
6763: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 6764: return "$num1:$num2";
1.366 albertel 6765: }
6766: }
6767:
1.575 albertel 6768: sub rndseed_CODE_64bit4 {
6769: my ($symb,$courseid,$domain,$username)=@_;
6770: {
6771: use integer;
6772: my $symbchck=unpack("%32S*",$symb.' ') << 16;
6773: my $symbseed=numval3($symb);
6774: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
6775: my $CODEseed=numval3(&getCODE());
6776: my $courseseed=unpack("%32S*",$courseid.' ');
6777: my $num1=$symbseed+$CODEchck;
6778: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 6779: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
6780: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 6781: if ($_64bit) { $num1=(($num1<<32)>>32); }
6782: if ($_64bit) { $num2=(($num2<<32)>>32); }
6783: return "$num1:$num2";
6784: }
6785: }
6786:
1.675 albertel 6787: sub rndseed_CODE_64bit5 {
6788: my ($symb,$courseid,$domain,$username)=@_;
6789: my $code = &getCODE();
6790: my ($num1,$num2)=&digest("$symb,$courseid,$code");
6791: return "$num1:$num2";
6792: }
6793:
1.366 albertel 6794: sub setup_random_from_rndseed {
6795: my ($rndseed)=@_;
1.503 albertel 6796: if ($rndseed =~/([,:])/) {
6797: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 6798: &Math::Random::random_set_seed(abs($num1),abs($num2));
6799: } else {
6800: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 6801: }
1.36 albertel 6802: }
6803:
1.474 albertel 6804: sub latest_receipt_algorithm_id {
6805: return 'receipt2';
6806: }
6807:
1.480 www 6808: sub recunique {
6809: my $fucourseid=shift;
6810: my $unique;
1.620 albertel 6811: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
6812: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 6813: } else {
6814: $unique=$perlvar{'lonReceipt'};
6815: }
6816: return unpack("%32C*",$unique);
6817: }
6818:
6819: sub recprefix {
6820: my $fucourseid=shift;
6821: my $prefix;
1.620 albertel 6822: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
6823: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 6824: } else {
6825: $prefix=$perlvar{'lonHostID'};
6826: }
6827: return unpack("%32C*",$prefix);
6828: }
6829:
1.76 www 6830: sub ireceipt {
1.474 albertel 6831: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76 www 6832: my $cuname=unpack("%32C*",$funame);
6833: my $cudom=unpack("%32C*",$fudom);
6834: my $cucourseid=unpack("%32C*",$fucourseid);
6835: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 6836: my $cunique=&recunique($fucourseid);
1.474 albertel 6837: my $cpart=unpack("%32S*",$part);
1.480 www 6838: my $return =&recprefix($fucourseid).'-';
1.620 albertel 6839: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
6840: $env{'request.state'} eq 'construct') {
1.790 albertel 6841: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 6842:
6843: $return.= ($cunique%$cuname+
6844: $cunique%$cudom+
6845: $cusymb%$cuname+
6846: $cusymb%$cudom+
6847: $cucourseid%$cuname+
6848: $cucourseid%$cudom+
6849: $cpart%$cuname+
6850: $cpart%$cudom);
6851: } else {
6852: $return.= ($cunique%$cuname+
6853: $cunique%$cudom+
6854: $cusymb%$cuname+
6855: $cusymb%$cudom+
6856: $cucourseid%$cuname+
6857: $cucourseid%$cudom);
6858: }
6859: return $return;
1.76 www 6860: }
6861:
6862: sub receipt {
1.474 albertel 6863: my ($part)=@_;
1.790 albertel 6864: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 6865: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 6866: }
1.260 ng 6867:
1.790 albertel 6868: sub whichuser {
6869: my ($passedsymb)=@_;
6870: my ($symb,$courseid,$domain,$name,$publicuser);
6871: if (defined($env{'form.grade_symb'})) {
6872: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
6873: my $allowed=&allowed('vgr',$tmp_courseid);
6874: if (!$allowed &&
6875: exists($env{'request.course.sec'}) &&
6876: $env{'request.course.sec'} !~ /^\s*$/) {
6877: $allowed=&allowed('vgr',$tmp_courseid.
6878: '/'.$env{'request.course.sec'});
6879: }
6880: if ($allowed) {
6881: ($symb)=&get_env_multiple('form.grade_symb');
6882: $courseid=$tmp_courseid;
6883: ($domain)=&get_env_multiple('form.grade_domain');
6884: ($name)=&get_env_multiple('form.grade_username');
6885: return ($symb,$courseid,$domain,$name,$publicuser);
6886: }
6887: }
6888: if (!$passedsymb) {
6889: $symb=&symbread();
6890: } else {
6891: $symb=$passedsymb;
6892: }
6893: $courseid=$env{'request.course.id'};
6894: $domain=$env{'user.domain'};
6895: $name=$env{'user.name'};
6896: if ($name eq 'public' && $domain eq 'public') {
6897: if (!defined($env{'form.username'})) {
6898: $env{'form.username'}.=time.rand(10000000);
6899: }
6900: $name.=$env{'form.username'};
6901: }
6902: return ($symb,$courseid,$domain,$name,$publicuser);
6903:
6904: }
6905:
1.36 albertel 6906: # ------------------------------------------------------------ Serves up a file
1.472 albertel 6907: # returns either the contents of the file or
6908: # -1 if the file doesn't exist
1.481 raeburn 6909: #
6910: # if the target is a file that was uploaded via DOCS,
6911: # a check will be made to see if a current copy exists on the local server,
6912: # if it does this will be served, otherwise a copy will be retrieved from
6913: # the home server for the course and stored in /home/httpd/html/userfiles on
6914: # the local server.
1.472 albertel 6915:
1.36 albertel 6916: sub getfile {
1.538 albertel 6917: my ($file) = @_;
1.609 banghart 6918: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 6919: &repcopy($file);
6920: return &readfile($file);
6921: }
6922:
6923: sub repcopy_userfile {
6924: my ($file)=@_;
1.609 banghart 6925: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 6926: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 6927: my ($cdom,$cnum,$filename) =
6928: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
6929: my ($info,$rtncode);
6930: my $uri="/uploaded/$cdom/$cnum/$filename";
6931: if (-e "$file") {
6932: my @fileinfo = stat($file);
6933: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 6934: if ($lwpresp ne 'ok') {
6935: if ($rtncode eq '404') {
1.538 albertel 6936: unlink($file);
1.482 albertel 6937: }
1.517 albertel 6938: #my $ua=new LWP::UserAgent;
1.538 albertel 6939: #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517 albertel 6940: #my $response=$ua->request($request);
6941: #if ($response->is_success()) {
6942: # return $response->content;
6943: # } else {
6944: # return -1;
6945: # }
1.482 albertel 6946: return -1;
6947: }
6948: if ($info < $fileinfo[9]) {
1.607 raeburn 6949: return 'ok';
1.482 albertel 6950: }
6951: $info = '';
1.538 albertel 6952: $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 6953: if ($lwpresp ne 'ok') {
6954: return -1;
6955: }
6956: } else {
1.538 albertel 6957: my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 6958: if ($lwpresp ne 'ok') {
1.517 albertel 6959: my $ua=new LWP::UserAgent;
1.538 albertel 6960: my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517 albertel 6961: my $response=$ua->request($request);
6962: if ($response->is_success()) {
1.538 albertel 6963: $info=$response->content;
1.517 albertel 6964: } else {
6965: return -1;
6966: }
1.482 albertel 6967: }
6968: my @parts = ($cdom,$cnum);
6969: if ($filename =~ m|^(.+)/[^/]+$|) {
6970: push @parts, split(/\//,$1);
1.518 albertel 6971: }
1.538 albertel 6972: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482 albertel 6973: foreach my $part (@parts) {
6974: $path .= '/'.$part;
6975: if (!-e $path) {
6976: mkdir($path,0770);
6977: }
6978: }
6979: }
1.538 albertel 6980: open(FILE,">$file");
1.482 albertel 6981: print FILE $info;
6982: close(FILE);
1.607 raeburn 6983: return 'ok';
1.481 raeburn 6984: }
6985:
1.517 albertel 6986: sub tokenwrapper {
6987: my $uri=shift;
1.552 albertel 6988: $uri=~s|^http\://([^/]+)||;
6989: $uri=~s|^/||;
1.620 albertel 6990: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 6991: my $token=$1;
1.552 albertel 6992: my (undef,$udom,$uname,$file)=split('/',$uri,4);
6993: if ($udom && $uname && $file) {
6994: $file=~s|(\?\.*)*$||;
1.620 albertel 6995: &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552 albertel 6996: return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517 albertel 6997: (($uri=~/\?/)?'&':'?').'token='.$token.
6998: '&tokenissued='.$perlvar{'lonHostID'};
6999: } else {
7000: return '/adm/notfound.html';
7001: }
7002: }
7003:
1.481 raeburn 7004: sub getuploaded {
7005: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
7006: $uri=~s/^\///;
7007: $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
7008: my $ua=new LWP::UserAgent;
7009: my $request=new HTTP::Request($reqtype,$uri);
7010: my $response=$ua->request($request);
7011: $$rtncode = $response->code;
1.482 albertel 7012: if (! $response->is_success()) {
7013: return 'failed';
7014: }
7015: if ($reqtype eq 'HEAD') {
1.486 www 7016: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 7017: } elsif ($reqtype eq 'GET') {
7018: $$info = $response->content;
1.472 albertel 7019: }
1.482 albertel 7020: return 'ok';
1.36 albertel 7021: }
7022:
1.481 raeburn 7023: sub readfile {
7024: my $file = shift;
7025: if ( (! -e $file ) || ($file eq '') ) { return -1; };
7026: my $fh;
7027: open($fh,"<$file");
7028: my $a='';
1.800 albertel 7029: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 7030: return $a;
7031: }
7032:
1.36 albertel 7033: sub filelocation {
1.590 banghart 7034: my ($dir,$file) = @_;
7035: my $location;
7036: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 7037:
7038: if ($file =~ m-^/adm/-) {
7039: $file=~s-^/adm/wrapper/-/-;
7040: $file=~s-^/adm/coursedocs/showdoc/-/-;
7041: }
1.590 banghart 7042: if ($file=~m:^/~:) { # is a contruction space reference
7043: $location = $file;
7044: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649 albertel 7045: } elsif ($file=~m:^/home/[^/]*/public_html/:) {
7046: # is a correct contruction space reference
7047: $location = $file;
1.609 banghart 7048: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 7049: my ($udom,$uname,$filename)=
1.609 banghart 7050: ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590 banghart 7051: my $home=&homeserver($uname,$udom);
7052: my $is_me=0;
7053: my @ids=¤t_machine_ids();
7054: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
7055: if ($is_me) {
1.740 www 7056: $location=&propath($udom,$uname).
1.590 banghart 7057: '/userfiles/'.$filename;
7058: } else {
7059: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
7060: $udom.'/'.$uname.'/'.$filename;
7061: }
7062: } else {
7063: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
7064: $file=~s:^/res/:/:;
7065: if ( !( $file =~ m:^/:) ) {
7066: $location = $dir. '/'.$file;
7067: } else {
7068: $location = '/home/httpd/html/res'.$file;
7069: }
1.59 albertel 7070: }
1.590 banghart 7071: $location=~s://+:/:g; # remove duplicate /
7072: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
7073: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
7074: return $location;
1.46 www 7075: }
1.36 albertel 7076:
1.46 www 7077: sub hreflocation {
7078: my ($dir,$file)=@_;
1.460 albertel 7079: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666 albertel 7080: $file=filelocation($dir,$file);
1.700 albertel 7081: } elsif ($file=~m-^/adm/-) {
7082: $file=~s-^/adm/wrapper/-/-;
7083: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 7084: }
7085: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
7086: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
7087: } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462 albertel 7088: $file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666 albertel 7089: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
7090: $file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
7091: -/uploaded/$1/$2/-x;
1.46 www 7092: }
1.462 albertel 7093: return $file;
1.465 albertel 7094: }
7095:
7096: sub current_machine_domains {
7097: my $hostname=$hostname{$perlvar{'lonHostID'}};
7098: my @domains;
7099: while( my($id, $name) = each(%hostname)) {
1.467 matthew 7100: # &logthis("-$id-$name-$hostname-");
1.465 albertel 7101: if ($hostname eq $name) {
7102: push(@domains,$hostdom{$id});
7103: }
7104: }
7105: return @domains;
7106: }
7107:
7108: sub current_machine_ids {
7109: my $hostname=$hostname{$perlvar{'lonHostID'}};
7110: my @ids;
7111: while( my($id, $name) = each(%hostname)) {
1.467 matthew 7112: # &logthis("-$id-$name-$hostname-");
1.465 albertel 7113: if ($hostname eq $name) {
7114: push(@ids,$id);
7115: }
7116: }
7117: return @ids;
1.31 www 7118: }
7119:
7120: # ------------------------------------------------------------- Declutters URLs
7121:
7122: sub declutter {
7123: my $thisfn=shift;
1.569 albertel 7124: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 7125: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 7126: $thisfn=~s/^\///;
1.697 albertel 7127: $thisfn=~s|^adm/wrapper/||;
7128: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 7129: $thisfn=~s/^res\///;
1.235 www 7130: $thisfn=~s/\?.+$//;
1.268 www 7131: return $thisfn;
7132: }
7133:
7134: # ------------------------------------------------------------- Clutter up URLs
7135:
7136: sub clutter {
7137: my $thisfn='/'.&declutter(shift);
1.609 banghart 7138: unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) {
1.270 www 7139: $thisfn='/res'.$thisfn;
7140: }
1.694 albertel 7141: if ($thisfn !~m|/adm|) {
1.695 albertel 7142: if ($thisfn =~ m|/ext/|) {
1.694 albertel 7143: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 7144: } else {
7145: my ($ext) = ($thisfn =~ /\.(\w+)$/);
7146: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 7147: if ($embstyle eq 'ssi'
7148: || ($embstyle eq 'hdn')
7149: || ($embstyle eq 'rat')
7150: || ($embstyle eq 'prv')
7151: || ($embstyle eq 'ign')) {
7152: #do nothing with these
7153: } elsif (($embstyle eq 'img')
1.695 albertel 7154: || ($embstyle eq 'emb')
7155: || ($embstyle eq 'wrp')) {
7156: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 7157: } elsif ($embstyle eq 'unk'
7158: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 7159: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 7160: } else {
1.718 www 7161: # &logthis("Got a blank emb style");
1.695 albertel 7162: }
1.694 albertel 7163: }
7164: }
1.31 www 7165: return $thisfn;
1.12 www 7166: }
7167:
1.787 albertel 7168: sub clutter_with_no_wrapper {
7169: my $uri = &clutter(shift);
7170: if ($uri =~ m-^/adm/-) {
7171: $uri =~ s-^/adm/wrapper/-/-;
7172: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
7173: }
7174: return $uri;
7175: }
7176:
1.557 albertel 7177: sub freeze_escape {
7178: my ($value)=@_;
7179: if (ref($value)) {
7180: $value=&nfreeze($value);
7181: return '__FROZEN__'.&escape($value);
7182: }
7183: return &escape($value);
7184: }
7185:
1.11 www 7186:
1.557 albertel 7187: sub thaw_unescape {
7188: my ($value)=@_;
7189: if ($value =~ /^__FROZEN__/) {
7190: substr($value,0,10,undef);
7191: $value=&unescape($value);
7192: return &thaw($value);
7193: }
7194: return &unescape($value);
7195: }
7196:
1.436 albertel 7197: sub correct_line_ends {
7198: my ($result)=@_;
7199: $$result =~s/\r\n/\n/mg;
7200: $$result =~s/\r/\n/mg;
1.415 albertel 7201: }
1.1 albertel 7202: # ================================================================ Main Program
7203:
1.184 www 7204: sub goodbye {
1.204 albertel 7205: &logthis("Starting Shut down");
1.443 albertel 7206: #not converted to using infrastruture and probably shouldn't be
1.599 albertel 7207: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443 albertel 7208: #converted
1.599 albertel 7209: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
7210: &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
7211: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
7212: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425 albertel 7213: #1.1 only
1.599 albertel 7214: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
7215: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
7216: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
7217: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
7218: &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
7219: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
7220: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 7221: &flushcourselogs();
7222: &logthis("Shutting down");
7223: }
7224:
1.179 www 7225: BEGIN {
1.228 harris41 7226: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195 www 7227: unless ($readit) {
1.217 harris41 7228: {
1.781 raeburn 7229: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
7230: %perlvar = (%perlvar,%{$configvars});
1.227 harris41 7231: }
1.1 albertel 7232:
1.327 albertel 7233: # ------------------------------------------------------------ Read domain file
7234: {
7235: %domaindescription = ();
7236: %domain_auth_def = ();
7237: %domain_auth_arg_def = ();
1.448 albertel 7238: my $fh;
7239: if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800 albertel 7240: while (my $line = <$fh>) {
7241: next if ($line =~ /^(\#|\s*$)/);
1.390 matthew 7242: # next if /^\#/;
1.801 foxr 7243: chomp $line;
1.403 www 7244: my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.800 albertel 7245: $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
1.403 www 7246: $domain_auth_def{$domain}=$def_auth;
1.327 albertel 7247: $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403 www 7248: $domaindescription{$domain}=$domain_description;
7249: $domain_lang_def{$domain}=$def_lang;
7250: $domain_city{$domain}=$city;
7251: $domain_longi{$domain}=$longi;
7252: $domain_lati{$domain}=$lati;
1.685 raeburn 7253: $domain_primary{$domain}=$primary;
1.403 www 7254:
1.448 albertel 7255: # &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327 albertel 7256: # &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448 albertel 7257: }
1.327 albertel 7258: }
1.448 albertel 7259: close ($fh);
1.327 albertel 7260: }
7261:
7262:
1.1 albertel 7263: # ------------------------------------------------------------- Read hosts file
7264: {
1.448 albertel 7265: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1 albertel 7266:
7267: while (my $configline=<$config>) {
1.303 matthew 7268: next if ($configline =~ /^(\#|\s*$)/);
1.154 www 7269: chomp($configline);
1.595 albertel 7270: my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597 albertel 7271: $name=~s/\s//g;
1.595 albertel 7272: if ($id && $domain && $role && $name) {
1.252 albertel 7273: $hostname{$id}=$name;
7274: $hostdom{$id}=$domain;
7275: if ($role eq 'library') { $libserv{$id}=$name; }
1.245 www 7276: }
1.1 albertel 7277: }
1.448 albertel 7278: close($config);
1.619 albertel 7279: # FIXME: dev server don't want this, production servers _do_ want this
1.654 albertel 7280: #&get_iphost();
1.1 albertel 7281: }
7282:
1.598 albertel 7283: sub get_iphost {
7284: if (%iphost) { return %iphost; }
1.653 albertel 7285: my %name_to_ip;
1.598 albertel 7286: foreach my $id (keys(%hostname)) {
7287: my $name=$hostname{$id};
1.653 albertel 7288: my $ip;
7289: if (!exists($name_to_ip{$name})) {
7290: $ip = gethostbyname($name);
7291: if (!$ip || length($ip) ne 4) {
7292: &logthis("Skipping host $id name $name no IP found\n");
7293: next;
7294: }
7295: $ip=inet_ntoa($ip);
7296: $name_to_ip{$name} = $ip;
7297: } else {
7298: $ip = $name_to_ip{$name};
1.598 albertel 7299: }
7300: push(@{$iphost{$ip}},$id);
7301: }
7302: return %iphost;
7303: }
7304:
1.1 albertel 7305: # ------------------------------------------------------ Read spare server file
7306: {
1.448 albertel 7307: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 7308:
7309: while (my $configline=<$config>) {
7310: chomp($configline);
1.284 matthew 7311: if ($configline) {
1.784 albertel 7312: my ($host,$type) = split(':',$configline,2);
1.785 albertel 7313: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 7314: push(@{ $spareid{$type} }, $host);
1.1 albertel 7315: }
7316: }
1.448 albertel 7317: close($config);
1.1 albertel 7318: }
1.11 www 7319: # ------------------------------------------------------------ Read permissions
7320: {
1.448 albertel 7321: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 7322:
7323: while (my $configline=<$config>) {
1.448 albertel 7324: chomp($configline);
7325: if ($configline) {
7326: my ($role,$perm)=split(/ /,$configline);
7327: if ($perm ne '') { $pr{$role}=$perm; }
7328: }
1.11 www 7329: }
1.448 albertel 7330: close($config);
1.11 www 7331: }
7332:
7333: # -------------------------------------------- Read plain texts for permissions
7334: {
1.448 albertel 7335: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 7336:
7337: while (my $configline=<$config>) {
1.448 albertel 7338: chomp($configline);
7339: if ($configline) {
1.742 raeburn 7340: my ($short,@plain)=split(/:/,$configline);
7341: %{$prp{$short}} = ();
7342: if (@plain > 0) {
7343: $prp{$short}{'std'} = $plain[0];
7344: for (my $i=1; $i<@plain; $i++) {
7345: $prp{$short}{'alt'.$i} = $plain[$i];
7346: }
7347: }
1.448 albertel 7348: }
1.135 www 7349: }
1.448 albertel 7350: close($config);
1.135 www 7351: }
7352:
7353: # ---------------------------------------------------------- Read package table
7354: {
1.448 albertel 7355: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 7356:
7357: while (my $configline=<$config>) {
1.483 albertel 7358: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 7359: chomp($configline);
7360: my ($short,$plain)=split(/:/,$configline);
7361: my ($pack,$name)=split(/\&/,$short);
7362: if ($plain ne '') {
7363: $packagetab{$pack.'&'.$name.'&name'}=$name;
7364: $packagetab{$short}=$plain;
7365: }
1.11 www 7366: }
1.448 albertel 7367: close($config);
1.329 matthew 7368: }
7369:
7370: # ------------- set up temporary directory
7371: {
7372: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
7373:
1.11 www 7374: }
7375:
1.794 albertel 7376: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
7377: 'compress_threshold'=> 20_000,
7378: });
1.185 www 7379:
1.281 www 7380: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 7381: $dumpcount=0;
1.22 www 7382:
1.163 harris41 7383: &logtouch();
1.672 albertel 7384: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 7385: $readit=1;
1.564 albertel 7386: {
7387: use integer;
7388: my $test=(2**32)+1;
1.568 albertel 7389: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 7390: &logthis(" Detected 64bit platform ($_64bit)");
7391: }
1.195 www 7392: }
1.1 albertel 7393: }
1.179 www 7394:
1.1 albertel 7395: 1;
1.191 harris41 7396: __END__
7397:
1.243 albertel 7398: =pod
7399:
1.191 harris41 7400: =head1 NAME
7401:
1.243 albertel 7402: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 7403:
7404: =head1 SYNOPSIS
7405:
1.243 albertel 7406: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 7407:
7408: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
7409:
1.243 albertel 7410: Common parameters:
7411:
7412: =over 4
7413:
7414: =item *
7415:
7416: $uname : an internal username (if $cname expecting a course Id specifically)
7417:
7418: =item *
7419:
7420: $udom : a domain (if $cdom expecting a course's domain specifically)
7421:
7422: =item *
7423:
7424: $symb : a resource instance identifier
7425:
7426: =item *
7427:
7428: $namespace : the name of a .db file that contains the data needed or
7429: being set.
7430:
7431: =back
7432:
1.394 bowersj2 7433: =head1 OVERVIEW
1.191 harris41 7434:
1.394 bowersj2 7435: lonnet provides subroutines which interact with the
7436: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
7437: about classes, users, and resources.
1.243 albertel 7438:
7439: For many of these objects you can also use this to store data about
7440: them or modify them in various ways.
1.191 harris41 7441:
1.394 bowersj2 7442: =head2 Symbs
1.191 harris41 7443:
1.394 bowersj2 7444: To identify a specific instance of a resource, LON-CAPA uses symbols
7445: or "symbs"X<symb>. These identifiers are built from the URL of the
7446: map, the resource number of the resource in the map, and the URL of
7447: the resource itself. The latter is somewhat redundant, but might help
7448: if maps change.
7449:
7450: An example is
7451:
7452: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
7453:
7454: The respective map entry is
7455:
7456: <resource id="19" src="/res/msu/korte/tests/part12.problem"
7457: title="Problem 2">
7458: </resource>
7459:
7460: Symbs are used by the random number generator, as well as to store and
7461: restore data specific to a certain instance of for example a problem.
7462:
7463: =head2 Storing And Retrieving Data
7464:
7465: X<store()>X<cstore()>X<restore()>Three of the most important functions
7466: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
7467: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
7468: is is the non-critical message twin of cstore. These functions are for
7469: handlers to store a perl hash to a user's permanent data space in an
7470: easy manner, and to retrieve it again on another call. It is expected
7471: that a handler would use this once at the beginning to retrieve data,
7472: and then again once at the end to send only the new data back.
7473:
7474: The data is stored in the user's data directory on the user's
7475: homeserver under the ID of the course.
7476:
7477: The hash that is returned by restore will have all of the previous
7478: value for all of the elements of the hash.
7479:
7480: Example:
7481:
7482: #creating a hash
7483: my %hash;
7484: $hash{'foo'}='bar';
7485:
7486: #storing it
7487: &Apache::lonnet::cstore(\%hash);
7488:
7489: #changing a value
7490: $hash{'foo'}='notbar';
7491:
7492: #adding a new value
7493: $hash{'bar'}='foo';
7494: &Apache::lonnet::cstore(\%hash);
7495:
7496: #retrieving the hash
7497: my %history=&Apache::lonnet::restore();
7498:
7499: #print the hash
7500: foreach my $key (sort(keys(%history))) {
7501: print("\%history{$key} = $history{$key}");
7502: }
7503:
7504: Will print out:
1.191 harris41 7505:
1.394 bowersj2 7506: %history{1:foo} = bar
7507: %history{1:keys} = foo:timestamp
7508: %history{1:timestamp} = 990455579
7509: %history{2:bar} = foo
7510: %history{2:foo} = notbar
7511: %history{2:keys} = foo:bar:timestamp
7512: %history{2:timestamp} = 990455580
7513: %history{bar} = foo
7514: %history{foo} = notbar
7515: %history{timestamp} = 990455580
7516: %history{version} = 2
7517:
7518: Note that the special hash entries C<keys>, C<version> and
7519: C<timestamp> were added to the hash. C<version> will be equal to the
7520: total number of versions of the data that have been stored. The
7521: C<timestamp> attribute will be the UNIX time the hash was
7522: stored. C<keys> is available in every historical section to list which
7523: keys were added or changed at a specific historical revision of a
7524: hash.
7525:
7526: B<Warning>: do not store the hash that restore returns directly. This
7527: will cause a mess since it will restore the historical keys as if the
7528: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 7529:
1.394 bowersj2 7530: Calling convention:
1.191 harris41 7531:
1.394 bowersj2 7532: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
7533: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 7534:
1.394 bowersj2 7535: For more detailed information, see lonnet specific documentation.
1.191 harris41 7536:
1.394 bowersj2 7537: =head1 RETURN MESSAGES
1.191 harris41 7538:
1.394 bowersj2 7539: =over 4
1.191 harris41 7540:
1.394 bowersj2 7541: =item * B<con_lost>: unable to contact remote host
1.191 harris41 7542:
1.394 bowersj2 7543: =item * B<con_delayed>: unable to contact remote host, message will be delivered
7544: when the connection is brought back up
1.191 harris41 7545:
1.394 bowersj2 7546: =item * B<con_failed>: unable to contact remote host and unable to save message
7547: for later delivery
1.191 harris41 7548:
1.394 bowersj2 7549: =item * B<error:>: an error a occured, a description of the error follows the :
1.191 harris41 7550:
1.394 bowersj2 7551: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 7552: that was requested
1.191 harris41 7553:
1.243 albertel 7554: =back
1.191 harris41 7555:
1.243 albertel 7556: =head1 PUBLIC SUBROUTINES
1.191 harris41 7557:
1.243 albertel 7558: =head2 Session Environment Functions
1.191 harris41 7559:
1.243 albertel 7560: =over 4
1.191 harris41 7561:
1.394 bowersj2 7562: =item *
7563: X<appenv()>
7564: B<appenv(%hash)>: the value of %hash is written to
7565: the user envirnoment file, and will be restored for each access this
1.620 albertel 7566: user makes during this session, also modifies the %env for the current
1.394 bowersj2 7567: process
1.191 harris41 7568:
7569: =item *
1.394 bowersj2 7570: X<delenv()>
7571: B<delenv($regexp)>: removes all items from the session
7572: environment file that matches the regular expression in $regexp. The
1.620 albertel 7573: values are also delted from the current processes %env.
1.191 harris41 7574:
1.795 albertel 7575: =item * get_env_multiple($name)
7576:
7577: gets $name from the %env hash, it seemlessly handles the cases where multiple
7578: values may be defined and end up as an array ref.
7579:
7580: returns an array of values
7581:
1.243 albertel 7582: =back
7583:
7584: =head2 User Information
1.191 harris41 7585:
1.243 albertel 7586: =over 4
1.191 harris41 7587:
7588: =item *
1.394 bowersj2 7589: X<queryauthenticate()>
7590: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 7591: authentication scheme
7592:
7593: =item *
1.394 bowersj2 7594: X<authenticate()>
7595: B<authenticate($uname,$upass,$udom)>: try to
7596: authenticate user from domain's lib servers (first use the current
7597: one). C<$upass> should be the users password.
1.191 harris41 7598:
7599: =item *
1.394 bowersj2 7600: X<homeserver()>
7601: B<homeserver($uname,$udom)>: find the server which has
7602: the user's directory and files (there must be only one), this caches
7603: the answer, and also caches if there is a borken connection.
1.191 harris41 7604:
7605: =item *
1.394 bowersj2 7606: X<idget()>
7607: B<idget($udom,@ids)>: find the usernames behind a list of IDs
7608: (IDs are a unique resource in a domain, there must be only 1 ID per
7609: username, and only 1 username per ID in a specific domain) (returns
7610: hash: id=>name,id=>name)
1.191 harris41 7611:
7612: =item *
1.394 bowersj2 7613: X<idrget()>
7614: B<idrget($udom,@unames)>: find the IDs behind a list of
7615: usernames (returns hash: name=>id,name=>id)
1.191 harris41 7616:
7617: =item *
1.394 bowersj2 7618: X<idput()>
7619: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 7620:
7621: =item *
1.394 bowersj2 7622: X<rolesinit()>
7623: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 7624:
7625: =item *
1.551 albertel 7626: X<getsection()>
7627: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 7628: course $cname, return section name/number or '' for "not in course"
7629: and '-1' for "no section"
7630:
7631: =item *
1.394 bowersj2 7632: X<userenvironment()>
7633: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 7634: passed in @what from the requested user's environment, returns a hash
7635:
7636: =back
7637:
7638: =head2 User Roles
7639:
7640: =over 4
7641:
7642: =item *
7643:
7644: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
7645: actions
7646: F: full access
7647: U,I,K: authentication modes (cxx only)
7648: '': forbidden
7649: 1: user needs to choose course
7650: 2: browse allowed
1.766 albertel 7651: A: passphrase authentication needed
1.243 albertel 7652:
7653: =item *
7654:
7655: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
7656: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
7657: and course level
7658:
7659: =item *
7660:
7661: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
7662: explanation of a user role term
7663:
7664: =back
7665:
7666: =head2 User Modification
7667:
7668: =over 4
7669:
7670: =item *
7671:
7672: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
7673: user for the level given by URL. Optional start and end dates (leave empty
7674: string or zero for "no date")
1.191 harris41 7675:
7676: =item *
7677:
1.243 albertel 7678: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
7679: change a users, password, possible return values are: ok,
7680: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
7681: refused
1.191 harris41 7682:
7683: =item *
7684:
1.243 albertel 7685: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 7686:
7687: =item *
7688:
1.243 albertel 7689: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
7690: modify user
1.191 harris41 7691:
7692: =item *
7693:
1.286 matthew 7694: modifystudent
7695:
7696: modify a students enrollment and identification information.
7697: The course id is resolved based on the current users environment.
7698: This means the envoking user must be a course coordinator or otherwise
7699: associated with a course.
7700:
1.297 matthew 7701: This call is essentially a wrapper for lonnet::modifyuser and
7702: lonnet::modify_student_enrollment
1.286 matthew 7703:
7704: Inputs:
7705:
7706: =over 4
7707:
7708: =item B<$udom> Students loncapa domain
7709:
7710: =item B<$uname> Students loncapa login name
7711:
7712: =item B<$uid> Students id/student number
7713:
7714: =item B<$umode> Students authentication mode
7715:
7716: =item B<$upass> Students password
7717:
7718: =item B<$first> Students first name
7719:
7720: =item B<$middle> Students middle name
7721:
7722: =item B<$last> Students last name
7723:
7724: =item B<$gene> Students generation
7725:
7726: =item B<$usec> Students section in course
7727:
7728: =item B<$end> Unix time of the roles expiration
7729:
7730: =item B<$start> Unix time of the roles start date
7731:
7732: =item B<$forceid> If defined, allow $uid to be changed
7733:
7734: =item B<$desiredhome> server to use as home server for student
7735:
7736: =back
1.297 matthew 7737:
7738: =item *
7739:
7740: modify_student_enrollment
7741:
7742: Change a students enrollment status in a class. The environment variable
7743: 'role.request.course' must be defined for this function to proceed.
7744:
7745: Inputs:
7746:
7747: =over 4
7748:
7749: =item $udom, students domain
7750:
7751: =item $uname, students name
7752:
7753: =item $uid, students user id
7754:
7755: =item $first, students first name
7756:
7757: =item $middle
7758:
7759: =item $last
7760:
7761: =item $gene
7762:
7763: =item $usec
7764:
7765: =item $end
7766:
7767: =item $start
7768:
7769: =back
7770:
1.191 harris41 7771:
7772: =item *
7773:
1.243 albertel 7774: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
7775: custom role; give a custom role to a user for the level given by URL. Specify
7776: name and domain of role author, and role name
1.191 harris41 7777:
7778: =item *
7779:
1.243 albertel 7780: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 7781:
7782: =item *
7783:
1.243 albertel 7784: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
7785:
7786: =back
7787:
7788: =head2 Course Infomation
7789:
7790: =over 4
1.191 harris41 7791:
7792: =item *
7793:
1.631 albertel 7794: coursedescription($courseid) : returns a hash of information about the
7795: specified course id, including all environment settings for the
7796: course, the description of the course will be in the hash under the
7797: key 'description'
1.191 harris41 7798:
7799: =item *
7800:
1.624 albertel 7801: resdata($name,$domain,$type,@which) : request for current parameter
7802: setting for a specific $type, where $type is either 'course' or 'user',
7803: @what should be a list of parameters to ask about. This routine caches
7804: answers for 5 minutes.
1.243 albertel 7805:
7806: =back
7807:
7808: =head2 Course Modification
7809:
7810: =over 4
1.191 harris41 7811:
7812: =item *
7813:
1.243 albertel 7814: writecoursepref($courseid,%prefs) : write preferences (environment
7815: database) for a course
1.191 harris41 7816:
7817: =item *
7818:
1.243 albertel 7819: createcourse($udom,$description,$url) : make/modify course
7820:
7821: =back
7822:
7823: =head2 Resource Subroutines
7824:
7825: =over 4
1.191 harris41 7826:
7827: =item *
7828:
1.243 albertel 7829: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 7830:
7831: =item *
7832:
1.243 albertel 7833: repcopy($filename) : subscribes to the requested file, and attempts to
7834: replicate from the owning library server, Might return
1.607 raeburn 7835: 'unavailable', 'not_found', 'forbidden', 'ok', or
7836: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 7837: resource. Expects the local filesystem pathname
7838: (/home/httpd/html/res/....)
7839:
7840: =back
7841:
7842: =head2 Resource Information
7843:
7844: =over 4
1.191 harris41 7845:
7846: =item *
7847:
1.243 albertel 7848: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
7849: a vairety of different possible values, $varname should be a request
7850: string, and the other parameters can be used to specify who and what
7851: one is asking about.
7852:
7853: Possible values for $varname are environment.lastname (or other item
7854: from the envirnment hash), user.name (or someother aspect about the
7855: user), resource.0.maxtries (or some other part and parameter of a
7856: resource)
1.204 albertel 7857:
7858: =item *
7859:
1.243 albertel 7860: directcondval($number) : get current value of a condition; reads from a state
7861: string
1.204 albertel 7862:
7863: =item *
7864:
1.243 albertel 7865: condval($condidx) : value of condition index based on state
1.204 albertel 7866:
7867: =item *
7868:
1.243 albertel 7869: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
7870: resource's metadata, $what should be either a specific key, or either
7871: 'keys' (to get a list of possible keys) or 'packages' to get a list of
7872: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
7873:
7874: this function automatically caches all requests
1.191 harris41 7875:
7876: =item *
7877:
1.243 albertel 7878: metadata_query($query,$custom,$customshow) : make a metadata query against the
7879: network of library servers; returns file handle of where SQL and regex results
7880: will be stored for query
1.191 harris41 7881:
7882: =item *
7883:
1.243 albertel 7884: symbread($filename) : return symbolic list entry (filename argument optional);
7885: returns the data handle
1.191 harris41 7886:
7887: =item *
7888:
1.243 albertel 7889: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 7890: a possible symb for the URL in $thisfn, and if is an encryypted
7891: resource that the user accessed using /enc/ returns a 1 on success, 0
7892: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 7893: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 7894:
1.191 harris41 7895:
7896: =item *
7897:
1.243 albertel 7898: symbclean($symb) : removes versions numbers from a symb, returns the
7899: cleaned symb
1.191 harris41 7900:
7901: =item *
7902:
1.243 albertel 7903: is_on_map($uri) : checks if the $uri is somewhere on the current
7904: course map, user must be in a course for it to work.
1.191 harris41 7905:
7906: =item *
7907:
1.243 albertel 7908: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 7909:
7910: =item *
7911:
1.243 albertel 7912: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
7913: a random seed, all arguments are optional, if they aren't sent it uses the
7914: environment to derive them. Note: if symb isn't sent and it can't get one
7915: from &symbread it will use the current time as its return value
1.191 harris41 7916:
7917: =item *
7918:
1.243 albertel 7919: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
7920: unfakeable, receipt
1.191 harris41 7921:
7922: =item *
7923:
1.620 albertel 7924: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 7925:
7926: =item *
7927:
1.243 albertel 7928: countacc($url) : count the number of accesses to a given URL
1.191 harris41 7929:
7930: =item *
7931:
1.243 albertel 7932: 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 7933:
7934: =item *
7935:
1.243 albertel 7936: 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 7937:
7938: =item *
7939:
1.243 albertel 7940: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 7941:
7942: =item *
7943:
1.243 albertel 7944: devalidate($symb) : devalidate temporary spreadsheet calculations,
7945: forcing spreadsheet to reevaluate the resource scores next time.
7946:
7947: =back
7948:
7949: =head2 Storing/Retreiving Data
7950:
7951: =over 4
1.191 harris41 7952:
7953: =item *
7954:
1.243 albertel 7955: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
7956: for this url; hashref needs to be given and should be a \%hashname; the
7957: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 7958: be derived from the env
1.191 harris41 7959:
7960: =item *
7961:
1.243 albertel 7962: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
7963: uses critical subroutine
1.191 harris41 7964:
7965: =item *
7966:
1.243 albertel 7967: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
7968: all args are optional
1.191 harris41 7969:
7970: =item *
7971:
1.717 albertel 7972: dumpstore($namespace,$udom,$uname,$regexp,$range) :
7973: dumps the complete (or key matching regexp) namespace into a hash
7974: ($udom, $uname, $regexp, $range are optional) for a namespace that is
7975: normally &store()ed into
7976:
7977: $range should be either an integer '100' (give me the first 100
7978: matching records)
7979: or be two integers sperated by a - with no spaces
7980: '30-50' (give me the 30th through the 50th matching
7981: records)
7982:
7983:
7984: =item *
7985:
7986: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
7987: replaces a &store() version of data with a replacement set of data
7988: for a particular resource in a namespace passed in the $storehash hash
7989: reference
7990:
7991: =item *
7992:
1.243 albertel 7993: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
7994: works very similar to store/cstore, but all data is stored in a
7995: temporary location and can be reset using tmpreset, $storehash should
7996: be a hash reference, returns nothing on success
1.191 harris41 7997:
7998: =item *
7999:
1.243 albertel 8000: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
8001: similar to restore, but all data is stored in a temporary location and
8002: can be reset using tmpreset. Returns a hash of values on success,
8003: error string otherwise.
1.191 harris41 8004:
8005: =item *
8006:
1.243 albertel 8007: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
8008: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 8009:
8010: =item *
8011:
1.243 albertel 8012: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8013: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 8014:
8015: =item *
8016:
1.243 albertel 8017: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
8018: namesp ($udom and $uname are optional)
1.191 harris41 8019:
8020: =item *
8021:
1.702 albertel 8022: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 8023: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 8024: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 8025:
1.702 albertel 8026: $range should be either an integer '100' (give me the first 100
8027: matching records)
8028: or be two integers sperated by a - with no spaces
8029: '30-50' (give me the 30th through the 50th matching
8030: records)
1.449 matthew 8031: =item *
8032:
8033: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
8034: $store can be a scalar, an array reference, or if the amount to be
8035: incremented is > 1, a hash reference.
8036:
8037: ($udom and $uname are optional)
1.191 harris41 8038:
8039: =item *
8040:
1.243 albertel 8041: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
8042: ($udom and $uname are optional)
1.191 harris41 8043:
8044: =item *
8045:
1.243 albertel 8046: cput($namespace,$storehash,$udom,$uname) : critical put
8047: ($udom and $uname are optional)
1.191 harris41 8048:
8049: =item *
8050:
1.748 albertel 8051: newput($namespace,$storehash,$udom,$uname) :
8052:
8053: Attempts to store the items in the $storehash, but only if they don't
8054: currently exist, if this succeeds you can be certain that you have
8055: successfully created a new key value pair in the $namespace db.
8056:
8057:
8058: Args:
8059: $namespace: name of database to store values to
8060: $storehash: hashref to store to the db
8061: $udom: (optional) domain of user containing the db
8062: $uname: (optional) name of user caontaining the db
8063:
8064: Returns:
8065: 'ok' -> succeeded in storing all keys of $storehash
8066: 'key_exists: <key>' -> failed to anything out of $storehash, as at
8067: least <key> already existed in the db (other
8068: requested keys may also already exist)
8069: 'error: <msg>' -> unable to tie the DB or other erorr occured
8070: 'con_lost' -> unable to contact request server
8071: 'refused' -> action was not allowed by remote machine
8072:
8073:
8074: =item *
8075:
1.243 albertel 8076: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8077: reference filled in from namesp (encrypts the return communication)
8078: ($udom and $uname are optional)
1.191 harris41 8079:
8080: =item *
8081:
1.243 albertel 8082: log($udom,$name,$home,$message) : write to permanent log for user; use
8083: critical subroutine
8084:
8085: =back
8086:
8087: =head2 Network Status Functions
8088:
8089: =over 4
1.191 harris41 8090:
8091: =item *
8092:
8093: dirlist($uri) : return directory list based on URI
8094:
8095: =item *
8096:
1.243 albertel 8097: spareserver() : find server with least workload from spare.tab
8098:
8099: =back
8100:
8101: =head2 Apache Request
8102:
8103: =over 4
1.191 harris41 8104:
8105: =item *
8106:
1.243 albertel 8107: ssi($url,%hash) : server side include, does a complete request cycle on url to
8108: localhost, posts hash
8109:
8110: =back
8111:
8112: =head2 Data to String to Data
8113:
8114: =over 4
1.191 harris41 8115:
8116: =item *
8117:
1.243 albertel 8118: hash2str(%hash) : convert a hash into a string complete with escaping and '='
8119: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 8120:
8121: =item *
8122:
1.243 albertel 8123: hashref2str($hashref) : convert a hashref into a string complete with
8124: escaping and '=' and '&' separators, supports elements that are
8125: arrayrefs and hashrefs
1.191 harris41 8126:
8127: =item *
8128:
1.243 albertel 8129: arrayref2str($arrayref) : convert an arrayref into a string complete
8130: with escaping and '&' separators, supports elements that are arrayrefs
8131: and hashrefs
1.191 harris41 8132:
8133: =item *
8134:
1.243 albertel 8135: str2hash($string) : convert string to hash using unescaping and
8136: splitting on '=' and '&', supports elements that are arrayrefs and
8137: hashrefs
1.191 harris41 8138:
8139: =item *
8140:
1.243 albertel 8141: str2array($string) : convert string to hash using unescaping and
8142: splitting on '&', supports elements that are arrayrefs and hashrefs
8143:
8144: =back
8145:
8146: =head2 Logging Routines
8147:
8148: =over 4
8149:
8150: These routines allow one to make log messages in the lonnet.log and
8151: lonnet.perm logfiles.
1.191 harris41 8152:
8153: =item *
8154:
1.243 albertel 8155: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 8156:
8157: =item *
8158:
1.243 albertel 8159: logthis() : append message to the normal lonnet.log file, it gets
8160: preiodically rolled over and deleted.
1.191 harris41 8161:
8162: =item *
8163:
1.243 albertel 8164: logperm() : append a permanent message to lonnet.perm.log, this log
8165: file never gets deleted by any automated portion of the system, only
8166: messages of critical importance should go in here.
8167:
8168: =back
8169:
8170: =head2 General File Helper Routines
8171:
8172: =over 4
1.191 harris41 8173:
8174: =item *
8175:
1.481 raeburn 8176: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
8177: (a) files in /uploaded
8178: (i) If a local copy of the file exists -
8179: compares modification date of local copy with last-modified date for
8180: definitive version stored on home server for course. If local copy is
8181: stale, requests a new version from the home server and stores it.
8182: If the original has been removed from the home server, then local copy
8183: is unlinked.
8184: (ii) If local copy does not exist -
8185: requests the file from the home server and stores it.
8186:
8187: If $caller is 'uploadrep':
8188: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
8189: for request for files originally uploaded via DOCS.
8190: - returns 'ok' if fresh local copy now available, -1 otherwise.
8191:
8192: Otherwise:
8193: This indicates a call from the content generation phase of the request.
8194: - returns the entire contents of the file or -1.
8195:
8196: (b) files in /res
8197: - returns the entire contents of a file or -1;
8198: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 8199:
1.712 albertel 8200:
8201: =item *
8202:
8203: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
8204: reference
8205:
8206: returns either a stat() list of data about the file or an empty list
8207: if the file doesn't exist or couldn't find out about it (connection
8208: problems or user unknown)
8209:
1.191 harris41 8210: =item *
8211:
1.243 albertel 8212: filelocation($dir,$file) : returns file system location of a file
8213: based on URI; meant to be "fairly clean" absolute reference, $dir is a
8214: directory that relative $file lookups are to looked in ($dir of /a/dir
8215: and a file of ../bob will become /a/bob)
1.191 harris41 8216:
8217: =item *
8218:
8219: hreflocation($dir,$file) : returns file system location or a URL; same as
8220: filelocation except for hrefs
8221:
8222: =item *
8223:
8224: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
8225:
1.243 albertel 8226: =back
8227:
1.608 albertel 8228: =head2 Usererfile file routines (/uploaded*)
8229:
8230: =over 4
8231:
8232: =item *
8233:
8234: userfileupload(): main rotine for putting a file in a user or course's
8235: filespace, arguments are,
8236:
1.620 albertel 8237: formname - required - this is the name of the element in $env where the
1.608 albertel 8238: filename, and the contents of the file to create/modifed exist
1.620 albertel 8239: the filename is in $env{'form.'.$formname.'.filename'} and the
8240: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 8241: coursedoc - if true, store the file in the course of the active role
8242: of the current user
8243: subdir - required - subdirectory to put the file in under ../userfiles/
8244: if undefined, it will be placed in "unknown"
8245:
8246: (This routine calls clean_filename() to remove any dangerous
8247: characters from the filename, and then calls finuserfileupload() to
8248: complete the transaction)
8249:
8250: returns either the url of the uploaded file (/uploaded/....) if successful
8251: and /adm/notfound.html if unsuccessful
8252:
8253: =item *
8254:
8255: clean_filename(): routine for cleaing a filename up for storage in
8256: userfile space, argument is:
8257:
8258: filename - proposed filename
8259:
8260: returns: the new clean filename
8261:
8262: =item *
8263:
8264: finishuserfileupload(): routine that creaes and sends the file to
8265: userspace, probably shouldn't be called directly
8266:
8267: docuname: username or courseid of destination for the file
8268: docudom: domain of user/course of destination for the file
8269: formname: same as for userfileupload()
8270: fname: filename (inculding subdirectories) for the file
8271:
8272: returns either the url of the uploaded file (/uploaded/....) if successful
8273: and /adm/notfound.html if unsuccessful
8274:
8275: =item *
8276:
8277: renameuserfile(): renames an existing userfile to a new name
8278:
8279: Args:
8280: docuname: username or courseid of destination for the file
8281: docudom: domain of user/course of destination for the file
8282: old: current file name (including any subdirs under userfiles)
8283: new: desired file name (including any subdirs under userfiles)
8284:
8285: =item *
8286:
8287: mkdiruserfile(): creates a directory is a userfiles dir
8288:
8289: Args:
8290: docuname: username or courseid of destination for the file
8291: docudom: domain of user/course of destination for the file
8292: dir: dir to create (including any subdirs under userfiles)
8293:
8294: =item *
8295:
8296: removeuserfile(): removes a file that exists in userfiles
8297:
8298: Args:
8299: docuname: username or courseid of destination for the file
8300: docudom: domain of user/course of destination for the file
8301: fname: filname to delete (including any subdirs under userfiles)
8302:
8303: =item *
8304:
8305: removeuploadedurl(): convience function for removeuserfile()
8306:
8307: Args:
8308: url: a full /uploaded/... url to delete
8309:
1.747 albertel 8310: =item *
8311:
8312: get_portfile_permissions():
8313: Args:
8314: domain: domain of user or course contain the portfolio files
8315: user: name of user or num of course contain the portfolio files
8316: Returns:
8317: hashref of a dump of the proper file_permissions.db
8318:
8319:
8320: =item *
8321:
8322: get_access_controls():
8323:
8324: Args:
8325: current_permissions: the hash ref returned from get_portfile_permissions()
8326: group: (optional) the group you want the files associated with
8327: file: (optional) the file you want access info on
8328:
8329: Returns:
1.749 raeburn 8330: a hash (keys are file names) of hashes containing
8331: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
8332: values are XML containing access control settings (see below)
1.747 albertel 8333:
8334: Internal notes:
8335:
1.749 raeburn 8336: access controls are stored in file_permissions.db as key=value pairs.
8337: key -> path to file/file_name\0uniqueID:scope_end_start
8338: where scope -> public,guest,course,group,domains or users.
8339: end -> UNIX time for end of access (0 -> no end date)
8340: start -> UNIX time for start of access
8341:
8342: value -> XML description of access control
8343: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
8344: <start></start>
8345: <end></end>
8346:
8347: <password></password> for scope type = guest
8348:
8349: <domain></domain> for scope type = course or group
8350: <number></number>
8351: <roles id="">
8352: <role></role>
8353: <access></access>
8354: <section></section>
8355: <group></group>
8356: </roles>
8357:
8358: <dom></dom> for scope type = domains
8359:
8360: <users> for scope type = users
8361: <user>
8362: <uname></uname>
8363: <udom></udom>
8364: </user>
8365: </users>
8366: </scope>
8367:
8368: Access data is also aggregated for each file in an additional key=value pair:
8369: key -> path to file/file_name\0accesscontrol
8370: value -> reference to hash
8371: hash contains key = value pairs
8372: where key = uniqueID:scope_end_start
8373: value = UNIX time record was last updated
8374:
8375: Used to improve speed of look-ups of access controls for each file.
8376:
8377: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
8378:
8379: modify_access_controls():
8380:
8381: Modifies access controls for a portfolio file
8382: Args
8383: 1. file name
8384: 2. reference to hash of required changes,
8385: 3. domain
8386: 4. username
8387: where domain,username are the domain of the portfolio owner
8388: (either a user or a course)
8389:
8390: Returns:
8391: 1. result of additions or updates ('ok' or 'error', with error message).
8392: 2. result of deletions ('ok' or 'error', with error message).
8393: 3. reference to hash of any new or updated access controls.
8394: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
8395: key = integer (inbound ID)
8396: value = uniqueID
1.747 albertel 8397:
1.608 albertel 8398: =back
8399:
1.243 albertel 8400: =head2 HTTP Helper Routines
8401:
8402: =over 4
8403:
1.191 harris41 8404: =item *
8405:
8406: escape() : unpack non-word characters into CGI-compatible hex codes
8407:
8408: =item *
8409:
8410: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
8411:
1.243 albertel 8412: =back
8413:
8414: =head1 PRIVATE SUBROUTINES
8415:
8416: =head2 Underlying communication routines (Shouldn't call)
8417:
8418: =over 4
8419:
8420: =item *
8421:
8422: subreply() : tries to pass a message to lonc, returns con_lost if incapable
8423:
8424: =item *
8425:
8426: reply() : uses subreply to send a message to remote machine, logs all failures
8427:
8428: =item *
8429:
8430: critical() : passes a critical message to another server; if cannot
8431: get through then place message in connection buffer directory and
8432: returns con_delayed, if incapable of saving message, returns
8433: con_failed
8434:
8435: =item *
8436:
8437: reconlonc() : tries to reconnect lonc client processes.
8438:
8439: =back
8440:
8441: =head2 Resource Access Logging
8442:
8443: =over 4
8444:
8445: =item *
8446:
8447: flushcourselogs() : flush (save) buffer logs and access logs
8448:
8449: =item *
8450:
8451: courselog($what) : save message for course in hash
8452:
8453: =item *
8454:
8455: courseacclog($what) : save message for course using &courselog(). Perform
8456: special processing for specific resource types (problems, exams, quizzes, etc).
8457:
1.191 harris41 8458: =item *
8459:
8460: goodbye() : flush course logs and log shutting down; it is called in srm.conf
8461: as a PerlChildExitHandler
1.243 albertel 8462:
8463: =back
8464:
8465: =head2 Other
8466:
8467: =over 4
8468:
8469: =item *
8470:
8471: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 8472:
8473: =back
8474:
8475: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>