Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.451
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.451 ! albertel 4: # $Id: lonnet.pm,v 1.450 2003/11/12 21:37:33 matthew 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.11 www 35: use vars
1.300 albertel 36: qw(%perlvar %hostname %homecache %badServerCache %hostip %iphost %spareid %hostdom
1.440 www 37: %libserv %pr %prp %metacache %packagetab %titlecache %courseresversioncache %resversioncache
1.349 www 38: %courselogs %accesshash %userrolehash $processmarker $dumpcount
1.352 www 39: %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseresdatacache
1.420 albertel 40: %userresdatacache %usectioncache %domaindescription %domain_auth_def %domain_auth_arg_def
1.403 www 41: %domain_lang_def %domain_city %domain_longi %domain_lati $tmpdir);
42:
1.1 albertel 43: use IO::Socket;
1.31 www 44: use GDBM_File;
1.8 www 45: use Apache::Constants qw(:common :http);
1.208 albertel 46: use HTML::LCParser;
1.88 www 47: use Fcntl qw(:flock);
1.294 matthew 48: use Apache::loncoursedata;
1.414 www 49: use Apache::lonlocal;
1.428 albertel 50: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw);
1.425 albertel 51: use Time::HiRes();
1.195 www 52: my $readit;
1.1 albertel 53:
1.449 matthew 54: =pod
55:
56: =head1 Package Variables
57:
58: These are largely undocumented, so if you decipher one please note it here.
59:
60: =over 4
61:
62: =item $processmarker
63:
64: Contains the time this process was started and this servers host id.
65:
66: =item $dumpcount
67:
68: Counts the number of times a message log flush has been attempted (regardless
69: of success) by this process. Used as part of the filename when messages are
70: delayed.
71:
72: =back
73:
74: =cut
75:
76:
1.1 albertel 77: # --------------------------------------------------------------------- Logging
78:
1.163 harris41 79: sub logtouch {
80: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 81: unless (-e "$execdir/logs/lonnet.log") {
82: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 83: close $fh;
84: }
85: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
86: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
87: }
88:
1.1 albertel 89: sub logthis {
90: my $message=shift;
91: my $execdir=$perlvar{'lonDaemons'};
92: my $now=time;
93: my $local=localtime($now);
1.448 albertel 94: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
95: print $fh "$local ($$): $message\n";
96: close($fh);
97: }
1.1 albertel 98: return 1;
99: }
100:
101: sub logperm {
102: my $message=shift;
103: my $execdir=$perlvar{'lonDaemons'};
104: my $now=time;
105: my $local=localtime($now);
1.448 albertel 106: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
107: print $fh "$now:$message:$local\n";
108: close($fh);
109: }
1.1 albertel 110: return 1;
111: }
112:
113: # -------------------------------------------------- Non-critical communication
114: sub subreply {
115: my ($cmd,$server)=@_;
116: my $peerfile="$perlvar{'lonSockDir'}/$server";
117: my $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
118: Type => SOCK_STREAM,
119: Timeout => 10)
120: or return "con_lost";
121: print $client "$cmd\n";
122: my $answer=<$client>;
1.9 www 123: if (!$answer) { $answer="con_lost"; }
1.1 albertel 124: chomp($answer);
125: return $answer;
126: }
127:
128: sub reply {
129: my ($cmd,$server)=@_;
1.205 www 130: unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1 albertel 131: my $answer=subreply($cmd,$server);
1.203 www 132: if ($answer eq 'con_lost') {
1.311 matthew 133: #sleep 5;
134: #$answer=subreply($cmd,$server);
135: #if ($answer eq 'con_lost') {
1.233 albertel 136: # &logthis("Second attempt con_lost on $server");
137: # my $peerfile="$perlvar{'lonSockDir'}/$server";
138: # my $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
139: # Type => SOCK_STREAM,
140: # Timeout => 10)
141: # or return "con_lost";
142: # &logthis("Killing socket");
143: # print $client "close_connection_exit\n";
144: #sleep 5;
145: # $answer=subreply($cmd,$server);
146: #}
1.203 www 147: }
1.65 www 148: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.12 www 149: &logthis("<font color=blue>WARNING:".
150: " $cmd to $server returned $answer</font>");
151: }
1.1 albertel 152: return $answer;
153: }
154:
155: # ----------------------------------------------------------- Send USR1 to lonc
156:
157: sub reconlonc {
158: my $peerfile=shift;
159: &logthis("Trying to reconnect for $peerfile");
160: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 161: if (open(my $fh,"<$loncfile")) {
1.1 albertel 162: my $loncpid=<$fh>;
163: chomp($loncpid);
164: if (kill 0 => $loncpid) {
165: &logthis("lonc at pid $loncpid responding, sending USR1");
166: kill USR1 => $loncpid;
167: sleep 1;
168: if (-e "$peerfile") { return; }
169: &logthis("$peerfile still not there, give it another try");
170: sleep 5;
171: if (-e "$peerfile") { return; }
1.12 www 172: &logthis(
173: "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
1.1 albertel 174: } else {
1.12 www 175: &logthis(
176: "<font color=blue>WARNING:".
177: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 178: }
179: } else {
1.12 www 180: &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
1.1 albertel 181: }
182: }
183:
184: # ------------------------------------------------------ Critical communication
1.12 www 185:
1.1 albertel 186: sub critical {
187: my ($cmd,$server)=@_;
1.89 www 188: unless ($hostname{$server}) {
189: &logthis("<font color=blue>WARNING:".
190: " Critical message to unknown server ($server)</font>");
191: return 'no_such_host';
192: }
1.1 albertel 193: my $answer=reply($cmd,$server);
194: if ($answer eq 'con_lost') {
195: my $pingreply=reply('ping',$server);
196: &reconlonc("$perlvar{'lonSockDir'}/$server");
197: my $pongreply=reply('pong',$server);
198: &logthis("Ping/Pong for $server: $pingreply/$pongreply");
199: $answer=reply($cmd,$server);
200: if ($answer eq 'con_lost') {
201: my $now=time;
202: my $middlename=$cmd;
1.5 www 203: $middlename=substr($middlename,0,16);
1.1 albertel 204: $middlename=~s/\W//g;
205: my $dfilename=
1.305 www 206: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
207: $dumpcount++;
1.1 albertel 208: {
1.448 albertel 209: my $dfh;
210: if (open($dfh,">$dfilename")) {
211: print $dfh "$cmd\n";
212: close($dfh);
213: }
1.1 albertel 214: }
215: sleep 2;
216: my $wcmd='';
217: {
1.448 albertel 218: my $dfh;
219: if (open($dfh,"<$dfilename")) {
220: $wcmd=<$dfh>;
221: close($dfh);
222: }
1.1 albertel 223: }
224: chomp($wcmd);
1.7 www 225: if ($wcmd eq $cmd) {
1.12 www 226: &logthis("<font color=blue>WARNING: ".
227: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 228: &logperm("D:$server:$cmd");
229: return 'con_delayed';
230: } else {
1.12 www 231: &logthis("<font color=red>CRITICAL:"
232: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 233: &logperm("F:$server:$cmd");
234: return 'con_failed';
235: }
236: }
237: }
238: return $answer;
1.405 albertel 239: }
240:
1.412 www 241: #
1.405 albertel 242: # -------------- Remove all key from the env that start witha lowercase letter
1.412 www 243: # (Which is always a lon-capa value)
244:
1.405 albertel 245: sub cleanenv {
1.412 www 246: # unless (defined(&Apache::exists_config_define("MODPERL2"))) { return; }
247: # unless (&Apache::exists_config_define("MODPERL2")) { return; }
1.405 albertel 248: foreach my $key (keys(%ENV)) {
249: if ($key =~ /^[a-z]/) {
250: delete($ENV{$key});
251: }
252: }
1.374 www 253: }
254:
255: # ------------------------------------------- Transfer profile into environment
256:
257: sub transfer_profile_to_env {
258: my ($lonidsdir,$handle)=@_;
259: my @profile;
260: {
1.448 albertel 261: open(my $idf,"$lonidsdir/$handle.id");
1.374 www 262: flock($idf,LOCK_SH);
263: @profile=<$idf>;
1.448 albertel 264: close($idf);
1.374 www 265: }
266: my $envi;
1.433 matthew 267: my %Remove;
1.374 www 268: for ($envi=0;$envi<=$#profile;$envi++) {
269: chomp($profile[$envi]);
270: my ($envname,$envvalue)=split(/=/,$profile[$envi]);
271: $ENV{$envname} = $envvalue;
1.433 matthew 272: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
273: if ($time < time-300) {
274: $Remove{$key}++;
275: }
276: }
277: }
1.446 albertel 278: $ENV{'user.environment'} = "$lonidsdir/$handle.id";
1.433 matthew 279: foreach my $expired_key (keys(%Remove)) {
280: &delenv($expired_key);
1.374 www 281: }
1.1 albertel 282: }
283:
1.5 www 284: # ---------------------------------------------------------- Append Environment
285:
286: sub appenv {
1.6 www 287: my %newenv=@_;
1.191 harris41 288: foreach (keys %newenv) {
1.35 www 289: if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
290: &logthis("<font color=blue>WARNING: ".
1.151 www 291: "Attempt to modify environment ".$_." to ".$newenv{$_}
292: .'</font>');
1.35 www 293: delete($newenv{$_});
294: } else {
295: $ENV{$_}=$newenv{$_};
296: }
1.191 harris41 297: }
1.95 www 298:
299: my $lockfh;
1.448 albertel 300: unless (open($lockfh,"$ENV{'user.environment'}")) {
301: return 'error: '.$!;
1.95 www 302: }
303: unless (flock($lockfh,LOCK_EX)) {
304: &logthis("<font color=blue>WARNING: ".
305: 'Could not obtain exclusive lock in appenv: '.$!);
1.448 albertel 306: close($lockfh);
1.95 www 307: return 'error: '.$!;
308: }
309:
1.6 www 310: my @oldenv;
311: {
1.448 albertel 312: my $fh;
313: unless (open($fh,"$ENV{'user.environment'}")) {
314: return 'error: '.$!;
315: }
316: @oldenv=<$fh>;
317: close($fh);
1.6 www 318: }
319: for (my $i=0; $i<=$#oldenv; $i++) {
320: chomp($oldenv[$i]);
1.9 www 321: if ($oldenv[$i] ne '') {
1.448 albertel 322: my ($name,$value)=split(/=/,$oldenv[$i]);
323: unless (defined($newenv{$name})) {
324: $newenv{$name}=$value;
325: }
1.9 www 326: }
1.6 www 327: }
328: {
1.448 albertel 329: my $fh;
330: unless (open($fh,">$ENV{'user.environment'}")) {
331: return 'error';
332: }
333: my $newname;
334: foreach $newname (keys %newenv) {
335: print $fh "$newname=$newenv{$newname}\n";
336: }
337: close($fh);
1.56 www 338: }
1.448 albertel 339:
340: close($lockfh);
1.56 www 341: return 'ok';
342: }
343: # ----------------------------------------------------- Delete from Environment
344:
345: sub delenv {
346: my $delthis=shift;
347: my %newenv=();
348: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
349: &logthis("<font color=blue>WARNING: ".
350: "Attempt to delete from environment ".$delthis);
351: return 'error';
352: }
353: my @oldenv;
354: {
1.448 albertel 355: my $fh;
356: unless (open($fh,"$ENV{'user.environment'}")) {
357: return 'error';
358: }
359: unless (flock($fh,LOCK_SH)) {
360: &logthis("<font color=blue>WARNING: ".
361: 'Could not obtain shared lock in delenv: '.$!);
362: close($fh);
363: return 'error: '.$!;
364: }
365: @oldenv=<$fh>;
366: close($fh);
1.56 www 367: }
368: {
1.448 albertel 369: my $fh;
370: unless (open($fh,">$ENV{'user.environment'}")) {
371: return 'error';
372: }
373: unless (flock($fh,LOCK_EX)) {
374: &logthis("<font color=blue>WARNING: ".
375: 'Could not obtain exclusive lock in delenv: '.$!);
376: close($fh);
377: return 'error: '.$!;
378: }
379: foreach (@oldenv) {
380: unless ($_=~/^$delthis/) { print $fh $_; }
381: }
382: close($fh);
1.5 www 383: }
384: return 'ok';
1.369 albertel 385: }
386:
387: # ------------------------------------------ Find out current server userload
388: # there is a copy in lond
389: sub userload {
390: my $numusers=0;
391: {
392: opendir(LONIDS,$perlvar{'lonIDsDir'});
393: my $filename;
394: my $curtime=time;
395: while ($filename=readdir(LONIDS)) {
396: if ($filename eq '.' || $filename eq '..') {next;}
1.404 albertel 397: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 398: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 399: }
400: closedir(LONIDS);
401: }
402: my $userloadpercent=0;
403: my $maxuserload=$perlvar{'lonUserLoadLim'};
404: if ($maxuserload) {
1.371 albertel 405: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 406: }
1.372 albertel 407: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 408: return $userloadpercent;
1.283 www 409: }
410:
411: # ------------------------------------------ Fight off request when overloaded
412:
413: sub overloaderror {
414: my ($r,$checkserver)=@_;
415: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
416: my $loadavg;
417: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 418: open(my $loadfile,'/proc/loadavg');
1.283 www 419: $loadavg=<$loadfile>;
420: $loadavg =~ s/\s.*//g;
1.285 matthew 421: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 422: close($loadfile);
1.283 www 423: } else {
424: $loadavg=&reply('load',$checkserver);
425: }
1.285 matthew 426: my $overload=$loadavg-100;
1.283 www 427: if ($overload>0) {
1.285 matthew 428: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 429: $r->log_error('Overload of '.$overload.' on '.$checkserver);
430: return 413;
431: }
432: return '';
1.5 www 433: }
1.1 albertel 434:
435: # ------------------------------ Find server with least workload from spare.tab
1.11 www 436:
1.1 albertel 437: sub spareserver {
1.370 albertel 438: my ($loadpercent,$userloadpercent) = @_;
1.1 albertel 439: my $tryserver;
440: my $spareserver='';
1.370 albertel 441: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
442: my $lowestserver=$loadpercent > $userloadpercent?
443: $loadpercent : $userloadpercent;
1.1 albertel 444: foreach $tryserver (keys %spareid) {
1.411 albertel 445: my $loadans=reply('load',$tryserver);
446: my $userloadans=reply('userload',$tryserver);
447: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
448: next; #didn't get a number from the server
449: }
450: my $answer;
451: if ($loadans =~ /\d/) {
452: if ($userloadans =~ /\d/) {
453: #both are numbers, pick the bigger one
454: $answer=$loadans > $userloadans?
455: $loadans : $userloadans;
456: } else {
457: $answer = $loadans;
458: }
459: } else {
460: $answer = $userloadans;
461: }
462: if (($answer =~ /\d/) && ($answer<$lowestserver)) {
463: $spareserver="http://$hostname{$tryserver}";
464: $lowestserver=$answer;
465: }
1.370 albertel 466: }
1.1 albertel 467: return $spareserver;
1.202 matthew 468: }
469:
470: # --------------------------------------------- Try to change a user's password
471:
472: sub changepass {
473: my ($uname,$udom,$currentpass,$newpass,$server)=@_;
474: $currentpass = &escape($currentpass);
475: $newpass = &escape($newpass);
476: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
477: $server);
478: if (! $answer) {
479: &logthis("No reply on password change request to $server ".
480: "by $uname in domain $udom.");
481: } elsif ($answer =~ "^ok") {
482: &logthis("$uname in $udom successfully changed their password ".
483: "on $server.");
484: } elsif ($answer =~ "^pwchange_failure") {
485: &logthis("$uname in $udom was unable to change their password ".
486: "on $server. The action was blocked by either lcpasswd ".
487: "or pwchange");
488: } elsif ($answer =~ "^non_authorized") {
489: &logthis("$uname in $udom did not get their password correct when ".
490: "attempting to change it on $server.");
491: } elsif ($answer =~ "^auth_mode_error") {
492: &logthis("$uname in $udom attempted to change their password despite ".
493: "not being locally or internally authenticated on $server.");
494: } elsif ($answer =~ "^unknown_user") {
495: &logthis("$uname in $udom attempted to change their password ".
496: "on $server but were unable to because $server is not ".
497: "their home server.");
498: } elsif ($answer =~ "^refused") {
499: &logthis("$server refused to change $uname in $udom password because ".
500: "it was sent an unencrypted request to change the password.");
501: }
502: return $answer;
1.1 albertel 503: }
504:
1.169 harris41 505: # ----------------------- Try to determine user's current authentication scheme
506:
507: sub queryauthenticate {
508: my ($uname,$udom)=@_;
509: if (($perlvar{'lonRole'} eq 'library') &&
510: ($udom eq $perlvar{'lonDefDomain'})) {
511: my $answer=reply("encrypt:currentauth:$udom:$uname",
512: $perlvar{'lonHostID'});
513: unless ($answer eq 'unknown_user' or $answer eq 'refused') {
514: if (length($answer)) {
515: return $answer;
516: }
517: else {
518: &logthis("User $uname at $udom lacks an authentication mechanism");
519: return 'no_host';
520: }
521: }
522: }
523:
524: my $tryserver;
525: foreach $tryserver (keys %libserv) {
526: if ($hostdom{$tryserver} eq $udom) {
527: my $answer=reply("encrypt:currentauth:$udom:$uname",$tryserver);
528: unless ($answer eq 'unknown_user' or $answer eq 'refused') {
529: if (length($answer)) {
530: return $answer;
531: }
532: else {
533: &logthis("User $uname at $udom lacks an authentication mechanism");
534: return 'no_host';
535: }
536: }
537: }
538: }
539: &logthis("User $uname at $udom lacks an authentication mechanism");
540: return 'no_host';
541: }
542:
1.1 albertel 543: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 544:
1.1 albertel 545: sub authenticate {
546: my ($uname,$upass,$udom)=@_;
1.12 www 547: $upass=escape($upass);
1.199 www 548: $uname=~s/\W//g;
1.1 albertel 549: if (($perlvar{'lonRole'} eq 'library') &&
550: ($udom eq $perlvar{'lonDefDomain'})) {
1.3 www 551: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$perlvar{'lonHostID'});
1.2 www 552: if ($answer =~ /authorized/) {
1.9 www 553: if ($answer eq 'authorized') {
554: &logthis("User $uname at $udom authorized by local server");
555: return $perlvar{'lonHostID'};
556: }
557: if ($answer eq 'non_authorized') {
558: &logthis("User $uname at $udom rejected by local server");
559: return 'no_host';
560: }
1.2 www 561: }
1.1 albertel 562: }
563:
564: my $tryserver;
565: foreach $tryserver (keys %libserv) {
566: if ($hostdom{$tryserver} eq $udom) {
1.10 www 567: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$tryserver);
1.1 albertel 568: if ($answer =~ /authorized/) {
1.9 www 569: if ($answer eq 'authorized') {
570: &logthis("User $uname at $udom authorized by $tryserver");
571: return $tryserver;
572: }
573: if ($answer eq 'non_authorized') {
574: &logthis("User $uname at $udom rejected by $tryserver");
575: return 'no_host';
576: }
1.1 albertel 577: }
578: }
1.9 www 579: }
580: &logthis("User $uname at $udom could not be authenticated");
1.1 albertel 581: return 'no_host';
582: }
583:
584: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 585:
1.1 albertel 586: sub homeserver {
1.230 stredwic 587: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 588: my $index="$uname:$udom";
1.426 albertel 589:
590: my ($result,$cached)=&is_cached(\%homecache,$index,'home',86400);
591: if (defined($cached)) { return $result; }
1.1 albertel 592: my $tryserver;
593: foreach $tryserver (keys %libserv) {
1.230 stredwic 594: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 595: exists($badServerCache{$tryserver}));
1.1 albertel 596: if ($hostdom{$tryserver} eq $udom) {
597: my $answer=reply("home:$udom:$uname",$tryserver);
598: if ($answer eq 'found') {
1.426 albertel 599: return &do_cache(\%homecache,$index,$tryserver,'home');
1.231 stredwic 600: } elsif ($answer eq 'no_host') {
601: $badServerCache{$tryserver}=1;
1.221 matthew 602: }
1.1 albertel 603: }
604: }
605: return 'no_host';
1.70 www 606: }
607:
608: # ------------------------------------- Find the usernames behind a list of IDs
609:
610: sub idget {
611: my ($udom,@ids)=@_;
612: my %returnhash=();
613:
614: my $tryserver;
615: foreach $tryserver (keys %libserv) {
616: if ($hostdom{$tryserver} eq $udom) {
617: my $idlist=join('&',@ids);
618: $idlist=~tr/A-Z/a-z/;
619: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
620: my @answer=();
1.76 www 621: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70 www 622: @answer=split(/\&/,$reply);
623: } ;
624: my $i;
625: for ($i=0;$i<=$#ids;$i++) {
626: if ($answer[$i]) {
627: $returnhash{$ids[$i]}=$answer[$i];
628: }
629: }
630: }
631: }
632: return %returnhash;
633: }
634:
635: # ------------------------------------- Find the IDs behind a list of usernames
636:
637: sub idrget {
638: my ($udom,@unames)=@_;
639: my %returnhash=();
1.191 harris41 640: foreach (@unames) {
1.70 www 641: $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191 harris41 642: }
1.70 www 643: return %returnhash;
644: }
645:
646: # ------------------------------- Store away a list of names and associated IDs
647:
648: sub idput {
649: my ($udom,%ids)=@_;
650: my %servers=();
1.191 harris41 651: foreach (keys %ids) {
1.70 www 652: my $uhom=&homeserver($_,$udom);
653: if ($uhom ne 'no_host') {
654: my $id=&escape($ids{$_});
655: $id=~tr/A-Z/a-z/;
656: my $unam=&escape($_);
657: if ($servers{$uhom}) {
658: $servers{$uhom}.='&'.$id.'='.$unam;
659: } else {
660: $servers{$uhom}=$id.'='.$unam;
661: }
662: &critical('put:'.$udom.':'.$unam.':environment:id='.$id,$uhom);
663: }
1.191 harris41 664: }
665: foreach (keys %servers) {
1.70 www 666: &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191 harris41 667: }
1.344 www 668: }
669:
670: # --------------------------------------------------- Assign a key to a student
671:
672: sub assign_access_key {
1.364 www 673: #
674: # a valid key looks like uname:udom#comments
675: # comments are being appended
676: #
677: my ($ckey,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1.344 www 678: $cdom=
679: $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
680: $cnum=
681: $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
682: $udom=$ENV{'user.name'} unless (defined($udom));
683: $uname=$ENV{'user.domain'} unless (defined($uname));
1.345 www 684: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.364 www 685: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
686: ($existing{$ckey}=~/^$uname\:$udom\#(.*)$/)) {
687: # assigned to this person
688: # - this should not happen,
1.345 www 689: # unless something went wrong
690: # the first time around
691: # ready to assign
1.364 www 692: $logentry=$1.'; '.$logentry;
693: if (&put('accesskey',{$ckey=>$uname.':'.$udom.'#'.$logentry},
694: $cdom,$cnum) eq 'ok') {
1.345 www 695: # key now belongs to user
1.346 www 696: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 697: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
698: &appenv('environment.'.$envkey => $ckey);
699: return 'ok';
700: } else {
701: return
702: 'error: Count not permanently assign key, will need to be re-entered later.';
703: }
704: } else {
705: return 'error: Could not assign key, try again later.';
706: }
1.364 www 707: } elsif (!$existing{$ckey}) {
1.345 www 708: # the key does not exist
709: return 'error: The key does not exist';
710: } else {
711: # the key is somebody else's
712: return 'error: The key is already in use';
713: }
1.344 www 714: }
715:
1.364 www 716: # ------------------------------------------ put an additional comment on a key
717:
718: sub comment_access_key {
719: #
720: # a valid key looks like uname:udom#comments
721: # comments are being appended
722: #
723: my ($ckey,$cdom,$cnum,$logentry)=@_;
724: $cdom=
725: $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
726: $cnum=
727: $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
728: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
729: if ($existing{$ckey}) {
730: $existing{$ckey}.='; '.$logentry;
731: # ready to assign
1.367 www 732: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 733: $cdom,$cnum) eq 'ok') {
734: return 'ok';
735: } else {
736: return 'error: Count not store comment.';
737: }
738: } else {
739: # the key does not exist
740: return 'error: The key does not exist';
741: }
742: }
743:
1.344 www 744: # ------------------------------------------------------ Generate a set of keys
745:
746: sub generate_access_keys {
1.364 www 747: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 748: $cdom=
749: $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
750: $cnum=
751: $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 752: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 753: unless (($cdom) && ($cnum)) { return 0; }
754: if ($number>10000) { return 0; }
755: sleep(2); # make sure don't get same seed twice
756: srand(time()^($$+($$<<15))); # from "Programming Perl"
757: my $total=0;
758: for (my $i=1;$i<=$number;$i++) {
759: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
760: sprintf("%lx",int(100000*rand)).'-'.
761: sprintf("%lx",int(100000*rand));
762: $newkey=~s/1/g/g; # folks mix up 1 and l
763: $newkey=~s/0/h/g; # and also 0 and O
764: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
765: if ($existing{$newkey}) {
766: $i--;
767: } else {
1.364 www 768: if (&put('accesskeys',
769: { $newkey => '# generated '.localtime().
770: ' by '.$ENV{'user.name'}.'@'.$ENV{'user.domain'}.
771: '; '.$logentry },
772: $cdom,$cnum) eq 'ok') {
1.344 www 773: $total++;
774: }
775: }
776: }
777: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
778: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
779: return $total;
780: }
781:
782: # ------------------------------------------------------- Validate an accesskey
783:
784: sub validate_access_key {
785: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
786: $cdom=
787: $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
788: $cnum=
789: $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
790: $udom=$ENV{'user.name'} unless (defined($udom));
791: $uname=$ENV{'user.domain'} unless (defined($uname));
1.345 www 792: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.364 www 793: return ($existing{$ckey}=~/^$uname\:$udom\#/);
1.70 www 794: }
795:
796: # ------------------------------------- Find the section of student in a course
1.298 matthew 797:
798: sub getsection {
799: my ($udom,$unam,$courseid)=@_;
800: $courseid=~s/\_/\//g;
801: $courseid=~s/^(\w)/\/$1/;
802: my %Pending;
803: my %Expired;
804: #
805: # Each role can either have not started yet (pending), be active,
806: # or have expired.
807: #
808: # If there is an active role, we are done.
809: #
810: # If there is more than one role which has not started yet,
811: # choose the one which will start sooner
812: # If there is one role which has not started yet, return it.
813: #
814: # If there is more than one expired role, choose the one which ended last.
815: # If there is a role which has expired, return it.
816: #
817: foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
818: &homeserver($unam,$udom)))) {
819: my ($key,$value)=split(/\=/,$_);
820: $key=&unescape($key);
821: next if ($key !~/^$courseid(?:\/)*(\w+)*\_st$/);
822: my $section=$1;
823: if ($key eq $courseid.'_st') { $section=''; }
824: my ($dummy,$end,$start)=split(/\_/,&unescape($value));
825: my $now=time;
826: if (defined($end) && ($now > $end)) {
827: $Expired{$end}=$section;
828: next;
829: }
830: if (defined($start) && ($now < $start)) {
831: $Pending{$start}=$section;
832: next;
833: }
834: return $section;
835: }
836: #
837: # Presumedly there will be few matching roles from the above
838: # loop and the sorting time will be negligible.
839: if (scalar(keys(%Pending))) {
840: my ($time) = sort {$a <=> $b} keys(%Pending);
841: return $Pending{$time};
842: }
843: if (scalar(keys(%Expired))) {
844: my @sorted = sort {$a <=> $b} keys(%Expired);
845: my $time = pop(@sorted);
846: return $Expired{$time};
847: }
848: return '-1';
849: }
1.70 www 850:
1.416 albertel 851: sub devalidate_cache {
1.428 albertel 852: my ($cache,$id,$name) = @_;
1.417 albertel 853: delete $$cache{$id.'.time'};
854: delete $$cache{$id};
1.442 albertel 855: my $filename=$perlvar{'lonDaemons'}.'/tmp/lonnet_internal_cache_'.$name.".db";
1.428 albertel 856: open(DB,"$filename.lock");
857: flock(DB,LOCK_EX);
858: my %hash;
859: if (tie(%hash,'GDBM_File',$filename,&GDBM_WRCREAT(),0640)) {
1.442 albertel 860: eval <<'EVALBLOCK';
861: delete($hash{$id});
862: delete($hash{$id.'.time'});
863: EVALBLOCK
864: if ($@) {
865: &logthis("<font color='red'>devalidate_cache blew up :$@:$name</font>");
866: unlink($filename);
867: }
1.428 albertel 868: } else {
1.442 albertel 869: if (-e $filename) {
870: &logthis("Unable to tie hash (devalidate cache): $name");
871: unlink($filename);
872: }
1.428 albertel 873: }
874: untie(%hash);
875: flock(DB,LOCK_UN);
876: close(DB);
1.416 albertel 877: }
878:
879: sub is_cached {
1.425 albertel 880: my ($cache,$id,$name,$time) = @_;
1.420 albertel 881: if (!$time) { $time=300; }
1.416 albertel 882: if (!exists($$cache{$id.'.time'})) {
1.428 albertel 883: &load_cache_item($cache,$name,$id);
1.425 albertel 884: }
885: if (!exists($$cache{$id.'.time'})) {
886: # &logthis("Didn't find $id");
1.417 albertel 887: return (undef,undef);
1.416 albertel 888: } else {
1.425 albertel 889: if (time-($$cache{$id.'.time'})>$time) {
1.435 www 890: # &logthis("Devalidating $id - ".time-($$cache{$id.'.time'}));
1.428 albertel 891: &devalidate_cache($cache,$id,$name);
1.417 albertel 892: return (undef,undef);
1.416 albertel 893: }
894: }
1.417 albertel 895: return ($$cache{$id},1);
1.416 albertel 896: }
897:
898: sub do_cache {
1.425 albertel 899: my ($cache,$id,$value,$name) = @_;
1.416 albertel 900: $$cache{$id.'.time'}=time;
1.425 albertel 901: $$cache{$id}=$value;
1.428 albertel 902: # &logthis("Caching $id as :$value:");
903: &save_cache_item($cache,$name,$id);
1.416 albertel 904: # do_cache implictly return the set value
1.425 albertel 905: $$cache{$id};
906: }
907:
1.428 albertel 908: sub save_cache_item {
909: my ($cache,$name,$id)=@_;
910: my $starttime=&Time::HiRes::time();
1.442 albertel 911: # &logthis("Saving :$name:$id");
1.428 albertel 912: my %hash;
1.442 albertel 913: my $filename=$perlvar{'lonDaemons'}.'/tmp/lonnet_internal_cache_'.$name.".db";
1.428 albertel 914: open(DB,"$filename.lock");
915: flock(DB,LOCK_EX);
916: if (tie(%hash,'GDBM_File',$filename,&GDBM_WRCREAT(),0640)) {
1.442 albertel 917: eval <<'EVALBLOCK';
918: $hash{$id.'.time'}=$$cache{$id.'.time'};
919: $hash{$id}=freeze({'item'=>$$cache{$id}});
920: EVALBLOCK
921: if ($@) {
922: &logthis("<font color='red'>save_cache blew up :$@:$name</font>");
923: unlink($filename);
924: }
1.428 albertel 925: } else {
1.442 albertel 926: if (-e $filename) {
1.445 www 927: &logthis("Unable to tie hash (save cache item): $name ($!)");
1.442 albertel 928: unlink($filename);
929: }
1.428 albertel 930: }
931: untie(%hash);
932: flock(DB,LOCK_UN);
933: close(DB);
934: # &logthis("save_cache_item $name took ".(&Time::HiRes::time()-$starttime));
935: }
936:
937: sub load_cache_item {
938: my ($cache,$name,$id)=@_;
939: my $starttime=&Time::HiRes::time();
940: # &logthis("Before Loading $name for $id size is ".scalar(%$cache));
941: my %hash;
1.442 albertel 942: my $filename=$perlvar{'lonDaemons'}.'/tmp/lonnet_internal_cache_'.$name.".db";
1.428 albertel 943: open(DB,"$filename.lock");
944: flock(DB,LOCK_SH);
945: if (tie(%hash,'GDBM_File',$filename,&GDBM_READER(),0640)) {
1.442 albertel 946: eval <<'EVALBLOCK';
947: if (!%$cache) {
948: my $count;
949: while (my ($key,$value)=each(%hash)) {
950: $count++;
951: if ($key =~ /\.time$/) {
952: $$cache{$key}=$value;
953: } else {
954: my $hashref=thaw($value);
955: $$cache{$key}=$hashref->{'item'};
956: }
1.428 albertel 957: }
1.442 albertel 958: # &logthis("Initial load: $count");
959: } else {
960: my $hashref=thaw($hash{$id});
961: $$cache{$id}=$hashref->{'item'};
962: $$cache{$id.'.time'}=$hash{$id.'.time'};
1.428 albertel 963: }
1.442 albertel 964: EVALBLOCK
965: if ($@) {
966: &logthis("<font color='red'>load_cache blew up :$@:$name</font>");
967: unlink($filename);
968: }
969: } else {
970: if (-e $filename) {
1.445 www 971: &logthis("Unable to tie hash (load cache item): $name ($!)");
1.442 albertel 972: unlink($filename);
1.428 albertel 973: }
974: }
975: untie(%hash);
976: flock(DB,LOCK_UN);
977: close(DB);
978: # &logthis("After Loading $name size is ".scalar(%$cache));
979: # &logthis("load_cache_item $name took ".(&Time::HiRes::time()-$starttime));
980: }
981:
1.70 www 982: sub usection {
983: my ($udom,$unam,$courseid)=@_;
1.416 albertel 984: my $hashid="$udom:$unam:$courseid";
985:
1.425 albertel 986: my ($result,$cached)=&is_cached(\%usectioncache,$hashid,'usection');
1.417 albertel 987: if (defined($cached)) { return $result; }
1.70 www 988: $courseid=~s/\_/\//g;
989: $courseid=~s/^(\w)/\/$1/;
1.191 harris41 990: foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
991: &homeserver($unam,$udom)))) {
1.70 www 992: my ($key,$value)=split(/\=/,$_);
993: $key=&unescape($key);
994: if ($key=~/^$courseid(?:\/)*(\w+)*\_st$/) {
995: my $section=$1;
996: if ($key eq $courseid.'_st') { $section=''; }
997: my ($dummy,$end,$start)=split(/\_/,&unescape($value));
998: my $now=time;
999: my $notactive=0;
1000: if ($start) {
1001: if ($now<$start) { $notactive=1; }
1002: }
1003: if ($end) {
1004: if ($now>$end) { $notactive=1; }
1005: }
1.416 albertel 1006: unless ($notactive) {
1.425 albertel 1007: return &do_cache(\%usectioncache,$hashid,$section,'usection');
1.416 albertel 1008: }
1.70 www 1009: }
1.191 harris41 1010: }
1.425 albertel 1011: return &do_cache(\%usectioncache,$hashid,'-1','usection');
1.70 www 1012: }
1013:
1014: # ------------------------------------- Read an entry from a user's environment
1015:
1016: sub userenvironment {
1017: my ($udom,$unam,@what)=@_;
1018: my %returnhash=();
1019: my @answer=split(/\&/,
1020: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
1021: &homeserver($unam,$udom)));
1022: my $i;
1023: for ($i=0;$i<=$#what;$i++) {
1024: $returnhash{$what[$i]}=&unescape($answer[$i]);
1025: }
1026: return %returnhash;
1.1 albertel 1027: }
1028:
1.263 www 1029: # -------------------------------------------------------------------- New chat
1030:
1031: sub chatsend {
1032: my ($newentry,$anon)=@_;
1033: my $cnum=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
1034: my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
1035: my $chome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1036: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1037: &escape($ENV{'user.domain'}.':'.$ENV{'user.name'}.':'.$anon.':'.
1038: &escape($newentry)),$chome);
1.292 www 1039: }
1040:
1041: # ------------------------------------------ Find current version of a resource
1042:
1043: sub getversion {
1044: my $fname=&clutter(shift);
1045: unless ($fname=~/^\/res\//) { return -1; }
1046: return ¤tversion(&filelocation('',$fname));
1047: }
1048:
1049: sub currentversion {
1050: my $fname=shift;
1.440 www 1051: my ($result,$cached)=&is_cached(\%resversioncache,$fname,'resversion',600);
1052: if (defined($cached)) { return $result; }
1.292 www 1053: my $author=$fname;
1054: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1055: my ($udom,$uname)=split(/\//,$author);
1056: my $home=homeserver($uname,$udom);
1057: if ($home eq 'no_host') {
1058: return -1;
1059: }
1060: my $answer=reply("currentversion:$fname",$home);
1061: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1062: return -1;
1063: }
1.440 www 1064: return &do_cache(\%resversioncache,$fname,$answer,'resversion');
1.263 www 1065: }
1066:
1.1 albertel 1067: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1068:
1.1 albertel 1069: sub subscribe {
1070: my $fname=shift;
1.312 www 1071: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.1 albertel 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);
1.335 albertel 1076: if ($home eq 'no_host') {
1077: return 'not_found';
1.1 albertel 1078: }
1079: my $answer=reply("sub:$fname",$home);
1.64 www 1080: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1081: $answer.=' by '.$home;
1082: }
1.1 albertel 1083: return $answer;
1084: }
1085:
1.8 www 1086: # -------------------------------------------------------------- Replicate file
1087:
1088: sub repcopy {
1089: my $filename=shift;
1.23 www 1090: $filename=~s/\/+/\//g;
1.214 www 1091: if ($filename=~/^\/home\/httpd\/html\/adm\//) { return OK; }
1.8 www 1092: my $transname="$filename.in.transfer";
1.17 www 1093: if ((-e $filename) || (-e $transname)) { return OK; }
1.8 www 1094: my $remoteurl=subscribe($filename);
1.64 www 1095: if ($remoteurl =~ /^con_lost by/) {
1096: &logthis("Subscribe returned $remoteurl: $filename");
1.8 www 1097: return HTTP_SERVICE_UNAVAILABLE;
1098: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1099: #&logthis("Subscribe returned not_found: $filename");
1.8 www 1100: return HTTP_NOT_FOUND;
1.64 www 1101: } elsif ($remoteurl =~ /^rejected by/) {
1102: &logthis("Subscribe returned $remoteurl: $filename");
1.8 www 1103: return FORBIDDEN;
1.20 www 1104: } elsif ($remoteurl eq 'directory') {
1105: return OK;
1.8 www 1106: } else {
1.290 www 1107: my $author=$filename;
1108: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1109: my ($udom,$uname)=split(/\//,$author);
1110: my $home=homeserver($uname,$udom);
1111: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1112: my @parts=split(/\//,$filename);
1113: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1114: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1115: &logthis("Malconfiguration for replication: $filename");
1116: return HTTP_BAD_REQUEST;
1117: }
1118: my $count;
1119: for ($count=5;$count<$#parts;$count++) {
1120: $path.="/$parts[$count]";
1121: if ((-e $path)!=1) {
1122: mkdir($path,0777);
1123: }
1124: }
1125: my $ua=new LWP::UserAgent;
1126: my $request=new HTTP::Request('GET',"$remoteurl");
1127: my $response=$ua->request($request,$transname);
1128: if ($response->is_error()) {
1129: unlink($transname);
1130: my $message=$response->status_line;
1.12 www 1131: &logthis("<font color=blue>WARNING:"
1132: ." LWP get: $message: $filename</font>");
1.8 www 1133: return HTTP_SERVICE_UNAVAILABLE;
1134: } else {
1.16 www 1135: if ($remoteurl!~/\.meta$/) {
1136: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1137: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1138: if ($mresponse->is_error()) {
1139: unlink($filename.'.meta');
1140: &logthis(
1141: "<font color=yellow>INFO: No metadata: $filename</font>");
1142: }
1143: }
1.8 www 1144: rename($transname,$filename);
1145: return OK;
1146: }
1.290 www 1147: }
1.8 www 1148: }
1.330 www 1149: }
1150:
1151: # ------------------------------------------------ Get server side include body
1152: sub ssi_body {
1.381 albertel 1153: my ($filelink,%form)=@_;
1.330 www 1154: my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381 albertel 1155: &ssi($filelink,%form));
1.451 ! albertel 1156: $output=~s/^.*?\<body[^\>]*\>//si;
! 1157: $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.331 www 1158: $output=~
1159: s/\/\/ BEGIN LON\-CAPA Internal.+\/\/ END LON\-CAPA Internal\s//gs;
1.330 www 1160: return $output;
1.8 www 1161: }
1162:
1.15 www 1163: # --------------------------------------------------------- Server Side Include
1164:
1165: sub ssi {
1166:
1.23 www 1167: my ($fn,%form)=@_;
1.15 www 1168:
1169: my $ua=new LWP::UserAgent;
1.23 www 1170:
1171: my $request;
1172:
1173: if (%form) {
1174: $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201 albertel 1175: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23 www 1176: } else {
1177: $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
1178: }
1179:
1.15 www 1180: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1181: my $response=$ua->request($request);
1182:
1.324 www 1183: return $response->content;
1184: }
1185:
1186: sub externalssi {
1187: my ($url)=@_;
1188: my $ua=new LWP::UserAgent;
1189: my $request=new HTTP::Request('GET',$url);
1190: my $response=$ua->request($request);
1.15 www 1191: return $response->content;
1192: }
1.254 www 1193:
1194: # ------- Add a token to a remote URI's query string to vouch for access rights
1195:
1196: sub tokenwrapper {
1197: my $uri=shift;
1.259 www 1198: $uri=~s/^http\:\/\/([^\/]+)//;
1199: $uri=~s/^\///;
1200: $ENV{'user.environment'}=~/\/([^\/]+)\.id/;
1201: my $token=$1;
1202: if ($uri=~/^uploaded\/([^\/]+)\/([^\/]+)\/([^\/]+)(\?\.*)*$/) {
1203: &appenv('userfile.'.$1.'/'.$2.'/'.$3 => $ENV{'request.course.id'});
1204: return 'http://'.$hostname{ &homeserver($2,$1)}.'/'.$uri.
1.304 www 1205: (($uri=~/\?/)?'&':'?').'token='.$token.
1206: '&tokenissued='.$perlvar{'lonHostID'};
1.259 www 1207: } else {
1208: return '/adm/notfound.html';
1209: }
1.254 www 1210: }
1211:
1.257 www 1212: # --------------- Take an uploaded file and put it into the userfiles directory
1.259 www 1213: # input: name of form element, coursedoc=1 means this is for the course
1.257 www 1214: # output: url of file in userspace
1215:
1216: sub userfileupload {
1.259 www 1217: my ($formname,$coursedoc)=@_;
1.257 www 1218: my $fname=$ENV{'form.'.$formname.'.filename'};
1.315 www 1219: # Replace Windows backslashes by forward slashes
1.257 www 1220: $fname=~s/\\/\//g;
1.315 www 1221: # Get rid of everything but the actual filename
1.257 www 1222: $fname=~s/^.*\/([^\/]+)$/$1/;
1.315 www 1223: # Replace spaces by underscores
1224: $fname=~s/\s+/\_/g;
1225: # Replace all other weird characters by nothing
1.317 www 1226: $fname=~s/[^\w\.\-]//g;
1.315 www 1227: # See if there is anything left
1.257 www 1228: unless ($fname) { return 'error: no uploaded file'; }
1229: chop($ENV{'form.'.$formname});
1.258 www 1230: # Create the directory if not present
1.259 www 1231: my $docuname='';
1232: my $docudom='';
1233: my $docuhome='';
1234: if ($coursedoc) {
1235: $docuname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
1236: $docudom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
1237: $docuhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1238: } else {
1239: $docuname=$ENV{'user.name'};
1240: $docudom=$ENV{'user.domain'};
1241: $docuhome=$ENV{'user.home'};
1242: }
1.271 www 1243: return
1244: &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname);
1245: }
1246:
1247: sub finishuserfileupload {
1248: my ($docuname,$docudom,$docuhome,$formname,$fname)=@_;
1.259 www 1249: my $path=$docudom.'/'.$docuname.'/';
1.258 www 1250: my $filepath=$perlvar{'lonDocRoot'};
1.259 www 1251: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 1252: my $count;
1253: for ($count=4;$count<=$#parts;$count++) {
1254: $filepath.="/$parts[$count]";
1255: if ((-e $filepath)!=1) {
1256: mkdir($filepath,0777);
1257: }
1258: }
1259: # Save the file
1260: {
1.448 albertel 1261: open(my $fh,'>'.$filepath.'/'.$fname);
1.258 www 1262: print $fh $ENV{'form.'.$formname};
1.448 albertel 1263: close($fh);
1.258 www 1264: }
1.259 www 1265: # Notify homeserver to grep it
1266: #
1.295 www 1267:
1268: my $fetchresult=
1269: &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$fname,$docuhome);
1270: if ($fetchresult eq 'ok') {
1.259 www 1271: #
1.258 www 1272: # Return the URL to it
1.263 www 1273: return '/uploaded/'.$path.$fname;
1274: } else {
1.295 www 1275: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$fname.
1276: ' to host '.$docuhome.': '.$fetchresult);
1.263 www 1277: return '/adm/notfound.html';
1278: }
1.257 www 1279: }
1.15 www 1280:
1.14 www 1281: # ------------------------------------------------------------------------- Log
1282:
1283: sub log {
1284: my ($dom,$nam,$hom,$what)=@_;
1.47 www 1285: return critical("log:$dom:$nam:$what",$hom);
1.157 www 1286: }
1287:
1288: # ------------------------------------------------------------------ Course Log
1.352 www 1289: #
1290: # This routine flushes several buffers of non-mission-critical nature
1291: #
1.157 www 1292:
1293: sub flushcourselogs {
1.352 www 1294: &logthis('Flushing log buffers');
1295: #
1296: # course logs
1297: # This is a log of all transactions in a course, which can be used
1298: # for data mining purposes
1299: #
1300: # It also collects the courseid database, which lists last transaction
1301: # times and course titles for all courseids
1302: #
1303: my %courseidbuffer=();
1.191 harris41 1304: foreach (keys %courselogs) {
1.157 www 1305: my $crsid=$_;
1.352 www 1306: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 1307: &escape($courselogs{$crsid}),
1308: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 1309: delete $courselogs{$crsid};
1310: } else {
1311: &logthis('Failed to flush log buffer for '.$crsid);
1312: if (length($courselogs{$crsid})>40000) {
1313: &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
1314: " exceeded maximum size, deleting.</font>");
1315: delete $courselogs{$crsid};
1316: }
1.352 www 1317: }
1318: if ($courseidbuffer{$coursehombuf{$crsid}}) {
1319: $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1320: &escape($crsid).'='.&escape($coursedescrbuf{$crsid});
1321: } else {
1322: $courseidbuffer{$coursehombuf{$crsid}}=
1323: &escape($crsid).'='.&escape($coursedescrbuf{$crsid});
1324: }
1.191 harris41 1325: }
1.352 www 1326: #
1327: # Write course id database (reverse lookup) to homeserver of courses
1328: # Is used in pickcourse
1329: #
1330: foreach (keys %courseidbuffer) {
1.353 www 1331: &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352 www 1332: }
1333: #
1334: # File accesses
1335: # Writes to the dynamic metadata of resources to get hit counts, etc.
1336: #
1.449 matthew 1337: foreach my $entry (keys(%accesshash)) {
1338: my ($dom,$name,undef,$type)=($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1339: if ($type eq 'count'){
1.450 matthew 1340: my $value = $accesshash{$entry};
1341: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
1342: my %temphash=($url => $value);
1.449 matthew 1343: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
1344: if ($result eq 'ok') {
1345: delete $accesshash{$entry};
1346: } elsif ($result eq 'unknown_cmd') {
1347: # Target server has old code running on it.
1.450 matthew 1348: my %temphash=($entry => $value);
1.449 matthew 1349: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1350: delete $accesshash{$entry};
1351: }
1352: }
1353: } else {
1.450 matthew 1354: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 1355: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1356: delete $accesshash{$entry};
1357: }
1.185 www 1358: }
1.191 harris41 1359: }
1.352 www 1360: #
1361: # Roles
1362: # Reverse lookup of user roles for course faculty/staff and co-authorship
1363: #
1.349 www 1364: foreach (keys %userrolehash) {
1365: my $entry=$_;
1.351 www 1366: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 1367: split(/\:/,$entry);
1368: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 1369: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 1370: $rudom,$runame) eq 'ok') {
1371: delete $userrolehash{$entry};
1372: }
1373: }
1.186 www 1374: $dumpcount++;
1.157 www 1375: }
1376:
1377: sub courselog {
1378: my $what=shift;
1.158 www 1379: $what=time.':'.$what;
1.157 www 1380: unless ($ENV{'request.course.id'}) { return ''; }
1.188 www 1381: $coursedombuf{$ENV{'request.course.id'}}=
1.352 www 1382: $ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
1383: $coursenumbuf{$ENV{'request.course.id'}}=
1.188 www 1384: $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
1385: $coursehombuf{$ENV{'request.course.id'}}=
1386: $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.352 www 1387: $coursedescrbuf{$ENV{'request.course.id'}}=
1388: $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
1.157 www 1389: if (defined $courselogs{$ENV{'request.course.id'}}) {
1390: $courselogs{$ENV{'request.course.id'}}.='&'.$what;
1391: } else {
1392: $courselogs{$ENV{'request.course.id'}}.=$what;
1393: }
1.450 matthew 1394: # if (length($courselogs{$ENV{'request.course.id'}})>4048) {
1395: if (length($courselogs{$ENV{'request.course.id'}})>48) {
1.157 www 1396: &flushcourselogs();
1397: }
1.158 www 1398: }
1399:
1400: sub courseacclog {
1401: my $fnsymb=shift;
1402: unless ($ENV{'request.course.id'}) { return ''; }
1403: my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'};
1.408 www 1404: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|page)$/) {
1.187 www 1405: $what.=':POST';
1.191 harris41 1406: foreach (keys %ENV) {
1.158 www 1407: if ($_=~/^form\.(.*)/) {
1408: $what.=':'.$1.'='.$ENV{$_};
1409: }
1.191 harris41 1410: }
1.158 www 1411: }
1412: &courselog($what);
1.149 www 1413: }
1414:
1.185 www 1415: sub countacc {
1416: my $url=&declutter(shift);
1417: unless ($ENV{'request.course.id'}) { return ''; }
1418: $accesshash{$ENV{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 1419: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 1420: $accesshash{$key}++;
1.185 www 1421: }
1.349 www 1422:
1.361 www 1423: sub linklog {
1424: my ($from,$to)=@_;
1425: $from=&declutter($from);
1426: $to=&declutter($to);
1427: $accesshash{$from.'___'.$to.'___comefrom'}=1;
1428: $accesshash{$to.'___'.$from.'___goto'}=1;
1429: }
1430:
1.349 www 1431: sub userrolelog {
1432: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1433: if (($trole=~/^ca/) || ($trole=~/^in/) ||
1434: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1435: ($trole=~/^cr/)) {
1.350 www 1436: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
1437: $userrolehash
1438: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 1439: =$tend.':'.$tstart;
1440: }
1.351 www 1441: }
1442:
1443: sub get_course_adv_roles {
1444: my $cid=shift;
1445: $cid=$ENV{'request.course.id'} unless (defined($cid));
1446: my %coursehash=&coursedescription($cid);
1447: my %returnhash=();
1448: my %dumphash=
1449: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
1450: my $now=time;
1451: foreach (keys %dumphash) {
1452: my ($tend,$tstart)=split(/\:/,$dumphash{$_});
1453: if (($tstart) && ($tstart<0)) { next; }
1454: if (($tend) && ($tend<$now)) { next; }
1455: if (($tstart) && ($now<$tstart)) { next; }
1456: my ($role,$username,$domain,$section)=split(/\:/,$_);
1457: my $key=&plaintext($role);
1458: if ($section) { $key.=' (Sec/Grp '.$section.')'; }
1459: if ($returnhash{$key}) {
1460: $returnhash{$key}.=','.$username.':'.$domain;
1461: } else {
1462: $returnhash{$key}=$username.':'.$domain;
1463: }
1.400 www 1464: }
1465: return %returnhash;
1466: }
1467:
1468: sub get_my_roles {
1469: my ($uname,$udom)=@_;
1470: unless (defined($uname)) { $uname=$ENV{'user.name'}; }
1471: unless (defined($udom)) { $udom=$ENV{'user.domain'}; }
1472: my %dumphash=
1473: &dump('nohist_userroles',$udom,$uname);
1474: my %returnhash=();
1475: my $now=time;
1476: foreach (keys %dumphash) {
1477: my ($tend,$tstart)=split(/\:/,$dumphash{$_});
1478: if (($tstart) && ($tstart<0)) { next; }
1479: if (($tend) && ($tend<$now)) { next; }
1480: if (($tstart) && ($now<$tstart)) { next; }
1481: my ($role,$username,$domain,$section)=split(/\:/,$_);
1482: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373 www 1483: }
1484: return %returnhash;
1.399 www 1485: }
1486:
1487: # ----------------------------------------------------- Frontpage Announcements
1488: #
1489: #
1490:
1491: sub postannounce {
1492: my ($server,$text)=@_;
1493: unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
1494: unless ($text=~/\w/) { $text=''; }
1495: return &reply('setannounce:'.&escape($text),$server);
1496: }
1497:
1498: sub getannounce {
1.448 albertel 1499:
1500: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 1501: my $announcement='';
1502: while (<$fh>) { $announcement .=$_; }
1.448 albertel 1503: close($fh);
1.399 www 1504: if ($announcement=~/\w/) {
1505: return
1506: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1507: '<tr><td bgcolor="#FFFFFF"><pre>'.$announcement.'</pre></td></tr></table>';
1508: } else {
1509: return '';
1510: }
1511: } else {
1512: return '';
1513: }
1.351 www 1514: }
1.353 www 1515:
1516: # ---------------------------------------------------------- Course ID routines
1517: # Deal with domain's nohist_courseid.db files
1518: #
1519:
1520: sub courseidput {
1521: my ($domain,$what,$coursehome)=@_;
1522: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
1523: }
1524:
1525: sub courseiddump {
1526: my ($domfilter,$descfilter,$sincefilter)=@_;
1527: my %returnhash=();
1.355 www 1528: unless ($domfilter) { $domfilter=''; }
1.353 www 1529: foreach my $tryserver (keys %libserv) {
1.355 www 1530: if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.353 www 1531: foreach (
1532: split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.354 www 1533: $sincefilter.':'.&escape($descfilter),
1534: $tryserver))) {
1.353 www 1535: my ($key,$value)=split(/\=/,$_);
1536: if (($key) && ($value)) {
1537: $returnhash{&unescape($key)}=&unescape($value);
1538: }
1539: }
1540:
1541: }
1542: }
1543: return %returnhash;
1544: }
1545:
1546: #
1.149 www 1547: # ----------------------------------------------------------- Check out an item
1548:
1549: sub checkout {
1550: my ($symb,$tuname,$tudom,$tcrsid)=@_;
1551: my $now=time;
1552: my $lonhost=$perlvar{'lonHostID'};
1553: my $infostr=&escape(
1.234 www 1554: 'CHECKOUTTOKEN&'.
1.149 www 1555: $tuname.'&'.
1556: $tudom.'&'.
1557: $tcrsid.'&'.
1558: $symb.'&'.
1559: $now.'&'.$ENV{'REMOTE_ADDR'});
1560: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 1561: if ($token=~/^error\:/) {
1562: &logthis("<font color=blue>WARNING: ".
1563: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
1564: "</font>");
1565: return '';
1566: }
1567:
1.149 www 1568: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
1569: $token=~tr/a-z/A-Z/;
1570:
1.153 www 1571: my %infohash=('resource.0.outtoken' => $token,
1572: 'resource.0.checkouttime' => $now,
1573: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 1574:
1575: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
1576: return '';
1.151 www 1577: } else {
1578: &logthis("<font color=blue>WARNING: ".
1579: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
1580: "</font>");
1.149 www 1581: }
1582:
1583: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
1584: &escape('Checkout '.$infostr.' - '.
1585: $token)) ne 'ok') {
1586: return '';
1.151 www 1587: } else {
1588: &logthis("<font color=blue>WARNING: ".
1589: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
1590: "</font>");
1.149 www 1591: }
1.151 www 1592: return $token;
1.149 www 1593: }
1594:
1595: # ------------------------------------------------------------ Check in an item
1596:
1597: sub checkin {
1598: my $token=shift;
1.150 www 1599: my $now=time;
1600: my ($ta,$tb,$lonhost)=split(/\*/,$token);
1601: $lonhost=~tr/A-Z/a-z/;
1602: my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb;
1603: $dtoken=~s/\W/\_/g;
1.234 www 1604: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 1605: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
1606:
1.154 www 1607: unless (($tuname) && ($tudom)) {
1608: &logthis('Check in '.$token.' ('.$dtoken.') failed');
1609: return '';
1610: }
1611:
1612: unless (&allowed('mgr',$tcrsid)) {
1613: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1614: $ENV{'user.name'}.' - '.$ENV{'user.domain'});
1615: return '';
1616: }
1617:
1.153 www 1618: my %infohash=('resource.0.intoken' => $token,
1619: 'resource.0.checkintime' => $now,
1620: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 1621:
1622: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
1623: return '';
1624: }
1625:
1626: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
1627: &escape('Checkin - '.$token)) ne 'ok') {
1628: return '';
1629: }
1630:
1631: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 1632: }
1633:
1634: # --------------------------------------------- Set Expire Date for Spreadsheet
1635:
1636: sub expirespread {
1637: my ($uname,$udom,$stype,$usymb)=@_;
1638: my $cid=$ENV{'request.course.id'};
1639: if ($cid) {
1640: my $now=time;
1641: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1642: return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
1643: $ENV{'course.'.$cid.'.num'}.
1644: ':nohist_expirationdates:'.
1645: &escape($key).'='.$now,
1646: $ENV{'course.'.$cid.'.home'})
1647: }
1648: return 'ok';
1.14 www 1649: }
1650:
1.109 www 1651: # ----------------------------------------------------- Devalidate Spreadsheets
1652:
1653: sub devalidate {
1.325 www 1654: my ($symb,$uname,$udom)=@_;
1.109 www 1655: my $cid=$ENV{'request.course.id'};
1656: if ($cid) {
1.391 matthew 1657: # delete the stored spreadsheets for
1658: # - the student level sheet of this user in course's homespace
1659: # - the assessment level sheet for this resource
1660: # for this user in user's homespace
1.325 www 1661: my $key=$uname.':'.$udom.':';
1.109 www 1662: my $status=
1.299 matthew 1663: &del('nohist_calculatedsheets',
1.391 matthew 1664: [$key.'studentcalc:'],
1.133 albertel 1665: $ENV{'course.'.$cid.'.domain'},
1666: $ENV{'course.'.$cid.'.num'})
1667: .' '.
1668: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 1669: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 1670: unless ($status eq 'ok ok') {
1671: &logthis('Could not devalidate spreadsheet '.
1.325 www 1672: $uname.' at '.$udom.' for '.
1.109 www 1673: $symb.': '.$status);
1.133 albertel 1674: }
1.109 www 1675: }
1676: }
1677:
1.265 albertel 1678: sub get_scalar {
1679: my ($string,$end) = @_;
1680: my $value;
1681: if ($$string =~ s/^([^&]*?)($end)/$2/) {
1682: $value = $1;
1683: } elsif ($$string =~ s/^([^&]*?)&//) {
1684: $value = $1;
1685: }
1686: return &unescape($value);
1687: }
1688:
1689: sub array2str {
1690: my (@array) = @_;
1691: my $result=&arrayref2str(\@array);
1692: $result=~s/^__ARRAY_REF__//;
1693: $result=~s/__END_ARRAY_REF__$//;
1694: return $result;
1695: }
1696:
1.204 albertel 1697: sub arrayref2str {
1698: my ($arrayref) = @_;
1.265 albertel 1699: my $result='__ARRAY_REF__';
1.204 albertel 1700: foreach my $elem (@$arrayref) {
1.265 albertel 1701: if(ref($elem) eq 'ARRAY') {
1702: $result.=&arrayref2str($elem).'&';
1703: } elsif(ref($elem) eq 'HASH') {
1704: $result.=&hashref2str($elem).'&';
1705: } elsif(ref($elem)) {
1706: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 1707: } else {
1708: $result.=&escape($elem).'&';
1709: }
1710: }
1711: $result=~s/\&$//;
1.265 albertel 1712: $result .= '__END_ARRAY_REF__';
1.204 albertel 1713: return $result;
1714: }
1715:
1.168 albertel 1716: sub hash2str {
1.204 albertel 1717: my (%hash) = @_;
1718: my $result=&hashref2str(\%hash);
1.265 albertel 1719: $result=~s/^__HASH_REF__//;
1720: $result=~s/__END_HASH_REF__$//;
1.204 albertel 1721: return $result;
1722: }
1723:
1724: sub hashref2str {
1725: my ($hashref)=@_;
1.265 albertel 1726: my $result='__HASH_REF__';
1.204 albertel 1727: foreach (keys(%$hashref)) {
1728: if (ref($_) eq 'ARRAY') {
1.265 albertel 1729: $result.=&arrayref2str($_).'=';
1.204 albertel 1730: } elsif (ref($_) eq 'HASH') {
1.265 albertel 1731: $result.=&hashref2str($_).'=';
1.204 albertel 1732: } elsif (ref($_)) {
1.265 albertel 1733: $result.='=';
1734: #print("Got a ref of ".(ref($_))." skipping.");
1.204 albertel 1735: } else {
1.265 albertel 1736: if ($_) {$result.=&escape($_).'=';} else { last; }
1.204 albertel 1737: }
1738:
1.265 albertel 1739: if(ref($hashref->{$_}) eq 'ARRAY') {
1740: $result.=&arrayref2str($hashref->{$_}).'&';
1741: } elsif(ref($hashref->{$_}) eq 'HASH') {
1742: $result.=&hashref2str($hashref->{$_}).'&';
1743: } elsif(ref($hashref->{$_})) {
1744: $result.='&';
1745: #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204 albertel 1746: } else {
1.265 albertel 1747: $result.=&escape($hashref->{$_}).'&';
1.204 albertel 1748: }
1749: }
1.168 albertel 1750: $result=~s/\&$//;
1.265 albertel 1751: $result .= '__END_HASH_REF__';
1.168 albertel 1752: return $result;
1753: }
1754:
1755: sub str2hash {
1.265 albertel 1756: my ($string)=@_;
1757: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
1758: return %$hash;
1759: }
1760:
1761: sub str2hashref {
1.168 albertel 1762: my ($string) = @_;
1.265 albertel 1763:
1764: my %hash;
1765:
1766: if($string !~ /^__HASH_REF__/) {
1767: if (! ($string eq '' || !defined($string))) {
1768: $hash{'error'}='Not hash reference';
1769: }
1770: return (\%hash, $string);
1771: }
1772:
1773: $string =~ s/^__HASH_REF__//;
1774:
1775: while($string !~ /^__END_HASH_REF__/) {
1776: #key
1777: my $key='';
1778: if($string =~ /^__HASH_REF__/) {
1779: ($key, $string)=&str2hashref($string);
1780: if(defined($key->{'error'})) {
1781: $hash{'error'}='Bad data';
1782: return (\%hash, $string);
1783: }
1784: } elsif($string =~ /^__ARRAY_REF__/) {
1785: ($key, $string)=&str2arrayref($string);
1786: if($key->[0] eq 'Array reference error') {
1787: $hash{'error'}='Bad data';
1788: return (\%hash, $string);
1789: }
1790: } else {
1791: $string =~ s/^(.*?)=//;
1.267 albertel 1792: $key=&unescape($1);
1.265 albertel 1793: }
1794: $string =~ s/^=//;
1795:
1796: #value
1797: my $value='';
1798: if($string =~ /^__HASH_REF__/) {
1799: ($value, $string)=&str2hashref($string);
1800: if(defined($value->{'error'})) {
1801: $hash{'error'}='Bad data';
1802: return (\%hash, $string);
1803: }
1804: } elsif($string =~ /^__ARRAY_REF__/) {
1805: ($value, $string)=&str2arrayref($string);
1806: if($value->[0] eq 'Array reference error') {
1807: $hash{'error'}='Bad data';
1808: return (\%hash, $string);
1809: }
1810: } else {
1811: $value=&get_scalar(\$string,'__END_HASH_REF__');
1812: }
1813: $string =~ s/^&//;
1814:
1815: $hash{$key}=$value;
1.204 albertel 1816: }
1.265 albertel 1817:
1818: $string =~ s/^__END_HASH_REF__//;
1819:
1820: return (\%hash, $string);
1.204 albertel 1821: }
1822:
1823: sub str2array {
1.265 albertel 1824: my ($string)=@_;
1825: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
1826: return @$array;
1827: }
1828:
1829: sub str2arrayref {
1.204 albertel 1830: my ($string) = @_;
1.265 albertel 1831: my @array;
1832:
1833: if($string !~ /^__ARRAY_REF__/) {
1834: if (! ($string eq '' || !defined($string))) {
1835: $array[0]='Array reference error';
1836: }
1837: return (\@array, $string);
1838: }
1839:
1840: $string =~ s/^__ARRAY_REF__//;
1841:
1842: while($string !~ /^__END_ARRAY_REF__/) {
1843: my $value='';
1844: if($string =~ /^__HASH_REF__/) {
1845: ($value, $string)=&str2hashref($string);
1846: if(defined($value->{'error'})) {
1847: $array[0] ='Array reference error';
1848: return (\@array, $string);
1849: }
1850: } elsif($string =~ /^__ARRAY_REF__/) {
1851: ($value, $string)=&str2arrayref($string);
1852: if($value->[0] eq 'Array reference error') {
1853: $array[0] ='Array reference error';
1854: return (\@array, $string);
1855: }
1856: } else {
1857: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
1858: }
1859: $string =~ s/^&//;
1860:
1861: push(@array, $value);
1.191 harris41 1862: }
1.265 albertel 1863:
1864: $string =~ s/^__END_ARRAY_REF__//;
1865:
1866: return (\@array, $string);
1.168 albertel 1867: }
1868:
1.167 albertel 1869: # -------------------------------------------------------------------Temp Store
1870:
1.168 albertel 1871: sub tmpreset {
1872: my ($symb,$namespace,$domain,$stuname) = @_;
1873: if (!$symb) {
1874: $symb=&symbread();
1.380 albertel 1875: if (!$symb) { $symb= $ENV{'request.url'}; }
1.168 albertel 1876: }
1877: $symb=escape($symb);
1878:
1879: if (!$namespace) { $namespace=$ENV{'request.state'}; }
1880: $namespace=~s/\//\_/g;
1881: $namespace=~s/\W//g;
1882:
1883: #FIXME needs to do something for /pub resources
1884: if (!$domain) { $domain=$ENV{'user.domain'}; }
1885: if (!$stuname) { $stuname=$ENV{'user.name'}; }
1886: my $path=$perlvar{'lonDaemons'}.'/tmp';
1887: my %hash;
1888: if (tie(%hash,'GDBM_File',
1889: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 1890: &GDBM_WRCREAT(),0640)) {
1.168 albertel 1891: foreach my $key (keys %hash) {
1.180 albertel 1892: if ($key=~ /:$symb/) {
1.168 albertel 1893: delete($hash{$key});
1894: }
1895: }
1896: }
1897: }
1898:
1.167 albertel 1899: sub tmpstore {
1.168 albertel 1900: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
1901:
1902: if (!$symb) {
1903: $symb=&symbread();
1904: if (!$symb) { $symb= $ENV{'request.url'}; }
1905: }
1906: $symb=escape($symb);
1907:
1908: if (!$namespace) {
1909: # I don't think we would ever want to store this for a course.
1910: # it seems this will only be used if we don't have a course.
1911: #$namespace=$ENV{'request.course.id'};
1912: #if (!$namespace) {
1913: $namespace=$ENV{'request.state'};
1914: #}
1915: }
1916: $namespace=~s/\//\_/g;
1917: $namespace=~s/\W//g;
1918: #FIXME needs to do something for /pub resources
1919: if (!$domain) { $domain=$ENV{'user.domain'}; }
1920: if (!$stuname) { $stuname=$ENV{'user.name'}; }
1921: my $now=time;
1922: my %hash;
1923: my $path=$perlvar{'lonDaemons'}.'/tmp';
1924: if (tie(%hash,'GDBM_File',
1925: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 1926: &GDBM_WRCREAT(),0640)) {
1.168 albertel 1927: $hash{"version:$symb"}++;
1928: my $version=$hash{"version:$symb"};
1929: my $allkeys='';
1930: foreach my $key (keys(%$storehash)) {
1931: $allkeys.=$key.':';
1932: $hash{"$version:$symb:$key"}=$$storehash{$key};
1933: }
1934: $hash{"$version:$symb:timestamp"}=$now;
1935: $allkeys.='timestamp';
1936: $hash{"$version:keys:$symb"}=$allkeys;
1937: if (untie(%hash)) {
1938: return 'ok';
1939: } else {
1940: return "error:$!";
1941: }
1942: } else {
1943: return "error:$!";
1944: }
1945: }
1.167 albertel 1946:
1.168 albertel 1947: # -----------------------------------------------------------------Temp Restore
1.167 albertel 1948:
1.168 albertel 1949: sub tmprestore {
1950: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 1951:
1.168 albertel 1952: if (!$symb) {
1953: $symb=&symbread();
1954: if (!$symb) { $symb= $ENV{'request.url'}; }
1955: }
1956: $symb=escape($symb);
1957:
1958: if (!$namespace) { $namespace=$ENV{'request.state'}; }
1959: #FIXME needs to do something for /pub resources
1960: if (!$domain) { $domain=$ENV{'user.domain'}; }
1961: if (!$stuname) { $stuname=$ENV{'user.name'}; }
1962:
1963: my %returnhash;
1964: $namespace=~s/\//\_/g;
1965: $namespace=~s/\W//g;
1966: my %hash;
1967: my $path=$perlvar{'lonDaemons'}.'/tmp';
1968: if (tie(%hash,'GDBM_File',
1969: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 1970: &GDBM_READER(),0640)) {
1.168 albertel 1971: my $version=$hash{"version:$symb"};
1972: $returnhash{'version'}=$version;
1973: my $scope;
1974: for ($scope=1;$scope<=$version;$scope++) {
1975: my $vkeys=$hash{"$scope:keys:$symb"};
1976: my @keys=split(/:/,$vkeys);
1977: my $key;
1978: $returnhash{"$scope:keys"}=$vkeys;
1979: foreach $key (@keys) {
1980: $returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"};
1981: $returnhash{"$key"}=$hash{"$scope:$symb:$key"};
1.167 albertel 1982: }
1983: }
1.168 albertel 1984: if (!(untie(%hash))) {
1985: return "error:$!";
1986: }
1987: } else {
1988: return "error:$!";
1989: }
1990: return %returnhash;
1.167 albertel 1991: }
1992:
1.9 www 1993: # ----------------------------------------------------------------------- Store
1994:
1995: sub store {
1.124 www 1996: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
1997: my $home='';
1998:
1.168 albertel 1999: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2000:
1.213 www 2001: $symb=&symbclean($symb);
1.122 albertel 2002: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 2003:
1.325 www 2004: if (!$domain) { $domain=$ENV{'user.domain'}; }
2005: if (!$stuname) { $stuname=$ENV{'user.name'}; }
2006:
2007: &devalidate($symb,$stuname,$domain);
1.109 www 2008:
2009: $symb=escape($symb);
1.187 www 2010: if (!$namespace) {
2011: unless ($namespace=$ENV{'request.course.id'}) {
2012: return '';
2013: }
2014: }
1.122 albertel 2015: if (!$home) { $home=$ENV{'user.home'}; }
1.447 www 2016:
2017: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2018: $$storehash{'host'}=$perlvar{'lonHostID'};
2019:
1.12 www 2020: my $namevalue='';
1.191 harris41 2021: foreach (keys %$storehash) {
1.122 albertel 2022: $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1.191 harris41 2023: }
1.12 www 2024: $namevalue=~s/\&$//;
1.187 www 2025: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 2026: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 2027: }
2028:
1.47 www 2029: # -------------------------------------------------------------- Critical Store
2030:
2031: sub cstore {
1.124 www 2032: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2033: my $home='';
2034:
1.168 albertel 2035: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2036:
1.213 www 2037: $symb=&symbclean($symb);
1.122 albertel 2038: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 2039:
1.325 www 2040: if (!$domain) { $domain=$ENV{'user.domain'}; }
2041: if (!$stuname) { $stuname=$ENV{'user.name'}; }
2042:
2043: &devalidate($symb,$stuname,$domain);
1.109 www 2044:
2045: $symb=escape($symb);
1.187 www 2046: if (!$namespace) {
2047: unless ($namespace=$ENV{'request.course.id'}) {
2048: return '';
2049: }
2050: }
1.122 albertel 2051: if (!$home) { $home=$ENV{'user.home'}; }
1.447 www 2052:
2053: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2054: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 2055:
1.47 www 2056: my $namevalue='';
1.191 harris41 2057: foreach (keys %$storehash) {
1.122 albertel 2058: $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
1.191 harris41 2059: }
1.47 www 2060: $namevalue=~s/\&$//;
1.187 www 2061: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 2062: return critical
2063: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 2064: }
2065:
1.9 www 2066: # --------------------------------------------------------------------- Restore
2067:
2068: sub restore {
1.124 www 2069: my ($symb,$namespace,$domain,$stuname) = @_;
2070: my $home='';
2071:
1.168 albertel 2072: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2073:
1.122 albertel 2074: if (!$symb) {
2075: unless ($symb=escape(&symbread())) { return ''; }
2076: } else {
1.213 www 2077: $symb=&escape(&symbclean($symb));
1.122 albertel 2078: }
1.188 www 2079: if (!$namespace) {
2080: unless ($namespace=$ENV{'request.course.id'}) {
2081: return '';
2082: }
2083: }
1.122 albertel 2084: if (!$domain) { $domain=$ENV{'user.domain'}; }
2085: if (!$stuname) { $stuname=$ENV{'user.name'}; }
2086: if (!$home) { $home=$ENV{'user.home'}; }
2087: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
2088:
1.12 www 2089: my %returnhash=();
1.191 harris41 2090: foreach (split(/\&/,$answer)) {
1.12 www 2091: my ($name,$value)=split(/\=/,$_);
2092: $returnhash{&unescape($name)}=&unescape($value);
1.191 harris41 2093: }
1.75 www 2094: my $version;
2095: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191 harris41 2096: foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75 www 2097: $returnhash{$_}=$returnhash{$version.':'.$_};
1.191 harris41 2098: }
1.75 www 2099: }
1.13 www 2100: return %returnhash;
1.34 www 2101: }
2102:
2103: # ---------------------------------------------------------- Course Description
2104:
2105: sub coursedescription {
2106: my $courseid=shift;
2107: $courseid=~s/^\///;
1.49 www 2108: $courseid=~s/\_/\//g;
1.34 www 2109: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 2110: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 2111: my $normalid=$cdomain.'_'.$cnum;
2112: # need to always cache even if we get errors otherwise we keep
2113: # trying and trying and trying to get the course description.
2114: my %envhash=();
2115: my %returnhash=();
2116: $envhash{'course.'.$normalid.'.last_cache'}=time;
1.34 www 2117: if ($chome ne 'no_host') {
1.302 albertel 2118: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 2119: if (!exists($returnhash{'con_lost'})) {
2120: $returnhash{'home'}= $chome;
2121: $returnhash{'domain'} = $cdomain;
2122: $returnhash{'num'} = $cnum;
1.130 albertel 2123: while (my ($name,$value) = each %returnhash) {
1.53 www 2124: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 2125: }
1.270 www 2126: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 2127: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.38 www 2128: $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 2129: $envhash{'course.'.$normalid.'.home'}=$chome;
2130: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
2131: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 2132: }
2133: }
1.302 albertel 2134: &appenv(%envhash);
2135: return %returnhash;
1.9 www 2136: }
1.1 albertel 2137:
1.103 harris41 2138: # -------------------------------------------------------- Get user privileges
1.11 www 2139:
2140: sub rolesinit {
2141: my ($domain,$username,$authhost)=@_;
2142: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12 www 2143: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11 www 2144: my %allroles=();
2145: my %thesepriv=();
2146: my $now=time;
1.21 www 2147: my $userroles="user.login.time=$now\n";
1.11 www 2148: my $thesestr;
2149:
2150: if ($rolesdump ne '') {
1.191 harris41 2151: foreach (split(/&/,$rolesdump)) {
1.21 www 2152: if ($_!~/^rolesdef\&/) {
1.11 www 2153: my ($area,$role)=split(/=/,$_);
1.21 www 2154: $area=~s/\_\w\w$//;
1.11 www 2155: my ($trole,$tend,$tstart)=split(/_/,$role);
1.21 www 2156: $userroles.='user.role.'.$trole.'.'.$area.'='.
2157: $tstart.'.'.$tend."\n";
1.349 www 2158: # log the associated role with the area
2159: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.11 www 2160: if ($tend!=0) {
2161: if ($tend<$now) {
2162: $trole='';
2163: }
2164: }
2165: if ($tstart!=0) {
2166: if ($tstart>$now) {
2167: $trole='';
2168: }
2169: }
2170: if (($area ne '') && ($trole ne '')) {
1.347 albertel 2171: my $spec=$trole.'.'.$area;
2172: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
2173: if ($trole =~ /^cr\//) {
2174: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.392 www 2175: my $homsvr=homeserver($rauthor,$rdomain);
1.347 albertel 2176: if ($hostname{$homsvr} ne '') {
1.392 www 2177: my ($rdummy,$roledef)=
2178: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
2179:
2180: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
1.347 albertel 2181: my ($syspriv,$dompriv,$coursepriv)=
1.392 www 2182: split(/\_/,$roledef);
1.347 albertel 2183: if (defined($syspriv)) {
2184: $allroles{'cm./'}.=':'.$syspriv;
2185: $allroles{$spec.'./'}.=':'.$syspriv;
2186: }
2187: if ($tdomain ne '') {
2188: if (defined($dompriv)) {
2189: $allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
2190: $allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
2191: }
2192: if ($trest ne '') {
2193: if (defined($coursepriv)) {
2194: $allroles{'cm.'.$area}.=':'.$coursepriv;
2195: $allroles{$spec.'.'.$area}.=':'.$coursepriv;
2196: }
2197: }
2198: }
2199: }
2200: }
2201: } else {
2202: if (defined($pr{$trole.':s'})) {
2203: $allroles{'cm./'}.=':'.$pr{$trole.':s'};
2204: $allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
2205: }
2206: if ($tdomain ne '') {
2207: if (defined($pr{$trole.':d'})) {
2208: $allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
2209: $allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
2210: }
2211: if ($trest ne '') {
2212: if (defined($pr{$trole.':c'})) {
2213: $allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
2214: $allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
2215: }
2216: }
2217: }
2218: }
1.12 www 2219: }
2220: }
1.191 harris41 2221: }
1.125 www 2222: my $adv=0;
1.128 www 2223: my $author=0;
1.191 harris41 2224: foreach (keys %allroles) {
1.11 www 2225: %thesepriv=();
1.146 www 2226: if (($_!~/^st/) && ($_!~/^ta/) && ($_!~/^cm/)) { $adv=1; }
1.128 www 2227: if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
1.191 harris41 2228: foreach (split(/:/,$allroles{$_})) {
1.11 www 2229: if ($_ ne '') {
1.103 harris41 2230: my ($privilege,$restrictions)=split(/&/,$_);
1.11 www 2231: if ($restrictions eq '') {
1.103 harris41 2232: $thesepriv{$privilege}='F';
1.11 www 2233: } else {
1.103 harris41 2234: if ($thesepriv{$privilege} ne 'F') {
2235: $thesepriv{$privilege}.=$restrictions;
1.11 www 2236: }
2237: }
2238: }
1.191 harris41 2239: }
1.11 www 2240: $thesestr='';
1.191 harris41 2241: foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.11 www 2242: $userroles.='user.priv.'.$_.'='.$thesestr."\n";
1.191 harris41 2243: }
1.128 www 2244: $userroles.='user.adv='.$adv."\n".
2245: 'user.author='.$author."\n";
1.126 www 2246: $ENV{'user.adv'}=$adv;
1.11 www 2247: }
2248: return $userroles;
2249: }
2250:
1.12 www 2251: # --------------------------------------------------------------- get interface
2252:
2253: sub get {
1.131 albertel 2254: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 2255: my $items='';
1.191 harris41 2256: foreach (@$storearr) {
1.12 www 2257: $items.=escape($_).'&';
1.191 harris41 2258: }
1.12 www 2259: $items=~s/\&$//;
1.131 albertel 2260: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2261: if (!$uname) { $uname=$ENV{'user.name'}; }
2262: my $uhome=&homeserver($uname,$udomain);
2263:
1.133 albertel 2264: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 2265: my @pairs=split(/\&/,$rep);
1.273 albertel 2266: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2267: return @pairs;
2268: }
1.15 www 2269: my %returnhash=();
1.42 www 2270: my $i=0;
1.191 harris41 2271: foreach (@$storearr) {
1.42 www 2272: $returnhash{$_}=unescape($pairs[$i]);
2273: $i++;
1.191 harris41 2274: }
1.15 www 2275: return %returnhash;
1.27 www 2276: }
2277:
2278: # --------------------------------------------------------------- del interface
2279:
2280: sub del {
1.133 albertel 2281: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 2282: my $items='';
1.191 harris41 2283: foreach (@$storearr) {
1.27 www 2284: $items.=escape($_).'&';
1.191 harris41 2285: }
1.27 www 2286: $items=~s/\&$//;
1.133 albertel 2287: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2288: if (!$uname) { $uname=$ENV{'user.name'}; }
2289: my $uhome=&homeserver($uname,$udomain);
2290:
2291: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 2292: }
2293:
2294: # -------------------------------------------------------------- dump interface
2295:
2296: sub dump {
1.193 www 2297: my ($namespace,$udomain,$uname,$regexp)=@_;
1.129 albertel 2298: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2299: if (!$uname) { $uname=$ENV{'user.name'}; }
2300: my $uhome=&homeserver($uname,$udomain);
1.193 www 2301: if ($regexp) {
2302: $regexp=&escape($regexp);
2303: } else {
2304: $regexp='.';
2305: }
2306: my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
1.12 www 2307: my @pairs=split(/\&/,$rep);
2308: my %returnhash=();
1.191 harris41 2309: foreach (@pairs) {
1.12 www 2310: my ($key,$value)=split(/=/,$_);
1.29 www 2311: $returnhash{unescape($key)}=unescape($value);
1.318 matthew 2312: }
2313: return %returnhash;
1.407 www 2314: }
2315:
2316: # -------------------------------------------------------------- keys interface
2317:
2318: sub getkeys {
2319: my ($namespace,$udomain,$uname)=@_;
2320: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2321: if (!$uname) { $uname=$ENV{'user.name'}; }
2322: my $uhome=&homeserver($uname,$udomain);
2323: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
2324: my @keyarray=();
2325: foreach (split(/\&/,$rep)) {
2326: push (@keyarray,&unescape($_));
2327: }
2328: return @keyarray;
1.318 matthew 2329: }
2330:
1.319 matthew 2331: # --------------------------------------------------------------- currentdump
2332: sub currentdump {
1.328 matthew 2333: my ($courseid,$sdom,$sname)=@_;
1.326 matthew 2334: $courseid = $ENV{'request.course.id'} if (! defined($courseid));
2335: $sdom = $ENV{'user.domain'} if (! defined($sdom));
2336: $sname = $ENV{'user.name'} if (! defined($sname));
2337: my $uhome = &homeserver($sname,$sdom);
2338: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 2339: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 2340: #
1.318 matthew 2341: my %returnhash=();
1.319 matthew 2342: #
2343: if ($rep eq "unknown_cmd") {
2344: # an old lond will not know currentdump
2345: # Do a dump and make it look like a currentdump
1.326 matthew 2346: my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319 matthew 2347: return if ($tmp[0] =~ /^(error:|no_such_host)/);
2348: my %hash = @tmp;
2349: @tmp=();
1.424 matthew 2350: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 2351: } else {
2352: my @pairs=split(/\&/,$rep);
2353: foreach (@pairs) {
2354: my ($key,$value)=split(/=/,$_);
2355: my ($symb,$param) = split(/:/,$key);
2356: $returnhash{&unescape($symb)}->{&unescape($param)} =
2357: &unescape($value);
2358: }
1.191 harris41 2359: }
1.12 www 2360: return %returnhash;
1.424 matthew 2361: }
2362:
2363: sub convert_dump_to_currentdump{
2364: my %hash = %{shift()};
2365: my %returnhash;
2366: # Code ripped from lond, essentially. The only difference
2367: # here is the unescaping done by lonnet::dump(). Conceivably
2368: # we might run in to problems with parameter names =~ /^v\./
2369: while (my ($key,$value) = each(%hash)) {
2370: my ($v,$symb,$param) = split(/:/,$key);
2371: next if ($v eq 'version' || $symb eq 'keys');
2372: next if (exists($returnhash{$symb}) &&
2373: exists($returnhash{$symb}->{$param}) &&
2374: $returnhash{$symb}->{'v.'.$param} > $v);
2375: $returnhash{$symb}->{$param}=$value;
2376: $returnhash{$symb}->{'v.'.$param}=$v;
2377: }
2378: #
2379: # Remove all of the keys in the hashes which keep track of
2380: # the version of the parameter.
2381: while (my ($symb,$param_hash) = each(%returnhash)) {
2382: # use a foreach because we are going to delete from the hash.
2383: foreach my $key (keys(%$param_hash)) {
2384: delete($param_hash->{$key}) if ($key =~ /^v\./);
2385: }
2386: }
2387: return \%returnhash;
1.12 www 2388: }
2389:
1.449 matthew 2390: # --------------------------------------------------------------- inc interface
2391:
2392: sub inc {
2393: my ($namespace,$store,$udomain,$uname) = @_;
2394: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2395: if (!$uname) { $uname=$ENV{'user.name'}; }
2396: my $uhome=&homeserver($uname,$udomain);
2397: my $items='';
2398: if (! ref($store)) {
2399: # got a single value, so use that instead
2400: $items = &escape($store).'=&';
2401: } elsif (ref($store) eq 'SCALAR') {
2402: $items = &escape($$store).'=&';
2403: } elsif (ref($store) eq 'ARRAY') {
2404: $items = join('=&',map {&escape($_);} @{$store});
2405: } elsif (ref($store) eq 'HASH') {
2406: while (my($key,$value) = each(%{$store})) {
2407: $items.= &escape($key).'='.&escape($value).'&';
2408: }
2409: }
2410: $items=~s/\&$//;
2411: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
2412: }
2413:
1.12 www 2414: # --------------------------------------------------------------- put interface
2415:
2416: sub put {
1.134 albertel 2417: my ($namespace,$storehash,$udomain,$uname)=@_;
2418: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2419: if (!$uname) { $uname=$ENV{'user.name'}; }
2420: my $uhome=&homeserver($uname,$udomain);
1.12 www 2421: my $items='';
1.191 harris41 2422: foreach (keys %$storehash) {
1.134 albertel 2423: $items.=&escape($_).'='.&escape($$storehash{$_}).'&';
1.191 harris41 2424: }
1.12 www 2425: $items=~s/\&$//;
1.134 albertel 2426: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 2427: }
2428:
2429: # ------------------------------------------------------ critical put interface
2430:
2431: sub cput {
1.134 albertel 2432: my ($namespace,$storehash,$udomain,$uname)=@_;
2433: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2434: if (!$uname) { $uname=$ENV{'user.name'}; }
2435: my $uhome=&homeserver($uname,$udomain);
1.47 www 2436: my $items='';
1.191 harris41 2437: foreach (keys %$storehash) {
1.134 albertel 2438: $items.=escape($_).'='.escape($$storehash{$_}).'&';
1.191 harris41 2439: }
1.47 www 2440: $items=~s/\&$//;
1.134 albertel 2441: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 2442: }
2443:
2444: # -------------------------------------------------------------- eget interface
2445:
2446: sub eget {
1.133 albertel 2447: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 2448: my $items='';
1.191 harris41 2449: foreach (@$storearr) {
1.12 www 2450: $items.=escape($_).'&';
1.191 harris41 2451: }
1.12 www 2452: $items=~s/\&$//;
1.133 albertel 2453: if (!$udomain) { $udomain=$ENV{'user.domain'}; }
2454: if (!$uname) { $uname=$ENV{'user.name'}; }
2455: my $uhome=&homeserver($uname,$udomain);
2456: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 2457: my @pairs=split(/\&/,$rep);
2458: my %returnhash=();
1.42 www 2459: my $i=0;
1.191 harris41 2460: foreach (@$storearr) {
1.42 www 2461: $returnhash{$_}=unescape($pairs[$i]);
2462: $i++;
1.191 harris41 2463: }
1.12 www 2464: return %returnhash;
2465: }
2466:
1.341 www 2467: # ---------------------------------------------- Custom access rule evaluation
2468:
2469: sub customaccess {
2470: my ($priv,$uri)=@_;
1.342 www 2471: my ($urole,$urealm)=split(/\./,$ENV{'request.role'});
1.343 www 2472: $urealm=~s/^\W//;
2473: my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341 www 2474: my $access=0;
2475: foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342 www 2476: my ($effect,$realm,$role)=split(/\:/,$_);
1.343 www 2477: if ($role) {
2478: if ($role ne $urole) { next; }
2479: }
2480: foreach (split(/\s*\,\s*/,$realm)) {
2481: my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
2482: if ($tdom) {
2483: if ($tdom ne $udom) { next; }
2484: }
2485: if ($tcrs) {
2486: if ($tcrs ne $ucrs) { next; }
2487: }
2488: if ($tsec) {
2489: if ($tsec ne $usec) { next; }
2490: }
2491: $access=($effect eq 'allow');
2492: last;
1.342 www 2493: }
1.402 bowersj2 2494: if ($realm eq '' && $role eq '') {
2495: $access=($effect eq 'allow');
2496: }
1.341 www 2497: }
2498: return $access;
2499: }
2500:
1.103 harris41 2501: # ------------------------------------------------- Check for a user privilege
1.12 www 2502:
2503: sub allowed {
2504: my ($priv,$uri)=@_;
1.439 www 2505: $uri=&deversion($uri);
1.152 www 2506: my $orguri=$uri;
1.52 www 2507: $uri=&declutter($uri);
1.29 www 2508:
1.398 albertel 2509: if (defined($ENV{'allowed.'.$priv})) { return $ENV{'allowed.'.$priv}; }
1.54 www 2510: # Free bre access to adm and meta resources
1.29 www 2511:
1.54 www 2512: if ((($uri=~/^adm\//) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14 www 2513: return 'F';
1.159 www 2514: }
2515:
2516: # Free bre to public access
2517:
2518: if ($priv eq 'bre') {
1.238 www 2519: my $copyright=&metadata($uri,'copyright');
1.301 www 2520: if (($copyright eq 'public') && (!$ENV{'request.course.id'})) {
2521: return 'F';
2522: }
1.238 www 2523: if ($copyright eq 'priv') {
2524: $uri=~/([^\/]+)\/([^\/]+)\//;
2525: unless (($ENV{'user.name'} eq $2) && ($ENV{'user.domain'} eq $1)) {
2526: return '';
2527: }
2528: }
2529: if ($copyright eq 'domain') {
2530: $uri=~/([^\/]+)\/([^\/]+)\//;
2531: unless (($ENV{'user.domain'} eq $1) ||
2532: ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $1)) {
2533: return '';
2534: }
1.262 matthew 2535: }
2536: if ($ENV{'request.role'}=~ /li\.\//) {
2537: # Library role, so allow browsing of resources in this domain.
2538: return 'F';
1.238 www 2539: }
1.341 www 2540: if ($copyright eq 'custom') {
2541: unless (&customaccess($priv,$uri)) { return ''; }
2542: }
1.14 www 2543: }
1.264 matthew 2544: # Domain coordinator is trying to create a course
2545: if (($priv eq 'ccc') && ($ENV{'request.role'} =~ /^dc\./)) {
2546: # uri is the requested domain in this case.
2547: # comparison to 'request.role.domain' shows if the user has selected
2548: # a role of dc for the domain in question.
2549: return 'F' if ($uri eq $ENV{'request.role.domain'});
2550: }
1.29 www 2551:
1.52 www 2552: my $thisallowed='';
2553: my $statecond=0;
2554: my $courseprivid='';
2555:
2556: # Course
2557:
2558: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/$priv\&([^\:]*)/) {
2559: $thisallowed.=$1;
2560: }
1.29 www 2561:
1.52 www 2562: # Domain
2563:
2564: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
2565: =~/$priv\&([^\:]*)/) {
1.12 www 2566: $thisallowed.=$1;
2567: }
1.52 www 2568:
2569: # Course: uri itself is a course
1.66 www 2570: my $courseuri=$uri;
2571: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 2572: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 2573:
1.83 www 2574: if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
1.52 www 2575: =~/$priv\&([^\:]*)/) {
1.12 www 2576: $thisallowed.=$1;
2577: }
1.29 www 2578:
1.314 www 2579: # URI is an uploaded document for this course
2580:
2581: if (($priv eq 'bre') &&
2582: ($uri=~/^uploaded\/$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}\/$ENV{'course.'.$ENV{'request.course.id'}.'.num'}/)) {
2583: return 'F';
2584: }
1.52 www 2585: # Full access at system, domain or course-wide level? Exit.
1.29 www 2586:
2587: if ($thisallowed=~/F/) {
2588: return 'F';
2589: }
2590:
1.52 www 2591: # If this is generating or modifying users, exit with special codes
1.29 www 2592:
1.166 www 2593: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:$priv\:/) {
1.52 www 2594: return $thisallowed;
2595: }
2596: #
1.103 harris41 2597: # Gathered so far: system, domain and course wide privileges
1.52 www 2598: #
2599: # Course: See if uri or referer is an individual resource that is part of
2600: # the course
2601:
2602: if ($ENV{'request.course.id'}) {
1.232 www 2603:
1.52 www 2604: $courseprivid=$ENV{'request.course.id'};
2605: if ($ENV{'request.course.sec'}) {
2606: $courseprivid.='/'.$ENV{'request.course.sec'};
2607: }
2608: $courseprivid=~s/\_/\//;
2609: my $checkreferer=1;
1.232 www 2610: my ($match,$cond)=&is_on_map($uri);
2611: if ($match) {
2612: $statecond=$cond;
1.52 www 2613: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
2614: =~/$priv\&([^\:]*)/) {
2615: $thisallowed.=$1;
2616: $checkreferer=0;
2617: }
1.29 www 2618: }
1.83 www 2619:
1.148 www 2620: if ($checkreferer) {
1.152 www 2621: my $refuri=$ENV{'httpref.'.$orguri};
1.148 www 2622: unless ($refuri) {
1.191 harris41 2623: foreach (keys %ENV) {
1.148 www 2624: if ($_=~/^httpref\..*\*/) {
2625: my $pattern=$_;
1.156 www 2626: $pattern=~s/^httpref\.\/res\///;
1.148 www 2627: $pattern=~s/\*/\[\^\/\]\+/g;
2628: $pattern=~s/\//\\\//g;
1.152 www 2629: if ($orguri=~/$pattern/) {
1.148 www 2630: $refuri=$ENV{$_};
2631: }
2632: }
1.191 harris41 2633: }
1.148 www 2634: }
1.232 www 2635:
1.148 www 2636: if ($refuri) {
1.152 www 2637: $refuri=&declutter($refuri);
1.232 www 2638: my ($match,$cond)=&is_on_map($refuri);
2639: if ($match) {
2640: my $refstatecond=$cond;
1.52 www 2641: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
2642: =~/$priv\&([^\:]*)/) {
2643: $thisallowed.=$1;
1.53 www 2644: $uri=$refuri;
2645: $statecond=$refstatecond;
1.52 www 2646: }
2647: }
1.148 www 2648: }
1.29 www 2649: }
1.52 www 2650: }
1.29 www 2651:
1.52 www 2652: #
1.103 harris41 2653: # Gathered now: all privileges that could apply, and condition number
1.52 www 2654: #
2655: #
2656: # Full or no access?
2657: #
1.29 www 2658:
1.52 www 2659: if ($thisallowed=~/F/) {
2660: return 'F';
2661: }
1.29 www 2662:
1.52 www 2663: unless ($thisallowed) {
2664: return '';
2665: }
1.29 www 2666:
1.52 www 2667: # Restrictions exist, deal with them
2668: #
2669: # C:according to course preferences
2670: # R:according to resource settings
2671: # L:unless locked
2672: # X:according to user session state
2673: #
2674:
2675: # Possibly locked functionality, check all courses
1.54 www 2676: # Locks might take effect only after 10 minutes cache expiration for other
2677: # courses, and 2 minutes for current course
1.52 www 2678:
2679: my $envkey;
2680: if ($thisallowed=~/L/) {
2681: foreach $envkey (keys %ENV) {
1.54 www 2682: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
2683: my $courseid=$2;
2684: my $roleid=$1.'.'.$2;
1.92 www 2685: $courseid=~s/^\///;
1.54 www 2686: my $expiretime=600;
2687: if ($ENV{'request.role'} eq $roleid) {
2688: $expiretime=120;
2689: }
2690: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
2691: my $prefix='course.'.$cdom.'_'.$cnum.'.';
2692: if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
2693: &coursedescription($courseid);
2694: }
2695: if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,$csec\,/)
2696: || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
2697: if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
1.57 www 2698: &log($ENV{'user.domain'},$ENV{'user.name'},
1.239 www 2699: $ENV{'user.home'},
1.57 www 2700: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 2701: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54 www 2702: $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 2703: return '';
2704: }
2705: }
1.54 www 2706: if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,$csec\,/)
2707: || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
2708: if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
1.57 www 2709: &log($ENV{'user.domain'},$ENV{'user.name'},
1.239 www 2710: $ENV{'user.home'},
1.57 www 2711: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 2712: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.54 www 2713: $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 2714: return '';
2715: }
2716: }
2717: }
1.29 www 2718: }
1.52 www 2719: }
2720:
2721: #
2722: # Rest of the restrictions depend on selected course
2723: #
2724:
2725: unless ($ENV{'request.course.id'}) {
2726: return '1';
2727: }
1.29 www 2728:
1.52 www 2729: #
2730: # Now user is definitely in a course
2731: #
1.53 www 2732:
2733:
2734: # Course preferences
2735:
2736: if ($thisallowed=~/C/) {
1.54 www 2737: my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
1.237 www 2738: my $unamedom=$ENV{'user.name'}.':'.$ENV{'user.domain'};
1.54 www 2739: if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.194 www 2740: =~/$rolecode/) {
1.57 www 2741: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
2742: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
1.237 www 2743: $ENV{'request.course.id'});
2744: return '';
2745: }
2746:
2747: if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.users.denied'}
2748: =~/$unamedom/) {
2749: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
2750: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
1.54 www 2751: $ENV{'request.course.id'});
2752: return '';
2753: }
1.53 www 2754: }
2755:
2756: # Resource preferences
2757:
2758: if ($thisallowed=~/R/) {
1.54 www 2759: my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
1.341 www 2760: if (&metadata($uri,'roledeny')=~/$rolecode/) {
2761: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
1.57 www 2762: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
1.341 www 2763: return '';
1.54 www 2764: }
1.53 www 2765: }
1.30 www 2766:
1.246 www 2767: # Restricted by state or randomout?
1.30 www 2768:
1.52 www 2769: if ($thisallowed=~/X/) {
1.247 www 2770: if ($ENV{'acc.randomout'}) {
1.249 www 2771: my $symb=&symbread($uri,1);
1.248 www 2772: if (($symb) && ($ENV{'acc.randomout'}=~/\&$symb\&/)) {
2773: return '';
2774: }
1.247 www 2775: }
2776: if (&condval($statecond)) {
1.52 www 2777: return '2';
2778: } else {
2779: return '';
2780: }
2781: }
1.30 www 2782:
1.52 www 2783: return 'F';
1.232 www 2784: }
2785:
2786: # --------------------------------------------------- Is a resource on the map?
2787:
2788: sub is_on_map {
2789: my $uri=&declutter(shift);
1.435 www 2790: $uri=~s/\.\d+\.(\w+)$/\.$1/;
1.232 www 2791: my @uriparts=split(/\//,$uri);
2792: my $filename=$uriparts[$#uriparts];
2793: my $pathname=$uri;
1.289 bowersj2 2794: $pathname=~s|/\Q$filename\E$||;
1.332 www 2795: $pathname=~s/^adm\/wrapper\///;
1.289 bowersj2 2796: #Trying to find the conditional for the file
1.232 www 2797: my $match=($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 2798: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 2799: if ($match) {
1.289 bowersj2 2800: return (1,$1);
2801: } else {
1.434 www 2802: return (0,0);
1.289 bowersj2 2803: }
1.12 www 2804: }
2805:
1.427 www 2806: # --------------------------------------------------------- Get symb from alias
2807:
2808: sub get_symb_from_alias {
2809: my $symb=shift;
2810: my ($map,$resid,$url)=&decode_symb($symb);
2811: # Already is a symb
2812: if ($url) { return $symb; }
2813: # Must be an alias
2814: my $aliassymb='';
2815: my %bighash;
2816: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
2817: &GDBM_READER(),0640)) {
2818: my $rid=$bighash{'mapalias_'.$symb};
2819: if ($rid) {
2820: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 2821: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
2822: $resid,$bighash{'src_'.$rid});
1.427 www 2823: }
2824: untie %bighash;
2825: }
2826: return $aliassymb;
2827: }
2828:
1.12 www 2829: # ----------------------------------------------------------------- Define Role
2830:
2831: sub definerole {
2832: if (allowed('mcr','/')) {
2833: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392 www 2834: foreach (split(':',$sysrole)) {
1.21 www 2835: my ($crole,$cqual)=split(/\&/,$_);
2836: if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
2837: if ($pr{'cr:s'}=~/$crole\&/) {
2838: if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) {
2839: return "refused:s:$crole&$cqual";
2840: }
2841: }
1.191 harris41 2842: }
1.392 www 2843: foreach (split(':',$domrole)) {
1.21 www 2844: my ($crole,$cqual)=split(/\&/,$_);
2845: if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
2846: if ($pr{'cr:d'}=~/$crole\&/) {
2847: if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) {
2848: return "refused:d:$crole&$cqual";
2849: }
2850: }
1.191 harris41 2851: }
1.392 www 2852: foreach (split(':',$courole)) {
1.21 www 2853: my ($crole,$cqual)=split(/\&/,$_);
2854: if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
2855: if ($pr{'cr:c'}=~/$crole\&/) {
2856: if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) {
2857: return "refused:c:$crole&$cqual";
2858: }
2859: }
1.191 harris41 2860: }
1.12 www 2861: my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
2862: "$ENV{'user.domain'}:$ENV{'user.name'}:".
1.21 www 2863: "rolesdef_$rolename=".
2864: escape($sysrole.'_'.$domrole.'_'.$courole);
1.12 www 2865: return reply($command,$ENV{'user.home'});
2866: } else {
2867: return 'refused';
2868: }
1.105 harris41 2869: }
2870:
2871: # ---------------- Make a metadata query against the network of library servers
2872:
2873: sub metadata_query {
1.244 matthew 2874: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 2875: my %rhash;
1.244 matthew 2876: my @server_list = (defined($server_array) ? @$server_array
2877: : keys(%libserv) );
2878: for my $server (@server_list) {
1.118 harris41 2879: unless ($custom or $customshow) {
2880: my $reply=&reply("querysend:".&escape($query),$server);
2881: $rhash{$server}=$reply;
2882: }
2883: else {
2884: my $reply=&reply("querysend:".&escape($query).':'.
2885: &escape($custom).':'.&escape($customshow),
2886: $server);
2887: $rhash{$server}=$reply;
2888: }
1.112 harris41 2889: }
1.118 harris41 2890: return \%rhash;
1.240 www 2891: }
2892:
2893: # ----------------------------------------- Send log queries and wait for reply
2894:
2895: sub log_query {
2896: my ($uname,$udom,$query,%filters)=@_;
2897: my $uhome=&homeserver($uname,$udom);
2898: if ($uhome eq 'no_host') { return 'error: no_host'; }
2899: my $uhost=$hostname{$uhome};
1.241 www 2900: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240 www 2901: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
2902: $uhome);
2903: unless ($queryid=~/^$uhost\_/) { return 'error: '.$queryid; }
1.242 www 2904: return get_query_reply($queryid);
2905: }
2906:
2907: sub get_query_reply {
2908: my $queryid=shift;
1.240 www 2909: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
2910: my $reply='';
2911: for (1..100) {
2912: sleep 2;
2913: if (-e $replyfile.'.end') {
1.448 albertel 2914: if (open(my $fh,$replyfile)) {
1.240 www 2915: $reply.=<$fh>;
1.448 albertel 2916: close($fh);
1.240 www 2917: } else { return 'error: reply_file_error'; }
1.242 www 2918: return &unescape($reply);
2919: }
1.240 www 2920: }
1.242 www 2921: return 'timeout:'.$queryid;
1.240 www 2922: }
2923:
2924: sub courselog_query {
1.241 www 2925: #
2926: # possible filters:
2927: # url: url or symb
2928: # username
2929: # domain
2930: # action: view, submit, grade
2931: # start: timestamp
2932: # end: timestamp
2933: #
1.240 www 2934: my (%filters)=@_;
2935: unless ($ENV{'request.course.id'}) { return 'no_course'; }
1.241 www 2936: if ($filters{'url'}) {
2937: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
2938: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
2939: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
2940: }
1.240 www 2941: my $cname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
2942: my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
2943: return &log_query($cname,$cdom,'courselog',%filters);
2944: }
2945:
2946: sub userlog_query {
2947: my ($uname,$udom,%filters)=@_;
2948: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 2949: }
2950:
2951: # ------------------------------------------------------------------ Plain Text
2952:
2953: sub plaintext {
1.22 www 2954: my $short=shift;
1.414 www 2955: return &mt($prp{$short});
1.12 www 2956: }
2957:
2958: # ----------------------------------------------------------------- Assign Role
2959:
2960: sub assignrole {
1.357 www 2961: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21 www 2962: my $mrole;
2963: if ($role =~ /^cr\//) {
1.393 www 2964: my $cwosec=$url;
2965: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
2966: unless (&allowed('ccr',$cwosec)) {
1.104 www 2967: &logthis('Refused custom assignrole: '.
2968: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
2969: $ENV{'user.name'}.' at '.$ENV{'user.domain'});
2970: return 'refused';
2971: }
1.21 www 2972: $mrole='cr';
2973: } else {
1.82 www 2974: my $cwosec=$url;
1.83 www 2975: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373 www 2976: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
1.104 www 2977: &logthis('Refused assignrole: '.
2978: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
2979: $ENV{'user.name'}.' at '.$ENV{'user.domain'});
2980: return 'refused';
2981: }
1.21 www 2982: $mrole=$role;
2983: }
2984: my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
2985: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 2986: if ($end) { $command.='_'.$end; }
1.21 www 2987: if ($start) {
2988: if ($end) {
1.81 www 2989: $command.='_'.$start;
1.21 www 2990: } else {
1.81 www 2991: $command.='_0_'.$start;
1.21 www 2992: }
2993: }
1.357 www 2994: # actually delete
2995: if ($deleteflag) {
1.373 www 2996: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 2997: # modify command to delete the role
2998: $command="encrypt:rolesdel:$ENV{'user.domain'}:$ENV{'user.name'}:".
2999: "$udom:$uname:$url".'_'."$mrole";
1.373 www 3000: &logthis("$ENV{'user.name'} at $ENV{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 3001: # set start and finish to negative values for userrolelog
3002: $start=-1;
3003: $end=-1;
3004: }
3005: }
3006: # send command
1.349 www 3007: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 3008: # log new user role if status is ok
1.349 www 3009: if ($answer eq 'ok') {
3010: &userrolelog($mrole,$uname,$udom,$url,$start,$end);
3011: }
3012: return $answer;
1.169 harris41 3013: }
3014:
3015: # -------------------------------------------------- Modify user authentication
1.197 www 3016: # Overrides without validation
3017:
1.169 harris41 3018: sub modifyuserauth {
3019: my ($udom,$uname,$umode,$upass)=@_;
3020: my $uhome=&homeserver($uname,$udom);
1.197 www 3021: unless (&allowed('mau',$udom)) { return 'refused'; }
3022: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.272 matthew 3023: $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
3024: ' in domain '.$ENV{'request.role.domain'});
1.169 harris41 3025: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
3026: &escape($upass),$uhome);
1.197 www 3027: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
3028: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
3029: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
3030: &log($udom,,$uname,$uhome,
3031: 'Authentication changed by '.$ENV{'user.domain'}.', '.
3032: $ENV{'user.name'}.', '.$umode.
3033: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 3034: unless ($reply eq 'ok') {
1.197 www 3035: &logthis('Authentication mode error: '.$reply);
1.169 harris41 3036: return 'error: '.$reply;
3037: }
1.170 harris41 3038: return 'ok';
1.80 www 3039: }
3040:
1.81 www 3041: # --------------------------------------------------------------- Modify a user
1.80 www 3042:
1.81 www 3043: sub modifyuser {
1.206 matthew 3044: my ($udom, $uname, $uid,
3045: $umode, $upass, $first,
3046: $middle, $last, $gene,
1.387 www 3047: $forceid, $desiredhome, $email)=@_;
1.198 www 3048: $udom=~s/\W//g;
3049: $uname=~s/\W//g;
1.81 www 3050: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 3051: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 3052: $last.', '.$gene.'(forceid: '.$forceid.')'.
3053: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
3054: ' desiredhome not specified').
1.272 matthew 3055: ' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
3056: ' in domain '.$ENV{'request.role.domain'});
1.230 stredwic 3057: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 3058: # ----------------------------------------------------------------- Create User
1.406 albertel 3059: if (($uhome eq 'no_host') &&
3060: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 3061: my $unhome='';
1.209 matthew 3062: if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) {
3063: $unhome = $desiredhome;
3064: } elsif($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
1.80 www 3065: $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1.209 matthew 3066: } else { # load balancing routine for determining $unhome
1.80 www 3067: my $tryserver;
1.81 www 3068: my $loadm=10000000;
1.80 www 3069: foreach $tryserver (keys %libserv) {
3070: if ($hostdom{$tryserver} eq $udom) {
3071: my $answer=reply('load',$tryserver);
3072: if (($answer=~/\d+/) && ($answer<$loadm)) {
3073: $loadm=$answer;
3074: $unhome=$tryserver;
3075: }
3076: }
3077: }
3078: }
3079: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 3080: return 'error: unable to find a home server for '.$uname.
3081: ' in domain '.$udom;
1.80 www 3082: }
3083: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
3084: &escape($upass),$unhome);
3085: unless ($reply eq 'ok') {
3086: return 'error: '.$reply;
3087: }
1.230 stredwic 3088: $uhome=&homeserver($uname,$udom,'true');
1.80 www 3089: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 3090: return 'error: unable verify users home machine.';
1.80 www 3091: }
1.209 matthew 3092: } # End of creation of new user
1.80 www 3093: # ---------------------------------------------------------------------- Add ID
3094: if ($uid) {
3095: $uid=~tr/A-Z/a-z/;
3096: my %uidhash=&idrget($udom,$uname);
1.196 www 3097: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
3098: && (!$forceid)) {
1.80 www 3099: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 3100: return 'error: user id "'.$uid.'" does not match '.
3101: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 3102: }
3103: } else {
3104: &idput($udom,($uname => $uid));
3105: }
3106: }
3107: # -------------------------------------------------------------- Add names, etc
1.313 matthew 3108: my @tmp=&get('environment',
1.134 albertel 3109: ['firstname','middlename','lastname','generation'],
3110: $udom,$uname);
1.313 matthew 3111: my %names;
3112: if ($tmp[0] =~ m/^error:.*/) {
3113: %names=();
3114: } else {
3115: %names = @tmp;
3116: }
1.388 www 3117: #
3118: # Make sure to not trash student environment if instructor does not bother
3119: # to supply name and email information
3120: #
3121: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 3122: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 3123: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 3124: if (defined($gene)) { $names{'generation'} = $gene; }
1.388 www 3125: if ($email) { $names{'notification'} = $email;
3126: $names{'critnotification'} = $email; }
1.387 www 3127:
1.134 albertel 3128: my $reply = &put('environment', \%names, $udom,$uname);
3129: if ($reply ne 'ok') { return 'error: '.$reply; }
1.81 www 3130: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 3131: $umode.', '.$first.', '.$middle.', '.
3132: $last.', '.$gene.' by '.
3133: $ENV{'user.name'}.' at '.$ENV{'user.domain'});
1.134 albertel 3134: return 'ok';
1.80 www 3135: }
3136:
1.81 www 3137: # -------------------------------------------------------------- Modify student
1.80 www 3138:
1.81 www 3139: sub modifystudent {
3140: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.387 www 3141: $end,$start,$forceid,$desiredhome,$email)=@_;
1.81 www 3142: my $cid='';
3143: unless ($cid=$ENV{'request.course.id'}) {
1.80 www 3144: return 'not_in_class';
3145: }
3146: # --------------------------------------------------------------- Make the user
1.81 www 3147: my $reply=&modifyuser
1.209 matthew 3148: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 3149: $desiredhome,$email);
1.80 www 3150: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 3151: # This will cause &modify_student_enrollment to get the uid from the
3152: # students environment
3153: $uid = undef if (!$forceid);
3154: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,
3155: $last,$gene,$usec,$end,$start);
3156: return $reply;
3157: }
3158:
3159: sub modify_student_enrollment {
3160: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start) = @_;
3161: # Get the course id from the environment
3162: my $cid='';
3163: unless ($cid=$ENV{'request.course.id'}) {
3164: return 'not_in_class';
3165: }
3166: # Make sure the user exists
1.81 www 3167: my $uhome=&homeserver($uname,$udom);
3168: if (($uhome eq '') || ($uhome eq 'no_host')) {
3169: return 'error: no such user';
3170: }
1.297 matthew 3171: #
3172: # Get student data if we were not given enough information
3173: if (!defined($first) || $first eq '' ||
3174: !defined($last) || $last eq '' ||
3175: !defined($uid) || $uid eq '' ||
3176: !defined($middle) || $middle eq '' ||
3177: !defined($gene) || $gene eq '') {
1.294 matthew 3178: # They did not supply us with enough data to enroll the student, so
3179: # we need to pick up more information.
1.297 matthew 3180: my %tmp = &get('environment',
1.294 matthew 3181: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 3182: ,$udom,$uname);
3183:
3184: foreach (keys(%tmp)) {
3185: &logthis("key $_ = ".$tmp{$_});
3186: }
1.294 matthew 3187: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
3188: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
3189: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 3190: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 3191: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
3192: }
3193: my $fullname = &Apache::loncoursedata::ProcessFullName($last,$gene,
3194: $first,$middle);
1.297 matthew 3195: my $reply=critical('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
1.81 www 3196: $ENV{'course.'.$cid.'.num'}.':classlist:'.
3197: &escape($uname.':'.$udom).'='.
1.294 matthew 3198: &escape(join(':',$end,$start,$uid,$usec,$fullname)),
1.81 www 3199: $ENV{'course.'.$cid.'.home'});
3200: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
3201: return 'error: '.$reply;
3202: }
1.297 matthew 3203: # Add student role to user
1.83 www 3204: my $uurl='/'.$cid;
1.81 www 3205: $uurl=~s/\_/\//g;
3206: if ($usec) {
3207: $uurl.='/'.$usec;
3208: }
3209: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21 www 3210: }
3211:
1.84 www 3212: # ------------------------------------------------- Write to course preferences
3213:
3214: sub writecoursepref {
3215: my ($courseid,%prefs)=@_;
3216: $courseid=~s/^\///;
3217: $courseid=~s/\_/\//g;
3218: my ($cdomain,$cnum)=split(/\//,$courseid);
3219: my $chome=homeserver($cnum,$cdomain);
3220: if (($chome eq '') || ($chome eq 'no_host')) {
3221: return 'error: no such course';
3222: }
3223: my $cstring='';
1.191 harris41 3224: foreach (keys %prefs) {
1.84 www 3225: $cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191 harris41 3226: }
1.84 www 3227: $cstring=~s/\&$//;
3228: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
3229: }
3230:
3231: # ---------------------------------------------------------- Make/modify course
3232:
3233: sub createcourse {
1.271 www 3234: my ($udom,$description,$url,$course_server,$nonstandard)=@_;
1.84 www 3235: $url=&declutter($url);
3236: my $cid='';
1.264 matthew 3237: unless (&allowed('ccc',$udom)) {
1.84 www 3238: return 'refused';
3239: }
3240: # ------------------------------------------------------------------- Create ID
3241: my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
3242: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
3243: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 3244: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 3245: unless (($uhome eq '') || ($uhome eq 'no_host')) {
3246: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
3247: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 3248: $uhome=&homeserver($uname,$udom,'true');
1.84 www 3249: unless (($uhome eq '') || ($uhome eq 'no_host')) {
3250: return 'error: unable to generate unique course-ID';
3251: }
3252: }
1.264 matthew 3253: # ------------------------------------------------ Check supplied server name
3254: $course_server = $ENV{'user.homeserver'} if (! defined($course_server));
3255: if (! exists($libserv{$course_server})) {
3256: return 'error:bad server name '.$course_server;
3257: }
1.84 www 3258: # ------------------------------------------------------------- Make the course
3259: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 3260: $course_server);
1.84 www 3261: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 3262: $uhome=&homeserver($uname,$udom,'true');
1.84 www 3263: if (($uhome eq '') || ($uhome eq 'no_host')) {
3264: return 'error: no such course';
3265: }
1.271 www 3266: # ----------------------------------------------------------------- Course made
1.358 www 3267: # log existance
3268: &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description),
3269: $uhome);
3270: &flushcourselogs();
3271: # set toplevel url
1.271 www 3272: my $topurl=$url;
3273: unless ($nonstandard) {
3274: # ------------------------------------------ For standard courses, make top url
3275: my $mapurl=&clutter($url);
1.278 www 3276: if ($mapurl eq '/res/') { $mapurl=''; }
1.271 www 3277: $ENV{'form.initmap'}=(<<ENDINITMAP);
3278: <map>
3279: <resource id="1" type="start"></resource>
3280: <resource id="2" src="$mapurl"></resource>
3281: <resource id="3" type="finish"></resource>
3282: <link index="1" from="1" to="2"></link>
3283: <link index="2" from="2" to="3"></link>
3284: </map>
3285: ENDINITMAP
3286: $topurl=&declutter(
3287: &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence')
3288: );
3289: }
3290: # ----------------------------------------------------------- Write preferences
1.84 www 3291: &writecoursepref($udom.'_'.$uname,
3292: ('description' => $description,
1.271 www 3293: 'url' => $topurl));
1.84 www 3294: return '/'.$udom.'/'.$uname;
3295: }
3296:
1.21 www 3297: # ---------------------------------------------------------- Assign Custom Role
3298:
3299: sub assigncustomrole {
1.357 www 3300: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21 www 3301: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357 www 3302: $end,$start,$deleteflag);
1.21 www 3303: }
3304:
3305: # ----------------------------------------------------------------- Revoke Role
3306:
3307: sub revokerole {
1.357 www 3308: my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21 www 3309: my $now=time;
1.357 www 3310: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21 www 3311: }
3312:
3313: # ---------------------------------------------------------- Revoke Custom Role
3314:
3315: sub revokecustomrole {
1.357 www 3316: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21 www 3317: my $now=time;
1.357 www 3318: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
3319: $deleteflag);
1.17 www 3320: }
3321:
3322: # ------------------------------------------------------------ Directory lister
3323:
3324: sub dirlist {
1.253 stredwic 3325: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
3326:
1.18 www 3327: $uri=~s/^\///;
3328: $uri=~s/\/$//;
1.253 stredwic 3329: my ($udom, $uname);
3330: (undef,$udom,$uname)=split(/\//,$uri);
3331: if(defined($userdomain)) {
3332: $udom = $userdomain;
3333: }
3334: if(defined($username)) {
3335: $uname = $username;
3336: }
3337:
3338: my $dirRoot = $perlvar{'lonDocRoot'};
3339: if(defined($alternateDirectoryRoot)) {
3340: $dirRoot = $alternateDirectoryRoot;
3341: $dirRoot =~ s/\/$//;
3342: }
3343:
3344: if($udom) {
3345: if($uname) {
3346: my $listing=reply('ls:'.$dirRoot.'/'.$uri,
3347: homeserver($uname,$udom));
3348: return split(/:/,$listing);
3349: } elsif(!defined($alternateDirectoryRoot)) {
3350: my $tryserver;
3351: my %allusers=();
3352: foreach $tryserver (keys %libserv) {
3353: if($hostdom{$tryserver} eq $udom) {
3354: my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
3355: $udom, $tryserver);
3356: if (($listing ne 'no_such_dir') && ($listing ne 'empty')
3357: && ($listing ne 'con_lost')) {
3358: foreach (split(/:/,$listing)) {
3359: my ($entry,@stat)=split(/&/,$_);
3360: $allusers{$entry}=1;
3361: }
3362: }
1.191 harris41 3363: }
1.253 stredwic 3364: }
3365: my $alluserstr='';
3366: foreach (sort keys %allusers) {
3367: $alluserstr.=$_.'&user:';
3368: }
3369: $alluserstr=~s/:$//;
3370: return split(/:/,$alluserstr);
3371: } else {
3372: my @emptyResults = ();
3373: push(@emptyResults, 'missing user name');
3374: return split(':',@emptyResults);
3375: }
3376: } elsif(!defined($alternateDirectoryRoot)) {
3377: my $tryserver;
3378: my %alldom=();
3379: foreach $tryserver (keys %libserv) {
3380: $alldom{$hostdom{$tryserver}}=1;
3381: }
3382: my $alldomstr='';
3383: foreach (sort keys %alldom) {
1.397 albertel 3384: $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253 stredwic 3385: }
3386: $alldomstr=~s/:$//;
3387: return split(/:/,$alldomstr);
3388: } else {
3389: my @emptyResults = ();
3390: push(@emptyResults, 'missing domain');
3391: return split(':',@emptyResults);
1.275 stredwic 3392: }
3393: }
3394:
3395: # --------------------------------------------- GetFileTimestamp
3396: # This function utilizes dirlist and returns the date stamp for
3397: # when it was last modified. It will also return an error of -1
3398: # if an error occurs
3399:
1.410 matthew 3400: ##
3401: ## FIXME: This subroutine assumes its caller knows something about the
3402: ## directory structure of the home server for the student ($root).
3403: ## Not a good assumption to make. Since this is for looking up files
3404: ## in user directories, the full path should be constructed by lond, not
3405: ## whatever machine we request data from.
3406: ##
1.275 stredwic 3407: sub GetFileTimestamp {
3408: my ($studentDomain,$studentName,$filename,$root)=@_;
3409: $studentDomain=~s/\W//g;
3410: $studentName=~s/\W//g;
3411: my $subdir=$studentName.'__';
3412: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
3413: my $proname="$studentDomain/$subdir/$studentName";
3414: $proname .= '/'.$filename;
1.375 matthew 3415: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
3416: $studentName, $root);
1.275 stredwic 3417: my @stats = split('&', $fileStat);
3418: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 3419: # @stats contains first the filename, then the stat output
3420: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 3421: } else {
3422: return -1;
1.253 stredwic 3423: }
1.26 www 3424: }
3425:
3426: # -------------------------------------------------------- Value of a Condition
3427:
1.40 www 3428: sub directcondval {
3429: my $number=shift;
3430: if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
3431: return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
3432: } else {
3433: return 2;
3434: }
3435: }
3436:
1.26 www 3437: sub condval {
3438: my $condidx=shift;
3439: my $result=0;
1.54 www 3440: my $allpathcond='';
1.191 harris41 3441: foreach (split(/\|/,$condidx)) {
1.54 www 3442: if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
3443: $allpathcond.=
3444: '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
3445: }
1.191 harris41 3446: }
1.54 www 3447: $allpathcond=~s/\|$//;
1.33 www 3448: if ($ENV{'request.course.id'}) {
1.54 www 3449: if ($allpathcond) {
1.26 www 3450: my $operand='|';
3451: my @stack;
1.191 harris41 3452: foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
1.26 www 3453: if ($_ eq '(') {
3454: push @stack,($operand,$result)
3455: } elsif ($_ eq ')') {
3456: my $before=pop @stack;
3457: if (pop @stack eq '&') {
3458: $result=$result>$before?$before:$result;
3459: } else {
3460: $result=$result>$before?$result:$before;
3461: }
3462: } elsif (($_ eq '&') || ($_ eq '|')) {
3463: $operand=$_;
3464: } else {
1.40 www 3465: my $new=directcondval($_);
1.26 www 3466: if ($operand eq '&') {
3467: $result=$result>$new?$new:$result;
3468: } else {
3469: $result=$result>$new?$result:$new;
1.191 harris41 3470: }
1.26 www 3471: }
1.191 harris41 3472: }
1.26 www 3473: }
3474: }
3475: return $result;
1.421 albertel 3476: }
3477:
3478: # ---------------------------------------------------- Devalidate courseresdata
3479:
3480: sub devalidatecourseresdata {
3481: my ($coursenum,$coursedomain)=@_;
3482: my $hashid=$coursenum.':'.$coursedomain;
1.428 albertel 3483: &devalidate_cache(\%courseresdatacache,$hashid,'courseres');
1.28 www 3484: }
3485:
1.200 www 3486: # --------------------------------------------------- Course Resourcedata Query
3487:
3488: sub courseresdata {
3489: my ($coursenum,$coursedomain,@which)=@_;
3490: my $coursehom=&homeserver($coursenum,$coursedomain);
3491: my $hashid=$coursenum.':'.$coursedomain;
1.425 albertel 3492: my ($result,$cached)=&is_cached(\%courseresdatacache,$hashid,'courseres');
1.417 albertel 3493: unless (defined($cached)) {
1.251 albertel 3494: my %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 3495: $result=\%dumpreply;
1.251 albertel 3496: my ($tmp) = keys(%dumpreply);
3497: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.425 albertel 3498: &do_cache(\%courseresdatacache,$hashid,$result,'courseres');
1.306 albertel 3499: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
3500: return $tmp;
1.416 albertel 3501: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 3502: $result=undef;
1.425 albertel 3503: &do_cache(\%courseresdatacache,$hashid,$result,'courseres');
1.250 albertel 3504: }
3505: }
1.251 albertel 3506: foreach my $item (@which) {
1.417 albertel 3507: if (defined($result->{$item})) {
3508: return $result->{$item};
1.251 albertel 3509: }
1.250 albertel 3510: }
1.291 albertel 3511: return undef;
1.200 www 3512: }
3513:
1.379 matthew 3514: #
3515: # EXT resource caching routines
3516: #
3517:
3518: sub clear_EXT_cache_status {
1.383 albertel 3519: &delenv('cache.EXT.');
1.379 matthew 3520: }
3521:
3522: sub EXT_cache_status {
3523: my ($target_domain,$target_user) = @_;
1.383 albertel 3524: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.389 www 3525: if (exists($ENV{$cachename}) && ($ENV{$cachename}+600) > time) {
1.379 matthew 3526: # We know already the user has no data
3527: return 1;
3528: } else {
3529: return 0;
3530: }
3531: }
3532:
3533: sub EXT_cache_set {
3534: my ($target_domain,$target_user) = @_;
1.383 albertel 3535: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.379 matthew 3536: &appenv($cachename => time);
3537: }
3538:
1.28 www 3539: # --------------------------------------------------------- Value of a Variable
1.58 www 3540: sub EXT {
1.395 albertel 3541: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.218 albertel 3542:
1.68 www 3543: unless ($varname) { return ''; }
1.218 albertel 3544: #get real user name/domain, courseid and symb
3545: my $courseid;
1.359 albertel 3546: my $publicuser;
1.427 www 3547: if ($symbparm) {
3548: $symbparm=&get_symb_from_alias($symbparm);
3549: }
1.218 albertel 3550: if (!($uname && $udom)) {
1.360 albertel 3551: (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378 matthew 3552: &Apache::lonxml::whichuser($symbparm);
1.218 albertel 3553: if (!$symbparm) { $symbparm=$cursymb; }
3554: } else {
3555: $courseid=$ENV{'request.course.id'};
3556: }
1.48 www 3557: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
3558: my $rest;
1.320 albertel 3559: if (defined($therest[0])) {
1.48 www 3560: $rest=join('.',@therest);
3561: } else {
3562: $rest='';
3563: }
1.320 albertel 3564:
1.57 www 3565: my $qualifierrest=$qualifier;
3566: if ($rest) { $qualifierrest.='.'.$rest; }
3567: my $spacequalifierrest=$space;
3568: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 3569: if ($realm eq 'user') {
1.48 www 3570: # --------------------------------------------------------------- user.resource
3571: if ($space eq 'resource') {
1.335 albertel 3572: if (defined($Apache::lonhomework::parsing_a_problem)) {
3573: return $Apache::lonhomework::history{$qualifierrest};
3574: } else {
1.359 albertel 3575: my %restored;
3576: if ($publicuser || $ENV{'request.state'} eq 'construct') {
3577: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
3578: } else {
3579: %restored=&restore($symbparm,$courseid,$udom,$uname);
3580: }
1.335 albertel 3581: return $restored{$qualifierrest};
3582: }
1.48 www 3583: # ----------------------------------------------------------------- user.access
3584: } elsif ($space eq 'access') {
1.218 albertel 3585: # FIXME - not supporting calls for a specific user
1.48 www 3586: return &allowed($qualifier,$rest);
3587: # ------------------------------------------ user.preferences, user.environment
3588: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.218 albertel 3589: if (($uname eq $ENV{'user.name'}) &&
3590: ($udom eq $ENV{'user.domain'})) {
3591: return $ENV{join('.',('environment',$qualifierrest))};
3592: } else {
1.359 albertel 3593: my %returnhash;
3594: if (!$publicuser) {
3595: %returnhash=&userenvironment($udom,$uname,
3596: $qualifierrest);
3597: }
1.218 albertel 3598: return $returnhash{$qualifierrest};
3599: }
1.48 www 3600: # ----------------------------------------------------------------- user.course
3601: } elsif ($space eq 'course') {
1.218 albertel 3602: # FIXME - not supporting calls for a specific user
1.48 www 3603: return $ENV{join('.',('request.course',$qualifier))};
3604: # ------------------------------------------------------------------- user.role
3605: } elsif ($space eq 'role') {
1.218 albertel 3606: # FIXME - not supporting calls for a specific user
1.48 www 3607: my ($role,$where)=split(/\./,$ENV{'request.role'});
3608: if ($qualifier eq 'value') {
3609: return $role;
3610: } elsif ($qualifier eq 'extent') {
3611: return $where;
3612: }
3613: # ----------------------------------------------------------------- user.domain
3614: } elsif ($space eq 'domain') {
1.218 albertel 3615: return $udom;
1.48 www 3616: # ------------------------------------------------------------------- user.name
3617: } elsif ($space eq 'name') {
1.218 albertel 3618: return $uname;
1.48 www 3619: # ---------------------------------------------------- Any other user namespace
1.29 www 3620: } else {
1.359 albertel 3621: my %reply;
3622: if (!$publicuser) {
3623: %reply=&get($space,[$qualifierrest],$udom,$uname);
3624: }
3625: return $reply{$qualifierrest};
1.48 www 3626: }
1.236 www 3627: } elsif ($realm eq 'query') {
3628: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 3629: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
3630: [$spacequalifierrest]);
1.376 albertel 3631: return $ENV{'form.'.$spacequalifierrest};
1.236 www 3632: } elsif ($realm eq 'request') {
1.48 www 3633: # ------------------------------------------------------------- request.browser
3634: if ($space eq 'browser') {
1.430 www 3635: if ($qualifier eq 'textremote') {
3636: if (&mt('textual_remote_display') eq 'on') {
3637: return 1;
3638: } else {
3639: return 0;
3640: }
3641: } else {
3642: return $ENV{'browser.'.$qualifier};
3643: }
1.57 www 3644: # ------------------------------------------------------------ request.filename
3645: } else {
3646: return $ENV{'request.'.$spacequalifierrest};
1.29 www 3647: }
1.28 www 3648: } elsif ($realm eq 'course') {
1.48 www 3649: # ---------------------------------------------------------- course.description
1.218 albertel 3650: return $ENV{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 3651: } elsif ($realm eq 'resource') {
1.165 www 3652:
1.395 albertel 3653: my $section;
1.359 albertel 3654: if (defined($courseid) && $courseid eq $ENV{'request.course.id'}) {
1.165 www 3655:
1.218 albertel 3656: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 3657:
1.60 www 3658: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 3659: if (!$symbparm) { $symbparm=&symbread(); }
3660: my $symbp=$symbparm;
1.409 www 3661: my $mapp=(&decode_symb($symbp))[0];
1.218 albertel 3662:
3663: my $symbparm=$symbp.'.'.$spacequalifierrest;
3664: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
3665:
3666: if (($ENV{'user.name'} eq $uname) &&
3667: ($ENV{'user.domain'} eq $udom)) {
1.255 albertel 3668: $section=$ENV{'request.course.sec'};
1.218 albertel 3669: } else {
1.377 matthew 3670: if (! defined($usection)) {
3671: $section=&usection($udom,$uname,$courseid);
3672: } else {
3673: $section = $usection;
3674: }
1.218 albertel 3675: }
3676:
3677: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
3678: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
3679: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
3680:
3681: my $courselevel=$courseid.'.'.$spacequalifierrest;
3682: my $courselevelr=$courseid.'.'.$symbparm;
3683: my $courselevelm=$courseid.'.'.$mapparm;
1.69 www 3684:
1.60 www 3685: # ----------------------------------------------------------- first, check user
1.379 matthew 3686: #most student don\'t have any data set, check if there is some data
3687: if (! &EXT_cache_status($udom,$uname)) {
1.420 albertel 3688: my $hashid="$udom:$uname";
1.425 albertel 3689: my ($result,$cached)=&is_cached(\%userresdatacache,$hashid,
3690: 'userres');
1.420 albertel 3691: if (!defined($cached)) {
3692: my %resourcedata=&get('resourcedata',
3693: [$courselevelr,$courselevelm,
3694: $courselevel],$udom,$uname);
3695: $result=\%resourcedata;
1.425 albertel 3696: &do_cache(\%userresdatacache,$hashid,$result,'userres');
1.420 albertel 3697: }
3698: my ($tmp)=keys(%$result);
1.308 albertel 3699: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
1.420 albertel 3700: if ($$result{$courselevelr}) {
3701: return $$result{$courselevelr}; }
3702: if ($$result{$courselevelm}) {
3703: return $$result{$courselevelm}; }
3704: if ($$result{$courselevel}) {
3705: return $$result{$courselevel}; }
1.308 albertel 3706: } else {
3707: if ($tmp!~/No such file/) {
3708: &logthis("<font color=blue>WARNING:".
3709: " Trying to get resource data for ".
3710: $uname." at ".$udom.": ".
3711: $tmp."</font>");
3712: } elsif ($tmp=~/error:No such file/) {
1.379 matthew 3713: &EXT_cache_set($udom,$uname);
1.308 albertel 3714: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
3715: return $tmp;
3716: }
1.218 albertel 3717: }
3718: }
1.95 www 3719:
1.60 www 3720: # -------------------------------------------------------- second, check course
1.96 www 3721:
1.218 albertel 3722: my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'},
3723: $ENV{'course.'.$courseid.'.domain'},
3724: ($seclevelr,$seclevelm,$seclevel,
3725: $courselevelr,$courselevelm,
3726: $courselevel));
1.287 albertel 3727: if (defined($coursereply)) { return $coursereply; }
1.200 www 3728:
1.60 www 3729: # ------------------------------------------------------ third, check map parms
1.218 albertel 3730: my %parmhash=();
3731: my $thisparm='';
3732: if (tie(%parmhash,'GDBM_File',
3733: $ENV{'request.course.fn'}.'_parms.db',
1.256 albertel 3734: &GDBM_READER(),0640)) {
1.218 albertel 3735: $thisparm=$parmhash{$symbparm};
3736: untie(%parmhash);
3737: }
3738: if ($thisparm) { return $thisparm; }
3739: }
1.60 www 3740: # --------------------------------------------- last, look in resource metadata
1.71 www 3741:
1.218 albertel 3742: $spacequalifierrest=~s/\./\_/;
1.282 albertel 3743: my $filename;
3744: if (!$symbparm) { $symbparm=&symbread(); }
3745: if ($symbparm) {
1.409 www 3746: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 3747: } else {
3748: $filename=$ENV{'request.filename'};
3749: }
3750: my $metadata=&metadata($filename,$spacequalifierrest);
1.288 albertel 3751: if (defined($metadata)) { return $metadata; }
1.282 albertel 3752: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288 albertel 3753: if (defined($metadata)) { return $metadata; }
1.142 www 3754:
1.145 www 3755: # ------------------------------------------------------------------ Cascade up
1.218 albertel 3756: unless ($space eq '0') {
1.336 albertel 3757: my @parts=split(/_/,$space);
3758: my $id=pop(@parts);
3759: my $part=join('_',@parts);
3760: if ($part eq '') { $part='0'; }
3761: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 3762: $symbparm,$udom,$uname,$section,1);
1.337 albertel 3763: if (defined($partgeneral)) { return $partgeneral; }
1.218 albertel 3764: }
1.395 albertel 3765: if ($recurse) { return undef; }
3766: my $pack_def=&packages_tab_default($filename,$varname);
3767: if (defined($pack_def)) { return $pack_def; }
1.71 www 3768:
1.48 www 3769: # ---------------------------------------------------- Any other user namespace
3770: } elsif ($realm eq 'environment') {
3771: # ----------------------------------------------------------------- environment
1.219 albertel 3772: if (($uname eq $ENV{'user.name'})&&($udom eq $ENV{'user.domain'})) {
3773: return $ENV{'environment.'.$spacequalifierrest};
3774: } else {
3775: my %returnhash=&userenvironment($udom,$uname,
3776: $spacequalifierrest);
3777: return $returnhash{$spacequalifierrest};
3778: }
1.28 www 3779: } elsif ($realm eq 'system') {
1.48 www 3780: # ----------------------------------------------------------------- system.time
3781: if ($space eq 'time') {
3782: return time;
3783: }
1.28 www 3784: }
1.48 www 3785: return '';
1.61 www 3786: }
3787:
1.395 albertel 3788: sub packages_tab_default {
3789: my ($uri,$varname)=@_;
3790: my (undef,$part,$name)=split(/\./,$varname);
3791: my $packages=&metadata($uri,'packages');
3792: foreach my $package (split(/,/,$packages)) {
3793: my ($pack_type,$pack_part)=split(/_/,$package,2);
3794: if ($pack_part eq $part) {
3795: return $packagetab{"$pack_type&$name&default"};
3796: }
3797: }
3798: return undef;
3799: }
3800:
1.334 albertel 3801: sub add_prefix_and_part {
3802: my ($prefix,$part)=@_;
3803: my $keyroot;
3804: if (defined($prefix) && $prefix !~ /^__/) {
3805: # prefix that has a part already
3806: $keyroot=$prefix;
3807: } elsif (defined($prefix)) {
3808: # prefix that is missing a part
3809: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
3810: } else {
3811: # no prefix at all
3812: if (defined($part)) { $keyroot='_'.$part; }
3813: }
3814: return $keyroot;
3815: }
3816:
1.71 www 3817: # ---------------------------------------------------------------- Get metadata
3818:
3819: sub metadata {
1.176 www 3820: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 3821: $uri=&declutter($uri);
1.288 albertel 3822: # if it is a non metadata possible uri return quickly
1.293 matthew 3823: if (($uri eq '') || (($uri =~ m|^/*adm/|) && ($uri !~ m|^adm/includes|)) ||
1.423 albertel 3824: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
3825: ($uri =~ m|home/[^/]+/public_html/|)) {
1.288 albertel 3826: return '';
3827: }
1.73 www 3828: my $filename=$uri;
3829: $uri=~s/\.meta$//;
1.172 www 3830: #
3831: # Is the metadata already cached?
1.177 www 3832: # Look at timestamp of caching
1.172 www 3833: # Everything is cached by the main uri, libraries are never directly cached
3834: #
1.428 albertel 3835: if (!defined($liburi)) {
3836: my ($result,$cached)=&is_cached(\%metacache,$uri,'meta');
3837: if (defined($cached)) { return $result->{':'.$what}; }
3838: }
3839: {
1.172 www 3840: #
3841: # Is this a recursive call for a library?
3842: #
1.428 albertel 3843: my %lcmetacache;
1.171 www 3844: if ($liburi) {
3845: $liburi=&declutter($liburi);
3846: $filename=$liburi;
1.401 bowersj2 3847: } else {
1.428 albertel 3848: &devalidate_cache(\%metacache,$uri,'meta');
1.401 bowersj2 3849: }
1.140 www 3850: my %metathesekeys=();
1.73 www 3851: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.335 albertel 3852: my $metastring=&getfile(&filelocation('',&clutter($filename)));
1.208 albertel 3853: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 3854: my $token;
1.140 www 3855: undef %metathesekeys;
1.71 www 3856: while ($token=$parser->get_token) {
1.339 albertel 3857: if ($token->[0] eq 'S') {
3858: if (defined($token->[2]->{'package'})) {
1.172 www 3859: #
3860: # This is a package - get package info
3861: #
1.339 albertel 3862: my $package=$token->[2]->{'package'};
3863: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
3864: if (defined($token->[2]->{'id'})) {
3865: $keyroot.='_'.$token->[2]->{'id'};
3866: }
1.428 albertel 3867: if ($lcmetacache{':packages'}) {
3868: $lcmetacache{':packages'}.=','.$package.$keyroot;
1.339 albertel 3869: } else {
1.428 albertel 3870: $lcmetacache{':packages'}=$package.$keyroot;
1.339 albertel 3871: }
3872: foreach (keys %packagetab) {
1.432 albertel 3873: my $part=$keyroot;
3874: $part=~s/^\_//;
3875: if ($_=~/^\Q$package\E\&/ ||
3876: $_=~/^\Q$package\E_0\&/) {
1.339 albertel 3877: my ($pack,$name,$subp)=split(/\&/,$_);
1.395 albertel 3878: # ignore package.tab specified default values
3879: # here &package_tab_default() will fetch those
3880: if ($subp eq 'default') { next; }
1.339 albertel 3881: my $value=$packagetab{$_};
1.432 albertel 3882: my $unikey;
3883: if ($pack =~ /_0$/) {
3884: $unikey='parameter_0_'.$name;
3885: $part=0;
3886: } else {
3887: $unikey='parameter'.$keyroot.'_'.$name;
3888: }
1.339 albertel 3889: if ($subp eq 'display') {
3890: $value.=' [Part: '.$part.']';
3891: }
1.428 albertel 3892: $lcmetacache{':'.$unikey.'.part'}=$part;
1.395 albertel 3893: $metathesekeys{$unikey}=1;
1.428 albertel 3894: unless (defined($lcmetacache{':'.$unikey.'.'.$subp})) {
3895: $lcmetacache{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 3896: }
1.428 albertel 3897: if (defined($lcmetacache{':'.$unikey.'.default'})) {
3898: $lcmetacache{':'.$unikey}=
3899: $lcmetacache{':'.$unikey.'.default'};
1.356 albertel 3900: }
1.339 albertel 3901: }
3902: }
3903: } else {
1.172 www 3904: #
3905: # This is not a package - some other kind of start tag
1.339 albertel 3906: #
3907: my $entry=$token->[1];
3908: my $unikey;
3909: if ($entry eq 'import') {
3910: $unikey='';
3911: } else {
3912: $unikey=$entry;
3913: }
3914: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
3915:
3916: if (defined($token->[2]->{'id'})) {
3917: $unikey.='_'.$token->[2]->{'id'};
3918: }
1.175 www 3919:
1.339 albertel 3920: if ($entry eq 'import') {
1.175 www 3921: #
3922: # Importing a library here
1.339 albertel 3923: #
3924: if ($depthcount<20) {
3925: my $location=$parser->get_text('/import');
3926: my $dir=$filename;
3927: $dir=~s|[^/]*$||;
3928: $location=&filelocation($dir,$location);
3929: foreach (sort(split(/\,/,&metadata($uri,'keys',
3930: $location,$unikey,
3931: $depthcount+1)))) {
3932: $metathesekeys{$_}=1;
3933: }
3934: }
3935: } else {
3936:
3937: if (defined($token->[2]->{'name'})) {
3938: $unikey.='_'.$token->[2]->{'name'};
3939: }
3940: $metathesekeys{$unikey}=1;
3941: foreach (@{$token->[3]}) {
1.428 albertel 3942: $lcmetacache{':'.$unikey.'.'.$_}=$token->[2]->{$_};
1.339 albertel 3943: }
3944: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.428 albertel 3945: my $default=$lcmetacache{':'.$unikey.'.default'};
1.339 albertel 3946: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
3947: # only ws inside the tag, and not in default, so use default
3948: # as value
1.428 albertel 3949: $lcmetacache{':'.$unikey}=$default;
1.339 albertel 3950: } else {
1.321 albertel 3951: # either something interesting inside the tag or default
3952: # uninteresting
1.428 albertel 3953: $lcmetacache{':'.$unikey}=$internaltext;
1.339 albertel 3954: }
1.172 www 3955: # end of not-a-package not-a-library import
1.339 albertel 3956: }
1.172 www 3957: # end of not-a-package start tag
1.339 albertel 3958: }
1.172 www 3959: # the next is the end of "start tag"
1.339 albertel 3960: }
3961: }
1.338 www 3962: # are there custom rights to evaluate
1.428 albertel 3963: if ($lcmetacache{':copyright'} eq 'custom') {
1.339 albertel 3964:
1.338 www 3965: #
3966: # Importing a rights file here
1.339 albertel 3967: #
3968: unless ($depthcount) {
1.428 albertel 3969: my $location=$lcmetacache{':customdistributionfile'};
1.339 albertel 3970: my $dir=$filename;
3971: $dir=~s|[^/]*$||;
3972: $location=&filelocation($dir,$location);
3973: foreach (sort(split(/\,/,&metadata($uri,'keys',
3974: $location,'_rights',
3975: $depthcount+1)))) {
3976: $metathesekeys{$_}=1;
3977: }
3978: }
3979: }
1.428 albertel 3980: $lcmetacache{':keys'}=join(',',keys %metathesekeys);
3981: &metadata_generate_part0(\%metathesekeys,\%lcmetacache,$uri);
3982: $lcmetacache{':allpossiblekeys'}=join(',',keys %metathesekeys);
3983: &do_cache(\%metacache,$uri,\%lcmetacache,'meta');
1.177 www 3984: # this is the end of "was not already recently cached
1.71 www 3985: }
1.428 albertel 3986: return $metacache{$uri}->{':'.$what};
1.261 albertel 3987: }
3988:
3989: sub metadata_generate_part0 {
3990: my ($metadata,$metacache,$uri) = @_;
3991: my %allnames;
3992: foreach my $metakey (sort keys %$metadata) {
3993: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 3994: my $part=$$metacache{':'.$metakey.'.part'};
3995: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 3996: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 3997: $allnames{$name}=$part;
3998: }
3999: }
4000: }
4001: foreach my $name (keys(%allnames)) {
4002: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 4003: my $key=":parameter_0_$name";
1.261 albertel 4004: $$metacache{"$key.part"}='0';
4005: $$metacache{"$key.name"}=$name;
1.428 albertel 4006: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 4007: $allnames{$name}.'_'.$name.
4008: '.type'};
1.428 albertel 4009: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 4010: '.display'};
4011: my $expr='\\[Part: '.$allnames{$name}.'\\]';
4012: $olddis=~s/$expr/\[Part: 0\]/;
4013: $$metacache{"$key.display"}=$olddis;
4014: }
1.71 www 4015: }
4016:
1.301 www 4017: # ------------------------------------------------- Get the title of a resource
4018:
4019: sub gettitle {
4020: my $urlsymb=shift;
4021: my $symb=&symbread($urlsymb);
4022: unless ($symb) {
4023: unless ($urlsymb) { $urlsymb=$ENV{'request.filename'}; }
4024: return &metadata($urlsymb,'title');
4025: }
1.425 albertel 4026: my ($result,$cached)=&is_cached(\%titlecache,$symb,'title',600);
1.419 albertel 4027: if (defined($cached)) { return $result; }
1.409 www 4028: my ($map,$resid,$url)=&decode_symb($symb);
1.301 www 4029: my $title='';
4030: my %bighash;
4031: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
4032: &GDBM_READER(),0640)) {
4033: my $mapid=$bighash{'map_pc_'.&clutter($map)};
4034: $title=$bighash{'title_'.$mapid.'.'.$resid};
4035: untie %bighash;
4036: }
1.363 www 4037: $title=~s/\&colon\;/\:/gs;
1.301 www 4038: if ($title) {
1.425 albertel 4039: return &do_cache(\%titlecache,$symb,$title,'title');
1.301 www 4040: } else {
4041: return &metadata($urlsymb,'title');
4042: }
4043: }
4044:
1.31 www 4045: # ------------------------------------------------- Update symbolic store links
4046:
4047: sub symblist {
4048: my ($mapname,%newhash)=@_;
1.438 www 4049: $mapname=&deversion(&declutter($mapname));
1.31 www 4050: my %hash;
4051: if (($ENV{'request.course.fn'}) && (%newhash)) {
4052: if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
1.256 albertel 4053: &GDBM_WRCREAT(),0640)) {
1.191 harris41 4054: foreach (keys %newhash) {
1.438 www 4055: $hash{declutter($_)}=$mapname.'___'.&deversion($newhash{$_});
1.191 harris41 4056: }
1.31 www 4057: if (untie(%hash)) {
4058: return 'ok';
4059: }
4060: }
4061: }
4062: return 'error';
1.212 www 4063: }
4064:
4065: # --------------------------------------------------------------- Verify a symb
4066:
4067: sub symbverify {
4068: my ($symb,$thisfn)=@_;
1.439 www 4069: $thisfn=&declutter($thisfn);
1.215 www 4070: # direct jump to resource in page or to a sequence - will construct own symbs
4071: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
4072: # check URL part
1.409 www 4073: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 4074:
1.431 www 4075: unless ($url eq $thisfn) { return 0; }
1.213 www 4076:
1.216 www 4077: $symb=&symbclean($symb);
1.439 www 4078: $thisfn=&deversion($thisfn);
1.213 www 4079:
4080: my %bighash;
4081: my $okay=0;
1.431 www 4082:
1.213 www 4083: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.256 albertel 4084: &GDBM_READER(),0640)) {
1.280 www 4085: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.216 www 4086: unless ($ids) {
4087: $ids=$bighash{'ids_/'.$thisfn};
4088: }
4089: if ($ids) {
4090: # ------------------------------------------------------------------- Has ID(s)
4091: foreach (split(/\,/,$ids)) {
4092: my ($mapid,$resid)=split(/\./,$_);
4093: if (
4094: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
4095: eq $symb) {
4096: $okay=1;
4097: }
4098: }
4099: }
1.213 www 4100: untie(%bighash);
4101: }
4102: return $okay;
1.31 www 4103: }
4104:
1.210 www 4105: # --------------------------------------------------------------- Clean-up symb
4106:
4107: sub symbclean {
4108: my $symb=shift;
1.213 www 4109:
1.210 www 4110: # remove version from map
4111: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 4112:
1.210 www 4113: # remove version from URL
4114: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 4115:
1.210 www 4116: return $symb;
1.409 www 4117: }
4118:
4119: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 4120:
4121: sub encode_symb {
4122: my ($map,$resid,$url)=@_;
4123: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
4124: }
1.409 www 4125:
4126: sub decode_symb {
1.413 www 4127: my ($map,$resid,$url)=split(/\_\_\_/,shift);
4128: return (&fixversion($map),$resid,&fixversion($url));
4129: }
4130:
4131: sub fixversion {
4132: my $fn=shift;
4133: if ($fn=~/^(adm|uploaded|public)/) { return $fn; }
1.435 www 4134: my %bighash;
4135: my $uri=&clutter($fn);
1.440 www 4136: my $key=$ENV{'request.course.id'}.'_'.$uri;
4137: # is this cached?
4138: my ($result,$cached)=&is_cached(\%courseresversioncache,$key,
4139: 'courseresversion',600);
4140: if (defined($cached)) { return $result; }
4141: # unfortunately not cached, or expired
1.435 www 4142: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.440 www 4143: &GDBM_READER(),0640)) {
4144: if ($bighash{'version_'.$uri}) {
4145: my $version=$bighash{'version_'.$uri};
1.444 www 4146: unless (($version eq 'mostrecent') ||
4147: ($version==&getversion($uri))) {
1.440 www 4148: $uri=~s/\.(\w+)$/\.$version\.$1/;
4149: }
4150: }
4151: untie %bighash;
1.413 www 4152: }
1.440 www 4153: return &do_cache
4154: (\%courseresversioncache,$key,&declutter($uri),'courseresversion');
1.438 www 4155: }
4156:
4157: sub deversion {
4158: my $url=shift;
4159: $url=~s/\.\d+\.(\w+)$/\.$1/;
4160: return $url;
1.210 www 4161: }
4162:
1.31 www 4163: # ------------------------------------------------------ Return symb list entry
4164:
4165: sub symbread {
1.249 www 4166: my ($thisfn,$donotrecurse)=@_;
1.242 www 4167: # no filename provided? try from environment
1.44 www 4168: unless ($thisfn) {
1.210 www 4169: if ($ENV{'request.symb'}) { return &symbclean($ENV{'request.symb'}); }
1.44 www 4170: $thisfn=$ENV{'request.filename'};
4171: }
1.242 www 4172: # is that filename actually a symb? Verify, clean, and return
4173: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
4174: if (&symbverify($thisfn,$1)) { return &symbclean($thisfn); }
4175: }
1.44 www 4176: $thisfn=declutter($thisfn);
1.31 www 4177: my %hash;
1.37 www 4178: my %bighash;
4179: my $syval='';
1.45 www 4180: if (($ENV{'request.course.fn'}) && ($thisfn)) {
1.31 www 4181: if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
1.256 albertel 4182: &GDBM_READER(),0640)) {
1.31 www 4183: $syval=$hash{$thisfn};
1.37 www 4184: untie(%hash);
4185: }
4186: # ---------------------------------------------------------- There was an entry
4187: if ($syval) {
4188: unless ($syval=~/\_\d+$/) {
4189: unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.44 www 4190: &appenv('request.ambiguous' => $thisfn);
1.37 www 4191: return '';
4192: }
4193: $syval.=$1;
4194: }
4195: } else {
4196: # ------------------------------------------------------- Was not in symb table
4197: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.256 albertel 4198: &GDBM_READER(),0640)) {
1.37 www 4199: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 4200: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 4201: unless ($ids) {
4202: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 4203: }
4204: unless ($ids) {
4205: # alias?
4206: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 4207: }
1.37 www 4208: if ($ids) {
4209: # ------------------------------------------------------------------- Has ID(s)
4210: my @possibilities=split(/\,/,$ids);
1.39 www 4211: if ($#possibilities==0) {
4212: # ----------------------------------------------- There is only one possibility
1.37 www 4213: my ($mapid,$resid)=split(/\./,$ids);
4214: $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
1.249 www 4215: } elsif (!$donotrecurse) {
1.39 www 4216: # ------------------------------------------ There is more than one possibility
4217: my $realpossible=0;
1.191 harris41 4218: foreach (@possibilities) {
1.39 www 4219: my $file=$bighash{'src_'.$_};
4220: if (&allowed('bre',$file)) {
4221: my ($mapid,$resid)=split(/\./,$_);
4222: if ($bighash{'map_type_'.$mapid} ne 'page') {
4223: $realpossible++;
4224: $syval=declutter($bighash{'map_id_'.$mapid}).
4225: '___'.$resid;
4226: }
4227: }
1.191 harris41 4228: }
1.39 www 4229: if ($realpossible!=1) { $syval=''; }
1.249 www 4230: } else {
4231: $syval='';
1.37 www 4232: }
4233: }
4234: untie(%bighash)
4235: }
1.31 www 4236: }
1.62 www 4237: if ($syval) {
1.210 www 4238: return &symbclean($syval.'___'.$thisfn);
1.62 www 4239: }
1.31 www 4240: }
1.44 www 4241: &appenv('request.ambiguous' => $thisfn);
1.31 www 4242: return '';
4243: }
4244:
4245: # ---------------------------------------------------------- Return random seed
4246:
1.32 www 4247: sub numval {
4248: my $txt=shift;
4249: $txt=~tr/A-J/0-9/;
4250: $txt=~tr/a-j/0-9/;
4251: $txt=~tr/K-T/0-9/;
4252: $txt=~tr/k-t/0-9/;
4253: $txt=~tr/U-Z/0-5/;
4254: $txt=~tr/u-z/0-5/;
4255: $txt=~s/\D//g;
4256: return int($txt);
1.368 albertel 4257: }
4258:
4259: sub latest_rnd_algorithm_id {
1.443 albertel 4260: return '64bit2';
1.366 albertel 4261: }
1.32 www 4262:
1.31 www 4263: sub rndseed {
1.155 albertel 4264: my ($symb,$courseid,$domain,$username)=@_;
1.366 albertel 4265:
4266: my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155 albertel 4267: if (!$symb) {
1.366 albertel 4268: unless ($symb=$wsymb) { return time; }
4269: }
4270: if (!$courseid) { $courseid=$wcourseid; }
4271: if (!$domain) { $domain=$wdomain; }
4272: if (!$username) { $username=$wusername }
4273: my $which=$ENV{"course.$courseid.rndseed"};
4274: my $CODE=$ENV{'scantron.CODE'};
4275: if (defined($CODE)) {
4276: &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
1.443 albertel 4277: } elsif ($which eq '64bit2') {
4278: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 4279: } elsif ($which eq '64bit') {
4280: return &rndseed_64bit($symb,$courseid,$domain,$username);
4281: }
4282: return &rndseed_32bit($symb,$courseid,$domain,$username);
4283: }
4284:
4285: sub rndseed_32bit {
4286: my ($symb,$courseid,$domain,$username)=@_;
4287: {
4288: use integer;
4289: my $symbchck=unpack("%32C*",$symb) << 27;
4290: my $symbseed=numval($symb) << 22;
4291: my $namechck=unpack("%32C*",$username) << 17;
4292: my $nameseed=numval($username) << 12;
4293: my $domainseed=unpack("%32C*",$domain) << 7;
4294: my $courseseed=unpack("%32C*",$courseid);
4295: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
4296: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
4297: #&Apache::lonxml::debug("rndseed :$num:$symb");
4298: return $num;
4299: }
4300: }
4301:
4302: sub rndseed_64bit {
4303: my ($symb,$courseid,$domain,$username)=@_;
4304: {
4305: use integer;
4306: my $symbchck=unpack("%32S*",$symb) << 21;
4307: my $symbseed=numval($symb) << 10;
4308: my $namechck=unpack("%32S*",$username);
4309:
4310: my $nameseed=numval($username) << 21;
4311: my $domainseed=unpack("%32S*",$domain) << 10;
4312: my $courseseed=unpack("%32S*",$courseid);
4313:
4314: my $num1=$symbchck+$symbseed+$namechck;
4315: my $num2=$nameseed+$domainseed+$courseseed;
4316: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
4317: #&Apache::lonxml::debug("rndseed :$num:$symb");
4318: return "$num1,$num2";
1.155 albertel 4319: }
1.366 albertel 4320: }
4321:
1.443 albertel 4322: sub rndseed_64bit2 {
4323: my ($symb,$courseid,$domain,$username)=@_;
4324: {
4325: use integer;
4326: # strings need to be an even # of cahracters long, it it is odd the
4327: # last characters gets thrown away
4328: my $symbchck=unpack("%32S*",$symb.' ') << 21;
4329: my $symbseed=numval($symb) << 10;
4330: my $namechck=unpack("%32S*",$username.' ');
4331:
4332: my $nameseed=numval($username) << 21;
4333: my $domainseed=unpack("%32S*",$domain.' ') << 10;
4334: my $courseseed=unpack("%32S*",$courseid.' ');
4335:
4336: my $num1=$symbchck+$symbseed+$namechck;
4337: my $num2=$nameseed+$domainseed+$courseseed;
4338: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
4339: #&Apache::lonxml::debug("rndseed :$num:$symb");
4340: return "$num1,$num2";
4341: }
4342: }
4343:
1.366 albertel 4344: sub rndseed_CODE_64bit {
4345: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 4346: {
1.366 albertel 4347: use integer;
1.443 albertel 4348: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.366 albertel 4349: my $symbseed=numval($symb);
4350: my $CODEseed=numval($ENV{'scantron.CODE'}) << 16;
1.443 albertel 4351: my $courseseed=unpack("%32S*",$courseid.' ');
1.366 albertel 4352: my $num1=$symbseed+$CODEseed;
4353: my $num2=$courseseed+$symbchck;
4354: #&Apache::lonxml::debug("$symbseed:$CODEseed|$courseseed:$symbchck");
4355: #&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
4356: return "$num1,$num2";
4357: }
4358: }
4359:
4360: sub setup_random_from_rndseed {
4361: my ($rndseed)=@_;
4362: if ($rndseed =~/,/) {
4363: my ($num1,$num2)=split(/,/,$rndseed);
4364: &Math::Random::random_set_seed(abs($num1),abs($num2));
4365: } else {
4366: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 4367: }
1.36 albertel 4368: }
4369:
1.76 www 4370: sub ireceipt {
4371: my ($funame,$fudom,$fucourseid,$fusymb)=@_;
4372: my $cuname=unpack("%32C*",$funame);
4373: my $cudom=unpack("%32C*",$fudom);
4374: my $cucourseid=unpack("%32C*",$fucourseid);
4375: my $cusymb=unpack("%32C*",$fusymb);
1.77 www 4376: my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
1.76 www 4377: return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
4378: ($cunique%$cuname+
4379: $cunique%$cudom+
4380: $cusymb%$cuname+
4381: $cusymb%$cudom+
4382: $cucourseid%$cuname+
4383: $cucourseid%$cudom);
4384: }
4385:
4386: sub receipt {
1.260 ng 4387: my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
4388: return &ireceipt($name,$domain,$courseid,$symb);
1.76 www 4389: }
1.260 ng 4390:
1.36 albertel 4391: # ------------------------------------------------------------ Serves up a file
4392: # returns either the contents of the file or a -1
4393: sub getfile {
1.269 www 4394: my $file=shift;
4395: if ($file=~/^\/*uploaded\//) { # user file
4396: my $ua=new LWP::UserAgent;
4397: my $request=new HTTP::Request('GET',&tokenwrapper($file));
4398: my $response=$ua->request($request);
4399: if ($response->is_success()) {
4400: return $response->content;
4401: } else {
4402: return -1;
4403: }
4404: } else { # normal file from res space
1.37 www 4405: &repcopy($file);
1.36 albertel 4406: if (! -e $file ) { return -1; };
1.448 albertel 4407: my $fh;
4408: open($fh,"<$file");
1.36 albertel 4409: my $a='';
4410: while (<$fh>) { $a .=$_; }
1.269 www 4411: return $a;
4412: }
1.36 albertel 4413: }
4414:
4415: sub filelocation {
4416: my ($dir,$file) = @_;
4417: my $location;
4418: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.59 albertel 4419: if ($file=~m:^/~:) { # is a contruction space reference
4420: $location = $file;
4421: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.270 www 4422: } elsif ($file=~/^\/*uploaded/) { # is an uploaded file
4423: $location=$file;
1.36 albertel 4424: } else {
1.59 albertel 4425: $file=~s/^$perlvar{'lonDocRoot'}//;
4426: $file=~s:^/*res::;
4427: if ( !( $file =~ m:^/:) ) {
4428: $location = $dir. '/'.$file;
4429: } else {
4430: $location = '/home/httpd/html/res'.$file;
4431: }
1.36 albertel 4432: }
4433: $location=~s://+:/:g; # remove duplicate /
1.46 www 4434: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
4435: return $location;
4436: }
1.36 albertel 4437:
1.46 www 4438: sub hreflocation {
4439: my ($dir,$file)=@_;
1.191 harris41 4440: unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
1.46 www 4441: my $finalpath=filelocation($dir,$file);
4442: $finalpath=~s/^\/home\/httpd\/html//;
1.225 albertel 4443: $finalpath=~s-/home/(\w+)/public_html/-/~$1/-;
1.46 www 4444: return $finalpath;
4445: } else {
4446: return $file;
4447: }
1.31 www 4448: }
4449:
4450: # ------------------------------------------------------------- Declutters URLs
4451:
4452: sub declutter {
4453: my $thisfn=shift;
4454: $thisfn=~s/^$perlvar{'lonDocRoot'}//;
4455: $thisfn=~s/^\///;
4456: $thisfn=~s/^res\///;
1.235 www 4457: $thisfn=~s/\?.+$//;
1.268 www 4458: return $thisfn;
4459: }
4460:
4461: # ------------------------------------------------------------- Clutter up URLs
4462:
4463: sub clutter {
4464: my $thisfn='/'.&declutter(shift);
1.270 www 4465: unless ($thisfn=~/^\/(uploaded|adm|userfiles|ext|raw|priv)\//) {
4466: $thisfn='/res'.$thisfn;
4467: }
1.31 www 4468: return $thisfn;
1.12 www 4469: }
4470:
4471: # -------------------------------------------------------- Escape Special Chars
4472:
4473: sub escape {
4474: my $str=shift;
4475: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
4476: return $str;
4477: }
4478:
4479: # ----------------------------------------------------- Un-Escape Special Chars
4480:
4481: sub unescape {
4482: my $str=shift;
4483: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
4484: return $str;
4485: }
1.11 www 4486:
1.415 albertel 4487: sub mod_perl_version {
4488: if (defined($perlvar{'MODPERL2'})) {
4489: return 2;
4490: }
4491: return 1;
1.436 albertel 4492: }
4493:
4494: sub correct_line_ends {
4495: my ($result)=@_;
4496: $$result =~s/\r\n/\n/mg;
4497: $$result =~s/\r/\n/mg;
1.415 albertel 4498: }
1.1 albertel 4499: # ================================================================ Main Program
4500:
1.184 www 4501: sub goodbye {
1.204 albertel 4502: &logthis("Starting Shut down");
1.443 albertel 4503: #not converted to using infrastruture and probably shouldn't be
1.425 albertel 4504: &logthis(sprintf("%-20s is %s",'%badServerCache',scalar(%badServerCache)));
1.443 albertel 4505: #converted
1.425 albertel 4506: &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.443 albertel 4507: &logthis(sprintf("%-20s is %s",'%homecache',scalar(%homecache)));
1.425 albertel 4508: &logthis(sprintf("%-20s is %s",'%titlecache',scalar(%titlecache)));
4509: &logthis(sprintf("%-20s is %s",'%courseresdatacache',scalar(%courseresdatacache)));
4510: #1.1 only
4511: &logthis(sprintf("%-20s is %s",'%userresdatacache',scalar(%userresdatacache)));
4512: &logthis(sprintf("%-20s is %s",'%usectioncache',scalar(%usectioncache)));
1.440 www 4513: &logthis(sprintf("%-20s is %s",'%courseresversioncache',scalar(%courseresversioncache)));
4514: &logthis(sprintf("%-20s is %s",'%resversioncache',scalar(%resversioncache)));
1.184 www 4515: &flushcourselogs();
4516: &logthis("Shutting down");
1.362 albertel 4517: return DONE;
1.184 www 4518: }
4519:
1.179 www 4520: BEGIN {
1.228 harris41 4521: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195 www 4522: unless ($readit) {
1.217 harris41 4523: {
1.448 albertel 4524: open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217 harris41 4525:
4526: while (my $configline=<$config>) {
4527: if ($configline =~ /^[^\#]*PerlSetVar/) {
1.1 albertel 4528: my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8 www 4529: chomp($varvalue);
1.1 albertel 4530: $perlvar{$varname}=$varvalue;
4531: }
4532: }
1.448 albertel 4533: close($config);
1.1 albertel 4534: }
1.227 harris41 4535: {
1.448 albertel 4536: open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227 harris41 4537:
4538: while (my $configline=<$config>) {
4539: if ($configline =~ /^[^\#]*PerlSetVar/) {
4540: my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
4541: chomp($varvalue);
4542: $perlvar{$varname}=$varvalue;
4543: }
4544: }
1.448 albertel 4545: close($config);
1.227 harris41 4546: }
1.1 albertel 4547:
1.327 albertel 4548: # ------------------------------------------------------------ Read domain file
4549: {
4550: %domaindescription = ();
4551: %domain_auth_def = ();
4552: %domain_auth_arg_def = ();
1.448 albertel 4553: my $fh;
4554: if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327 albertel 4555: while (<$fh>) {
1.390 matthew 4556: next if (/^(\#|\s*$)/);
4557: # next if /^\#/;
1.327 albertel 4558: chomp;
1.403 www 4559: my ($domain, $domain_description, $def_auth, $def_auth_arg,
4560: $def_lang, $city, $longi, $lati) = split(/:/,$_);
4561: $domain_auth_def{$domain}=$def_auth;
1.327 albertel 4562: $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403 www 4563: $domaindescription{$domain}=$domain_description;
4564: $domain_lang_def{$domain}=$def_lang;
4565: $domain_city{$domain}=$city;
4566: $domain_longi{$domain}=$longi;
4567: $domain_lati{$domain}=$lati;
4568:
1.448 albertel 4569: # &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327 albertel 4570: # &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448 albertel 4571: }
1.327 albertel 4572: }
1.448 albertel 4573: close ($fh);
1.327 albertel 4574: }
4575:
4576:
1.1 albertel 4577: # ------------------------------------------------------------- Read hosts file
4578: {
1.448 albertel 4579: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1 albertel 4580:
4581: while (my $configline=<$config>) {
1.303 matthew 4582: next if ($configline =~ /^(\#|\s*$)/);
1.154 www 4583: chomp($configline);
1.245 www 4584: my ($id,$domain,$role,$name,$ip,$domdescr)=split(/:/,$configline);
1.252 albertel 4585: if ($id && $domain && $role && $name && $ip) {
4586: $hostname{$id}=$name;
4587: $hostdom{$id}=$domain;
4588: $hostip{$id}=$ip;
1.300 albertel 4589: $iphost{$ip}=$id;
1.252 albertel 4590: if ($role eq 'library') { $libserv{$id}=$name; }
4591: } else {
4592: if ($configline) {
4593: &logthis("Skipping hosts.tab line -$configline-");
4594: }
1.245 www 4595: }
1.1 albertel 4596: }
1.448 albertel 4597: close($config);
1.1 albertel 4598: }
4599:
4600: # ------------------------------------------------------ Read spare server file
4601: {
1.448 albertel 4602: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 4603:
4604: while (my $configline=<$config>) {
4605: chomp($configline);
1.284 matthew 4606: if ($configline) {
1.1 albertel 4607: $spareid{$configline}=1;
4608: }
4609: }
1.448 albertel 4610: close($config);
1.1 albertel 4611: }
1.11 www 4612: # ------------------------------------------------------------ Read permissions
4613: {
1.448 albertel 4614: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 4615:
4616: while (my $configline=<$config>) {
1.448 albertel 4617: chomp($configline);
4618: if ($configline) {
4619: my ($role,$perm)=split(/ /,$configline);
4620: if ($perm ne '') { $pr{$role}=$perm; }
4621: }
1.11 www 4622: }
1.448 albertel 4623: close($config);
1.11 www 4624: }
4625:
4626: # -------------------------------------------- Read plain texts for permissions
4627: {
1.448 albertel 4628: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 4629:
4630: while (my $configline=<$config>) {
1.448 albertel 4631: chomp($configline);
4632: if ($configline) {
4633: my ($short,$plain)=split(/:/,$configline);
4634: if ($plain ne '') { $prp{$short}=$plain; }
4635: }
1.135 www 4636: }
1.448 albertel 4637: close($config);
1.135 www 4638: }
4639:
4640: # ---------------------------------------------------------- Read package table
4641: {
1.448 albertel 4642: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 4643:
4644: while (my $configline=<$config>) {
1.448 albertel 4645: chomp($configline);
4646: my ($short,$plain)=split(/:/,$configline);
4647: my ($pack,$name)=split(/\&/,$short);
4648: if ($plain ne '') {
4649: $packagetab{$pack.'&'.$name.'&name'}=$name;
4650: $packagetab{$short}=$plain;
4651: }
1.11 www 4652: }
1.448 albertel 4653: close($config);
1.329 matthew 4654: }
4655:
4656: # ------------- set up temporary directory
4657: {
4658: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
4659:
1.11 www 4660: }
4661:
1.71 www 4662: %metacache=();
1.185 www 4663:
1.281 www 4664: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 4665: $dumpcount=0;
1.22 www 4666:
1.163 harris41 4667: &logtouch();
1.12 www 4668: &logthis('<font color=yellow>INFO: Read configuration</font>');
1.195 www 4669: $readit=1;
4670: }
1.1 albertel 4671: }
1.179 www 4672:
1.1 albertel 4673: 1;
1.191 harris41 4674: __END__
4675:
1.243 albertel 4676: =pod
4677:
1.191 harris41 4678: =head1 NAME
4679:
1.243 albertel 4680: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 4681:
4682: =head1 SYNOPSIS
4683:
1.243 albertel 4684: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 4685:
4686: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
4687:
1.243 albertel 4688: Common parameters:
4689:
4690: =over 4
4691:
4692: =item *
4693:
4694: $uname : an internal username (if $cname expecting a course Id specifically)
4695:
4696: =item *
4697:
4698: $udom : a domain (if $cdom expecting a course's domain specifically)
4699:
4700: =item *
4701:
4702: $symb : a resource instance identifier
4703:
4704: =item *
4705:
4706: $namespace : the name of a .db file that contains the data needed or
4707: being set.
4708:
4709: =back
4710:
1.394 bowersj2 4711: =head1 OVERVIEW
1.191 harris41 4712:
1.394 bowersj2 4713: lonnet provides subroutines which interact with the
4714: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
4715: about classes, users, and resources.
1.243 albertel 4716:
4717: For many of these objects you can also use this to store data about
4718: them or modify them in various ways.
1.191 harris41 4719:
1.394 bowersj2 4720: =head2 Symbs
1.191 harris41 4721:
1.394 bowersj2 4722: To identify a specific instance of a resource, LON-CAPA uses symbols
4723: or "symbs"X<symb>. These identifiers are built from the URL of the
4724: map, the resource number of the resource in the map, and the URL of
4725: the resource itself. The latter is somewhat redundant, but might help
4726: if maps change.
4727:
4728: An example is
4729:
4730: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
4731:
4732: The respective map entry is
4733:
4734: <resource id="19" src="/res/msu/korte/tests/part12.problem"
4735: title="Problem 2">
4736: </resource>
4737:
4738: Symbs are used by the random number generator, as well as to store and
4739: restore data specific to a certain instance of for example a problem.
4740:
4741: =head2 Storing And Retrieving Data
4742:
4743: X<store()>X<cstore()>X<restore()>Three of the most important functions
4744: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
4745: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
4746: is is the non-critical message twin of cstore. These functions are for
4747: handlers to store a perl hash to a user's permanent data space in an
4748: easy manner, and to retrieve it again on another call. It is expected
4749: that a handler would use this once at the beginning to retrieve data,
4750: and then again once at the end to send only the new data back.
4751:
4752: The data is stored in the user's data directory on the user's
4753: homeserver under the ID of the course.
4754:
4755: The hash that is returned by restore will have all of the previous
4756: value for all of the elements of the hash.
4757:
4758: Example:
4759:
4760: #creating a hash
4761: my %hash;
4762: $hash{'foo'}='bar';
4763:
4764: #storing it
4765: &Apache::lonnet::cstore(\%hash);
4766:
4767: #changing a value
4768: $hash{'foo'}='notbar';
4769:
4770: #adding a new value
4771: $hash{'bar'}='foo';
4772: &Apache::lonnet::cstore(\%hash);
4773:
4774: #retrieving the hash
4775: my %history=&Apache::lonnet::restore();
4776:
4777: #print the hash
4778: foreach my $key (sort(keys(%history))) {
4779: print("\%history{$key} = $history{$key}");
4780: }
4781:
4782: Will print out:
1.191 harris41 4783:
1.394 bowersj2 4784: %history{1:foo} = bar
4785: %history{1:keys} = foo:timestamp
4786: %history{1:timestamp} = 990455579
4787: %history{2:bar} = foo
4788: %history{2:foo} = notbar
4789: %history{2:keys} = foo:bar:timestamp
4790: %history{2:timestamp} = 990455580
4791: %history{bar} = foo
4792: %history{foo} = notbar
4793: %history{timestamp} = 990455580
4794: %history{version} = 2
4795:
4796: Note that the special hash entries C<keys>, C<version> and
4797: C<timestamp> were added to the hash. C<version> will be equal to the
4798: total number of versions of the data that have been stored. The
4799: C<timestamp> attribute will be the UNIX time the hash was
4800: stored. C<keys> is available in every historical section to list which
4801: keys were added or changed at a specific historical revision of a
4802: hash.
4803:
4804: B<Warning>: do not store the hash that restore returns directly. This
4805: will cause a mess since it will restore the historical keys as if the
4806: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 4807:
1.394 bowersj2 4808: Calling convention:
1.191 harris41 4809:
1.394 bowersj2 4810: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
4811: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 4812:
1.394 bowersj2 4813: For more detailed information, see lonnet specific documentation.
1.191 harris41 4814:
1.394 bowersj2 4815: =head1 RETURN MESSAGES
1.191 harris41 4816:
1.394 bowersj2 4817: =over 4
1.191 harris41 4818:
1.394 bowersj2 4819: =item * B<con_lost>: unable to contact remote host
1.191 harris41 4820:
1.394 bowersj2 4821: =item * B<con_delayed>: unable to contact remote host, message will be delivered
4822: when the connection is brought back up
1.191 harris41 4823:
1.394 bowersj2 4824: =item * B<con_failed>: unable to contact remote host and unable to save message
4825: for later delivery
1.191 harris41 4826:
1.394 bowersj2 4827: =item * B<error:>: an error a occured, a description of the error follows the :
1.191 harris41 4828:
1.394 bowersj2 4829: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 4830: that was requested
1.191 harris41 4831:
1.243 albertel 4832: =back
1.191 harris41 4833:
1.243 albertel 4834: =head1 PUBLIC SUBROUTINES
1.191 harris41 4835:
1.243 albertel 4836: =head2 Session Environment Functions
1.191 harris41 4837:
1.243 albertel 4838: =over 4
1.191 harris41 4839:
1.394 bowersj2 4840: =item *
4841: X<appenv()>
4842: B<appenv(%hash)>: the value of %hash is written to
4843: the user envirnoment file, and will be restored for each access this
4844: user makes during this session, also modifies the %ENV for the current
4845: process
1.191 harris41 4846:
4847: =item *
1.394 bowersj2 4848: X<delenv()>
4849: B<delenv($regexp)>: removes all items from the session
4850: environment file that matches the regular expression in $regexp. The
4851: values are also delted from the current processes %ENV.
1.191 harris41 4852:
1.243 albertel 4853: =back
4854:
4855: =head2 User Information
1.191 harris41 4856:
1.243 albertel 4857: =over 4
1.191 harris41 4858:
4859: =item *
1.394 bowersj2 4860: X<queryauthenticate()>
4861: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 4862: authentication scheme
4863:
4864: =item *
1.394 bowersj2 4865: X<authenticate()>
4866: B<authenticate($uname,$upass,$udom)>: try to
4867: authenticate user from domain's lib servers (first use the current
4868: one). C<$upass> should be the users password.
1.191 harris41 4869:
4870: =item *
1.394 bowersj2 4871: X<homeserver()>
4872: B<homeserver($uname,$udom)>: find the server which has
4873: the user's directory and files (there must be only one), this caches
4874: the answer, and also caches if there is a borken connection.
1.191 harris41 4875:
4876: =item *
1.394 bowersj2 4877: X<idget()>
4878: B<idget($udom,@ids)>: find the usernames behind a list of IDs
4879: (IDs are a unique resource in a domain, there must be only 1 ID per
4880: username, and only 1 username per ID in a specific domain) (returns
4881: hash: id=>name,id=>name)
1.191 harris41 4882:
4883: =item *
1.394 bowersj2 4884: X<idrget()>
4885: B<idrget($udom,@unames)>: find the IDs behind a list of
4886: usernames (returns hash: name=>id,name=>id)
1.191 harris41 4887:
4888: =item *
1.394 bowersj2 4889: X<idput()>
4890: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 4891:
4892: =item *
1.394 bowersj2 4893: X<rolesinit()>
4894: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 4895:
4896: =item *
1.394 bowersj2 4897: X<usection()>
4898: B<usection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 4899: course $cname, return section name/number or '' for "not in course"
4900: and '-1' for "no section"
4901:
4902: =item *
1.394 bowersj2 4903: X<userenvironment()>
4904: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 4905: passed in @what from the requested user's environment, returns a hash
4906:
4907: =back
4908:
4909: =head2 User Roles
4910:
4911: =over 4
4912:
4913: =item *
4914:
4915: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
4916: actions
4917: F: full access
4918: U,I,K: authentication modes (cxx only)
4919: '': forbidden
4920: 1: user needs to choose course
4921: 2: browse allowed
4922:
4923: =item *
4924:
4925: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
4926: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
4927: and course level
4928:
4929: =item *
4930:
4931: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
4932: explanation of a user role term
4933:
4934: =back
4935:
4936: =head2 User Modification
4937:
4938: =over 4
4939:
4940: =item *
4941:
4942: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
4943: user for the level given by URL. Optional start and end dates (leave empty
4944: string or zero for "no date")
1.191 harris41 4945:
4946: =item *
4947:
1.243 albertel 4948: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
4949: change a users, password, possible return values are: ok,
4950: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
4951: refused
1.191 harris41 4952:
4953: =item *
4954:
1.243 albertel 4955: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 4956:
4957: =item *
4958:
1.243 albertel 4959: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
4960: modify user
1.191 harris41 4961:
4962: =item *
4963:
1.286 matthew 4964: modifystudent
4965:
4966: modify a students enrollment and identification information.
4967: The course id is resolved based on the current users environment.
4968: This means the envoking user must be a course coordinator or otherwise
4969: associated with a course.
4970:
1.297 matthew 4971: This call is essentially a wrapper for lonnet::modifyuser and
4972: lonnet::modify_student_enrollment
1.286 matthew 4973:
4974: Inputs:
4975:
4976: =over 4
4977:
4978: =item B<$udom> Students loncapa domain
4979:
4980: =item B<$uname> Students loncapa login name
4981:
4982: =item B<$uid> Students id/student number
4983:
4984: =item B<$umode> Students authentication mode
4985:
4986: =item B<$upass> Students password
4987:
4988: =item B<$first> Students first name
4989:
4990: =item B<$middle> Students middle name
4991:
4992: =item B<$last> Students last name
4993:
4994: =item B<$gene> Students generation
4995:
4996: =item B<$usec> Students section in course
4997:
4998: =item B<$end> Unix time of the roles expiration
4999:
5000: =item B<$start> Unix time of the roles start date
5001:
5002: =item B<$forceid> If defined, allow $uid to be changed
5003:
5004: =item B<$desiredhome> server to use as home server for student
5005:
5006: =back
1.297 matthew 5007:
5008: =item *
5009:
5010: modify_student_enrollment
5011:
5012: Change a students enrollment status in a class. The environment variable
5013: 'role.request.course' must be defined for this function to proceed.
5014:
5015: Inputs:
5016:
5017: =over 4
5018:
5019: =item $udom, students domain
5020:
5021: =item $uname, students name
5022:
5023: =item $uid, students user id
5024:
5025: =item $first, students first name
5026:
5027: =item $middle
5028:
5029: =item $last
5030:
5031: =item $gene
5032:
5033: =item $usec
5034:
5035: =item $end
5036:
5037: =item $start
5038:
5039: =back
5040:
1.191 harris41 5041:
5042: =item *
5043:
1.243 albertel 5044: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
5045: custom role; give a custom role to a user for the level given by URL. Specify
5046: name and domain of role author, and role name
1.191 harris41 5047:
5048: =item *
5049:
1.243 albertel 5050: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 5051:
5052: =item *
5053:
1.243 albertel 5054: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
5055:
5056: =back
5057:
5058: =head2 Course Infomation
5059:
5060: =over 4
1.191 harris41 5061:
5062: =item *
5063:
1.243 albertel 5064: coursedescription($courseid) : course description
1.191 harris41 5065:
5066: =item *
5067:
1.243 albertel 5068: courseresdata($coursenum,$coursedomain,@which) : request for current
5069: parameter setting for a specific course, @what should be a list of
5070: parameters to ask about. This routine caches answers for 5 minutes.
5071:
5072: =back
5073:
5074: =head2 Course Modification
5075:
5076: =over 4
1.191 harris41 5077:
5078: =item *
5079:
1.243 albertel 5080: writecoursepref($courseid,%prefs) : write preferences (environment
5081: database) for a course
1.191 harris41 5082:
5083: =item *
5084:
1.243 albertel 5085: createcourse($udom,$description,$url) : make/modify course
5086:
5087: =back
5088:
5089: =head2 Resource Subroutines
5090:
5091: =over 4
1.191 harris41 5092:
5093: =item *
5094:
1.243 albertel 5095: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 5096:
5097: =item *
5098:
1.243 albertel 5099: repcopy($filename) : subscribes to the requested file, and attempts to
5100: replicate from the owning library server, Might return
5101: HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND, FORBIDDEN, OK, or
5102: HTTP_BAD_REQUEST, also attempts to grab the metadata for the
5103: resource. Expects the local filesystem pathname
5104: (/home/httpd/html/res/....)
5105:
5106: =back
5107:
5108: =head2 Resource Information
5109:
5110: =over 4
1.191 harris41 5111:
5112: =item *
5113:
1.243 albertel 5114: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
5115: a vairety of different possible values, $varname should be a request
5116: string, and the other parameters can be used to specify who and what
5117: one is asking about.
5118:
5119: Possible values for $varname are environment.lastname (or other item
5120: from the envirnment hash), user.name (or someother aspect about the
5121: user), resource.0.maxtries (or some other part and parameter of a
5122: resource)
1.204 albertel 5123:
5124: =item *
5125:
1.243 albertel 5126: directcondval($number) : get current value of a condition; reads from a state
5127: string
1.204 albertel 5128:
5129: =item *
5130:
1.243 albertel 5131: condval($condidx) : value of condition index based on state
1.204 albertel 5132:
5133: =item *
5134:
1.243 albertel 5135: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
5136: resource's metadata, $what should be either a specific key, or either
5137: 'keys' (to get a list of possible keys) or 'packages' to get a list of
5138: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
5139:
5140: this function automatically caches all requests
1.191 harris41 5141:
5142: =item *
5143:
1.243 albertel 5144: metadata_query($query,$custom,$customshow) : make a metadata query against the
5145: network of library servers; returns file handle of where SQL and regex results
5146: will be stored for query
1.191 harris41 5147:
5148: =item *
5149:
1.243 albertel 5150: symbread($filename) : return symbolic list entry (filename argument optional);
5151: returns the data handle
1.191 harris41 5152:
5153: =item *
5154:
1.243 albertel 5155: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
5156: a possible symb for the URL in $thisfn, returns a 1 on success, 0 on
5157: failure, user must be in a course, as it assumes the existance of the
5158: course initi hash, and uses $ENV('request.course.id'}
5159:
1.191 harris41 5160:
5161: =item *
5162:
1.243 albertel 5163: symbclean($symb) : removes versions numbers from a symb, returns the
5164: cleaned symb
1.191 harris41 5165:
5166: =item *
5167:
1.243 albertel 5168: is_on_map($uri) : checks if the $uri is somewhere on the current
5169: course map, user must be in a course for it to work.
1.191 harris41 5170:
5171: =item *
5172:
1.243 albertel 5173: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 5174:
5175: =item *
5176:
1.243 albertel 5177: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
5178: a random seed, all arguments are optional, if they aren't sent it uses the
5179: environment to derive them. Note: if symb isn't sent and it can't get one
5180: from &symbread it will use the current time as its return value
1.191 harris41 5181:
5182: =item *
5183:
1.243 albertel 5184: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
5185: unfakeable, receipt
1.191 harris41 5186:
5187: =item *
5188:
1.243 albertel 5189: receipt() : API to ireceipt working off of ENV values; given out to users
1.191 harris41 5190:
5191: =item *
5192:
1.243 albertel 5193: countacc($url) : count the number of accesses to a given URL
1.191 harris41 5194:
5195: =item *
5196:
1.243 albertel 5197: 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 5198:
5199: =item *
5200:
1.243 albertel 5201: 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 5202:
5203: =item *
5204:
1.243 albertel 5205: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 5206:
5207: =item *
5208:
1.243 albertel 5209: devalidate($symb) : devalidate temporary spreadsheet calculations,
5210: forcing spreadsheet to reevaluate the resource scores next time.
5211:
5212: =back
5213:
5214: =head2 Storing/Retreiving Data
5215:
5216: =over 4
1.191 harris41 5217:
5218: =item *
5219:
1.243 albertel 5220: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
5221: for this url; hashref needs to be given and should be a \%hashname; the
5222: remaining args aren't required and if they aren't passed or are '' they will
5223: be derived from the ENV
1.191 harris41 5224:
5225: =item *
5226:
1.243 albertel 5227: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
5228: uses critical subroutine
1.191 harris41 5229:
5230: =item *
5231:
1.243 albertel 5232: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
5233: all args are optional
1.191 harris41 5234:
5235: =item *
5236:
1.243 albertel 5237: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
5238: works very similar to store/cstore, but all data is stored in a
5239: temporary location and can be reset using tmpreset, $storehash should
5240: be a hash reference, returns nothing on success
1.191 harris41 5241:
5242: =item *
5243:
1.243 albertel 5244: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
5245: similar to restore, but all data is stored in a temporary location and
5246: can be reset using tmpreset. Returns a hash of values on success,
5247: error string otherwise.
1.191 harris41 5248:
5249: =item *
5250:
1.243 albertel 5251: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
5252: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 5253:
5254: =item *
5255:
1.243 albertel 5256: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
5257: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 5258:
5259: =item *
5260:
1.243 albertel 5261: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
5262: namesp ($udom and $uname are optional)
1.191 harris41 5263:
5264: =item *
5265:
1.243 albertel 5266: dump($namespace,$udom,$uname,$regexp) :
5267: dumps the complete (or key matching regexp) namespace into a hash
5268: ($udom, $uname and $regexp are optional)
1.449 matthew 5269:
5270: =item *
5271:
5272: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
5273: $store can be a scalar, an array reference, or if the amount to be
5274: incremented is > 1, a hash reference.
5275:
5276: ($udom and $uname are optional)
1.191 harris41 5277:
5278: =item *
5279:
1.243 albertel 5280: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
5281: ($udom and $uname are optional)
1.191 harris41 5282:
5283: =item *
5284:
1.243 albertel 5285: cput($namespace,$storehash,$udom,$uname) : critical put
5286: ($udom and $uname are optional)
1.191 harris41 5287:
5288: =item *
5289:
1.243 albertel 5290: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
5291: reference filled in from namesp (encrypts the return communication)
5292: ($udom and $uname are optional)
1.191 harris41 5293:
5294: =item *
5295:
1.243 albertel 5296: log($udom,$name,$home,$message) : write to permanent log for user; use
5297: critical subroutine
5298:
5299: =back
5300:
5301: =head2 Network Status Functions
5302:
5303: =over 4
1.191 harris41 5304:
5305: =item *
5306:
5307: dirlist($uri) : return directory list based on URI
5308:
5309: =item *
5310:
1.243 albertel 5311: spareserver() : find server with least workload from spare.tab
5312:
5313: =back
5314:
5315: =head2 Apache Request
5316:
5317: =over 4
1.191 harris41 5318:
5319: =item *
5320:
1.243 albertel 5321: ssi($url,%hash) : server side include, does a complete request cycle on url to
5322: localhost, posts hash
5323:
5324: =back
5325:
5326: =head2 Data to String to Data
5327:
5328: =over 4
1.191 harris41 5329:
5330: =item *
5331:
1.243 albertel 5332: hash2str(%hash) : convert a hash into a string complete with escaping and '='
5333: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 5334:
5335: =item *
5336:
1.243 albertel 5337: hashref2str($hashref) : convert a hashref into a string complete with
5338: escaping and '=' and '&' separators, supports elements that are
5339: arrayrefs and hashrefs
1.191 harris41 5340:
5341: =item *
5342:
1.243 albertel 5343: arrayref2str($arrayref) : convert an arrayref into a string complete
5344: with escaping and '&' separators, supports elements that are arrayrefs
5345: and hashrefs
1.191 harris41 5346:
5347: =item *
5348:
1.243 albertel 5349: str2hash($string) : convert string to hash using unescaping and
5350: splitting on '=' and '&', supports elements that are arrayrefs and
5351: hashrefs
1.191 harris41 5352:
5353: =item *
5354:
1.243 albertel 5355: str2array($string) : convert string to hash using unescaping and
5356: splitting on '&', supports elements that are arrayrefs and hashrefs
5357:
5358: =back
5359:
5360: =head2 Logging Routines
5361:
5362: =over 4
5363:
5364: These routines allow one to make log messages in the lonnet.log and
5365: lonnet.perm logfiles.
1.191 harris41 5366:
5367: =item *
5368:
1.243 albertel 5369: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 5370:
5371: =item *
5372:
1.243 albertel 5373: logthis() : append message to the normal lonnet.log file, it gets
5374: preiodically rolled over and deleted.
1.191 harris41 5375:
5376: =item *
5377:
1.243 albertel 5378: logperm() : append a permanent message to lonnet.perm.log, this log
5379: file never gets deleted by any automated portion of the system, only
5380: messages of critical importance should go in here.
5381:
5382: =back
5383:
5384: =head2 General File Helper Routines
5385:
5386: =over 4
1.191 harris41 5387:
5388: =item *
5389:
1.243 albertel 5390: getfile($file) : returns the entire contents of a file or -1; it
5391: properly subscribes to and replicates the file if neccessary.
1.191 harris41 5392:
5393: =item *
5394:
1.243 albertel 5395: filelocation($dir,$file) : returns file system location of a file
5396: based on URI; meant to be "fairly clean" absolute reference, $dir is a
5397: directory that relative $file lookups are to looked in ($dir of /a/dir
5398: and a file of ../bob will become /a/bob)
1.191 harris41 5399:
5400: =item *
5401:
5402: hreflocation($dir,$file) : returns file system location or a URL; same as
5403: filelocation except for hrefs
5404:
5405: =item *
5406:
5407: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
5408:
1.243 albertel 5409: =back
5410:
5411: =head2 HTTP Helper Routines
5412:
5413: =over 4
5414:
1.191 harris41 5415: =item *
5416:
5417: escape() : unpack non-word characters into CGI-compatible hex codes
5418:
5419: =item *
5420:
5421: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
5422:
1.243 albertel 5423: =back
5424:
5425: =head1 PRIVATE SUBROUTINES
5426:
5427: =head2 Underlying communication routines (Shouldn't call)
5428:
5429: =over 4
5430:
5431: =item *
5432:
5433: subreply() : tries to pass a message to lonc, returns con_lost if incapable
5434:
5435: =item *
5436:
5437: reply() : uses subreply to send a message to remote machine, logs all failures
5438:
5439: =item *
5440:
5441: critical() : passes a critical message to another server; if cannot
5442: get through then place message in connection buffer directory and
5443: returns con_delayed, if incapable of saving message, returns
5444: con_failed
5445:
5446: =item *
5447:
5448: reconlonc() : tries to reconnect lonc client processes.
5449:
5450: =back
5451:
5452: =head2 Resource Access Logging
5453:
5454: =over 4
5455:
5456: =item *
5457:
5458: flushcourselogs() : flush (save) buffer logs and access logs
5459:
5460: =item *
5461:
5462: courselog($what) : save message for course in hash
5463:
5464: =item *
5465:
5466: courseacclog($what) : save message for course using &courselog(). Perform
5467: special processing for specific resource types (problems, exams, quizzes, etc).
5468:
1.191 harris41 5469: =item *
5470:
5471: goodbye() : flush course logs and log shutting down; it is called in srm.conf
5472: as a PerlChildExitHandler
1.243 albertel 5473:
5474: =back
5475:
5476: =head2 Other
5477:
5478: =over 4
5479:
5480: =item *
5481:
5482: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 5483:
5484: =back
5485:
5486: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>