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