Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.637
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.637 ! raeburn 4: # $Id: lonnet.pm,v 1.636 2005/05/25 21:33:35 albertel Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.1 albertel 30: package Apache::lonnet;
31:
32: use strict;
1.8 www 33: use LWP::UserAgent();
1.15 www 34: use HTTP::Headers;
1.486 www 35: use HTTP::Date;
36: # use Date::Parse;
1.11 www 37: use vars
1.599 albertel 38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom
39: %libserv %pr %prp $memcache %packagetab
1.349 www 40: %courselogs %accesshash %userrolehash $processmarker $dumpcount
1.599 albertel 41: %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf
42: %domaindescription %domain_auth_def %domain_auth_arg_def
1.619 albertel 43: %domain_lang_def %domain_city %domain_longi %domain_lati $tmpdir $_64bit
44: %env);
1.403 www 45:
1.1 albertel 46: use IO::Socket;
1.31 www 47: use GDBM_File;
1.8 www 48: use Apache::Constants qw(:common :http);
1.208 albertel 49: use HTML::LCParser;
1.637 ! raeburn 50: use HTML::Parser;
1.88 www 51: use Fcntl qw(:flock);
1.414 www 52: use Apache::lonlocal;
1.557 albertel 53: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539 albertel 54: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 55: use Cache::Memcached;
1.195 www 56: my $readit;
1.550 foxr 57: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 58:
1.619 albertel 59: require Exporter;
60:
61: our @ISA = qw (Exporter);
62: our @EXPORT = qw(%env);
63:
1.449 matthew 64: =pod
65:
66: =head1 Package Variables
67:
68: These are largely undocumented, so if you decipher one please note it here.
69:
70: =over 4
71:
72: =item $processmarker
73:
74: Contains the time this process was started and this servers host id.
75:
76: =item $dumpcount
77:
78: Counts the number of times a message log flush has been attempted (regardless
79: of success) by this process. Used as part of the filename when messages are
80: delayed.
81:
82: =back
83:
84: =cut
85:
86:
1.1 albertel 87: # --------------------------------------------------------------------- Logging
88:
1.163 harris41 89: sub logtouch {
90: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 91: unless (-e "$execdir/logs/lonnet.log") {
92: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 93: close $fh;
94: }
95: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
96: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
97: }
98:
1.1 albertel 99: sub logthis {
100: my $message=shift;
101: my $execdir=$perlvar{'lonDaemons'};
102: my $now=time;
103: my $local=localtime($now);
1.448 albertel 104: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
105: print $fh "$local ($$): $message\n";
106: close($fh);
107: }
1.1 albertel 108: return 1;
109: }
110:
111: sub logperm {
112: my $message=shift;
113: my $execdir=$perlvar{'lonDaemons'};
114: my $now=time;
115: my $local=localtime($now);
1.448 albertel 116: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
117: print $fh "$now:$message:$local\n";
118: close($fh);
119: }
1.1 albertel 120: return 1;
121: }
122:
123: # -------------------------------------------------- Non-critical communication
124: sub subreply {
125: my ($cmd,$server)=@_;
126: my $peerfile="$perlvar{'lonSockDir'}/$server";
1.549 foxr 127: #
128: # With loncnew process trimming, there's a timing hole between lonc server
129: # process exit and the master server picking up the listen on the AF_UNIX
130: # socket. In that time interval, a lock file will exist:
131:
132: my $lockfile=$peerfile.".lock";
133: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
134: sleep(1);
135: }
136: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 137: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 138: #
1.550 foxr 139: # We'll give the connection a few tries before abandoning it. If
140: # connection is not possible, we'll con_lost back to the client.
141: #
142: my $client;
143: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
144: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
145: Type => SOCK_STREAM,
146: Timeout => 10);
147: if($client) {
148: last; # Connected!
149: }
150: sleep(1); # Try again later if failed connection.
151: }
152: my $answer;
153: if ($client) {
154: print $client "$cmd\n";
155: $answer=<$client>;
156: if (!$answer) { $answer="con_lost"; }
157: chomp($answer);
158: } else {
159: $answer = 'con_lost'; # Failed connection.
160: }
1.1 albertel 161: return $answer;
162: }
163:
164: sub reply {
165: my ($cmd,$server)=@_;
1.205 www 166: unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1 albertel 167: my $answer=subreply($cmd,$server);
1.65 www 168: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.12 www 169: &logthis("<font color=blue>WARNING:".
170: " $cmd to $server returned $answer</font>");
171: }
1.1 albertel 172: return $answer;
173: }
174:
175: # ----------------------------------------------------------- Send USR1 to lonc
176:
177: sub reconlonc {
178: my $peerfile=shift;
179: &logthis("Trying to reconnect for $peerfile");
180: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 181: if (open(my $fh,"<$loncfile")) {
1.1 albertel 182: my $loncpid=<$fh>;
183: chomp($loncpid);
184: if (kill 0 => $loncpid) {
185: &logthis("lonc at pid $loncpid responding, sending USR1");
186: kill USR1 => $loncpid;
187: sleep 1;
188: if (-e "$peerfile") { return; }
189: &logthis("$peerfile still not there, give it another try");
190: sleep 5;
191: if (-e "$peerfile") { return; }
1.12 www 192: &logthis(
193: "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
1.1 albertel 194: } else {
1.12 www 195: &logthis(
196: "<font color=blue>WARNING:".
197: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 198: }
199: } else {
1.12 www 200: &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
1.1 albertel 201: }
202: }
203:
204: # ------------------------------------------------------ Critical communication
1.12 www 205:
1.1 albertel 206: sub critical {
207: my ($cmd,$server)=@_;
1.89 www 208: unless ($hostname{$server}) {
209: &logthis("<font color=blue>WARNING:".
210: " Critical message to unknown server ($server)</font>");
211: return 'no_such_host';
212: }
1.1 albertel 213: my $answer=reply($cmd,$server);
214: if ($answer eq 'con_lost') {
215: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 216: my $answer=reply($cmd,$server);
1.1 albertel 217: if ($answer eq 'con_lost') {
218: my $now=time;
219: my $middlename=$cmd;
1.5 www 220: $middlename=substr($middlename,0,16);
1.1 albertel 221: $middlename=~s/\W//g;
222: my $dfilename=
1.305 www 223: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
224: $dumpcount++;
1.1 albertel 225: {
1.448 albertel 226: my $dfh;
227: if (open($dfh,">$dfilename")) {
228: print $dfh "$cmd\n";
229: close($dfh);
230: }
1.1 albertel 231: }
232: sleep 2;
233: my $wcmd='';
234: {
1.448 albertel 235: my $dfh;
236: if (open($dfh,"<$dfilename")) {
237: $wcmd=<$dfh>;
238: close($dfh);
239: }
1.1 albertel 240: }
241: chomp($wcmd);
1.7 www 242: if ($wcmd eq $cmd) {
1.12 www 243: &logthis("<font color=blue>WARNING: ".
244: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 245: &logperm("D:$server:$cmd");
246: return 'con_delayed';
247: } else {
1.12 www 248: &logthis("<font color=red>CRITICAL:"
249: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 250: &logperm("F:$server:$cmd");
251: return 'con_failed';
252: }
253: }
254: }
255: return $answer;
1.405 albertel 256: }
257:
1.374 www 258: # ------------------------------------------- Transfer profile into environment
259:
260: sub transfer_profile_to_env {
261: my ($lonidsdir,$handle)=@_;
262: my @profile;
263: {
1.448 albertel 264: open(my $idf,"$lonidsdir/$handle.id");
1.374 www 265: flock($idf,LOCK_SH);
266: @profile=<$idf>;
1.448 albertel 267: close($idf);
1.374 www 268: }
269: my $envi;
1.433 matthew 270: my %Remove;
1.374 www 271: for ($envi=0;$envi<=$#profile;$envi++) {
272: chomp($profile[$envi]);
273: my ($envname,$envvalue)=split(/=/,$profile[$envi]);
1.619 albertel 274: $env{$envname} = $envvalue;
1.433 matthew 275: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
276: if ($time < time-300) {
277: $Remove{$key}++;
278: }
279: }
280: }
1.619 albertel 281: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.433 matthew 282: foreach my $expired_key (keys(%Remove)) {
283: &delenv($expired_key);
1.374 www 284: }
1.1 albertel 285: }
286:
1.5 www 287: # ---------------------------------------------------------- Append Environment
288:
289: sub appenv {
1.6 www 290: my %newenv=@_;
1.191 harris41 291: foreach (keys %newenv) {
1.35 www 292: if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
293: &logthis("<font color=blue>WARNING: ".
1.151 www 294: "Attempt to modify environment ".$_." to ".$newenv{$_}
295: .'</font>');
1.35 www 296: delete($newenv{$_});
297: } else {
1.619 albertel 298: $env{$_}=$newenv{$_};
1.35 www 299: }
1.191 harris41 300: }
1.95 www 301:
302: my $lockfh;
1.620 albertel 303: unless (open($lockfh,"$env{'user.environment'}")) {
1.448 albertel 304: return 'error: '.$!;
1.95 www 305: }
306: unless (flock($lockfh,LOCK_EX)) {
307: &logthis("<font color=blue>WARNING: ".
308: 'Could not obtain exclusive lock in appenv: '.$!);
1.448 albertel 309: close($lockfh);
1.95 www 310: return 'error: '.$!;
311: }
312:
1.6 www 313: my @oldenv;
314: {
1.448 albertel 315: my $fh;
1.620 albertel 316: unless (open($fh,"$env{'user.environment'}")) {
1.448 albertel 317: return 'error: '.$!;
318: }
319: @oldenv=<$fh>;
320: close($fh);
1.6 www 321: }
322: for (my $i=0; $i<=$#oldenv; $i++) {
323: chomp($oldenv[$i]);
1.9 www 324: if ($oldenv[$i] ne '') {
1.448 albertel 325: my ($name,$value)=split(/=/,$oldenv[$i]);
326: unless (defined($newenv{$name})) {
327: $newenv{$name}=$value;
328: }
1.9 www 329: }
1.6 www 330: }
331: {
1.448 albertel 332: my $fh;
1.620 albertel 333: unless (open($fh,">$env{'user.environment'}")) {
1.448 albertel 334: return 'error';
335: }
336: my $newname;
337: foreach $newname (keys %newenv) {
338: print $fh "$newname=$newenv{$newname}\n";
339: }
340: close($fh);
1.56 www 341: }
1.448 albertel 342:
343: close($lockfh);
1.56 www 344: return 'ok';
345: }
346: # ----------------------------------------------------- Delete from Environment
347:
348: sub delenv {
349: my $delthis=shift;
350: my %newenv=();
351: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
352: &logthis("<font color=blue>WARNING: ".
353: "Attempt to delete from environment ".$delthis);
354: return 'error';
355: }
356: my @oldenv;
357: {
1.448 albertel 358: my $fh;
1.620 albertel 359: unless (open($fh,"$env{'user.environment'}")) {
1.448 albertel 360: return 'error';
361: }
362: unless (flock($fh,LOCK_SH)) {
363: &logthis("<font color=blue>WARNING: ".
364: 'Could not obtain shared lock in delenv: '.$!);
365: close($fh);
366: return 'error: '.$!;
367: }
368: @oldenv=<$fh>;
369: close($fh);
1.56 www 370: }
371: {
1.448 albertel 372: my $fh;
1.620 albertel 373: unless (open($fh,">$env{'user.environment'}")) {
1.448 albertel 374: return 'error';
375: }
376: unless (flock($fh,LOCK_EX)) {
377: &logthis("<font color=blue>WARNING: ".
378: 'Could not obtain exclusive lock in delenv: '.$!);
379: close($fh);
380: return 'error: '.$!;
381: }
382: foreach (@oldenv) {
1.473 matthew 383: if ($_=~/^$delthis/) {
384: my ($key,undef) = split('=',$_);
1.619 albertel 385: delete($env{$key});
1.473 matthew 386: } else {
387: print $fh $_;
388: }
1.448 albertel 389: }
390: close($fh);
1.5 www 391: }
392: return 'ok';
1.369 albertel 393: }
394:
395: # ------------------------------------------ Find out current server userload
396: # there is a copy in lond
397: sub userload {
398: my $numusers=0;
399: {
400: opendir(LONIDS,$perlvar{'lonIDsDir'});
401: my $filename;
402: my $curtime=time;
403: while ($filename=readdir(LONIDS)) {
404: if ($filename eq '.' || $filename eq '..') {next;}
1.404 albertel 405: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 406: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 407: }
408: closedir(LONIDS);
409: }
410: my $userloadpercent=0;
411: my $maxuserload=$perlvar{'lonUserLoadLim'};
412: if ($maxuserload) {
1.371 albertel 413: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 414: }
1.372 albertel 415: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 416: return $userloadpercent;
1.283 www 417: }
418:
419: # ------------------------------------------ Fight off request when overloaded
420:
421: sub overloaderror {
422: my ($r,$checkserver)=@_;
423: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
424: my $loadavg;
425: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 426: open(my $loadfile,'/proc/loadavg');
1.283 www 427: $loadavg=<$loadfile>;
428: $loadavg =~ s/\s.*//g;
1.285 matthew 429: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 430: close($loadfile);
1.283 www 431: } else {
432: $loadavg=&reply('load',$checkserver);
433: }
1.285 matthew 434: my $overload=$loadavg-100;
1.283 www 435: if ($overload>0) {
1.285 matthew 436: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 437: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 438: return 413;
1.283 www 439: }
440: return '';
1.5 www 441: }
1.1 albertel 442:
443: # ------------------------------ Find server with least workload from spare.tab
1.11 www 444:
1.1 albertel 445: sub spareserver {
1.370 albertel 446: my ($loadpercent,$userloadpercent) = @_;
1.1 albertel 447: my $tryserver;
448: my $spareserver='';
1.370 albertel 449: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
450: my $lowestserver=$loadpercent > $userloadpercent?
451: $loadpercent : $userloadpercent;
1.1 albertel 452: foreach $tryserver (keys %spareid) {
1.411 albertel 453: my $loadans=reply('load',$tryserver);
454: my $userloadans=reply('userload',$tryserver);
455: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
456: next; #didn't get a number from the server
457: }
458: my $answer;
459: if ($loadans =~ /\d/) {
460: if ($userloadans =~ /\d/) {
461: #both are numbers, pick the bigger one
462: $answer=$loadans > $userloadans?
463: $loadans : $userloadans;
464: } else {
465: $answer = $loadans;
466: }
467: } else {
468: $answer = $userloadans;
469: }
470: if (($answer =~ /\d/) && ($answer<$lowestserver)) {
471: $spareserver="http://$hostname{$tryserver}";
472: $lowestserver=$answer;
473: }
1.370 albertel 474: }
1.1 albertel 475: return $spareserver;
1.202 matthew 476: }
477:
478: # --------------------------------------------- Try to change a user's password
479:
480: sub changepass {
481: my ($uname,$udom,$currentpass,$newpass,$server)=@_;
482: $currentpass = &escape($currentpass);
483: $newpass = &escape($newpass);
484: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
485: $server);
486: if (! $answer) {
487: &logthis("No reply on password change request to $server ".
488: "by $uname in domain $udom.");
489: } elsif ($answer =~ "^ok") {
490: &logthis("$uname in $udom successfully changed their password ".
491: "on $server.");
492: } elsif ($answer =~ "^pwchange_failure") {
493: &logthis("$uname in $udom was unable to change their password ".
494: "on $server. The action was blocked by either lcpasswd ".
495: "or pwchange");
496: } elsif ($answer =~ "^non_authorized") {
497: &logthis("$uname in $udom did not get their password correct when ".
498: "attempting to change it on $server.");
499: } elsif ($answer =~ "^auth_mode_error") {
500: &logthis("$uname in $udom attempted to change their password despite ".
501: "not being locally or internally authenticated on $server.");
502: } elsif ($answer =~ "^unknown_user") {
503: &logthis("$uname in $udom attempted to change their password ".
504: "on $server but were unable to because $server is not ".
505: "their home server.");
506: } elsif ($answer =~ "^refused") {
507: &logthis("$server refused to change $uname in $udom password because ".
508: "it was sent an unencrypted request to change the password.");
509: }
510: return $answer;
1.1 albertel 511: }
512:
1.169 harris41 513: # ----------------------- Try to determine user's current authentication scheme
514:
515: sub queryauthenticate {
516: my ($uname,$udom)=@_;
1.456 albertel 517: my $uhome=&homeserver($uname,$udom);
518: if (!$uhome) {
519: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
520: return 'no_host';
521: }
522: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
523: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
524: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 525: }
1.456 albertel 526: return $answer;
1.169 harris41 527: }
528:
1.1 albertel 529: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 530:
1.1 albertel 531: sub authenticate {
532: my ($uname,$upass,$udom)=@_;
1.12 www 533: $upass=escape($upass);
1.199 www 534: $uname=~s/\W//g;
1.471 albertel 535: my $uhome=&homeserver($uname,$udom);
536: if (!$uhome) {
537: &logthis("User $uname at $udom is unknown in authenticate");
538: return 'no_host';
1.1 albertel 539: }
1.471 albertel 540: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
541: if ($answer eq 'authorized') {
542: &logthis("User $uname at $udom authorized by $uhome");
543: return $uhome;
544: }
545: if ($answer eq 'non_authorized') {
546: &logthis("User $uname at $udom rejected by $uhome");
547: return 'no_host';
1.9 www 548: }
1.471 albertel 549: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 550: return 'no_host';
551: }
552:
553: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 554:
1.599 albertel 555: my %homecache;
1.1 albertel 556: sub homeserver {
1.230 stredwic 557: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 558: my $index="$uname:$udom";
1.426 albertel 559:
1.599 albertel 560: if (exists($homecache{$index})) { return $homecache{$index}; }
1.1 albertel 561: my $tryserver;
562: foreach $tryserver (keys %libserv) {
1.230 stredwic 563: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 564: exists($badServerCache{$tryserver}));
1.1 albertel 565: if ($hostdom{$tryserver} eq $udom) {
566: my $answer=reply("home:$udom:$uname",$tryserver);
567: if ($answer eq 'found') {
1.599 albertel 568: return $homecache{$index}=$tryserver;
1.231 stredwic 569: } elsif ($answer eq 'no_host') {
570: $badServerCache{$tryserver}=1;
1.221 matthew 571: }
1.1 albertel 572: }
573: }
574: return 'no_host';
1.70 www 575: }
576:
577: # ------------------------------------- Find the usernames behind a list of IDs
578:
579: sub idget {
580: my ($udom,@ids)=@_;
581: my %returnhash=();
582:
583: my $tryserver;
584: foreach $tryserver (keys %libserv) {
585: if ($hostdom{$tryserver} eq $udom) {
586: my $idlist=join('&',@ids);
587: $idlist=~tr/A-Z/a-z/;
588: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
589: my @answer=();
1.76 www 590: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70 www 591: @answer=split(/\&/,$reply);
592: } ;
593: my $i;
594: for ($i=0;$i<=$#ids;$i++) {
595: if ($answer[$i]) {
596: $returnhash{$ids[$i]}=$answer[$i];
597: }
598: }
599: }
600: }
601: return %returnhash;
602: }
603:
604: # ------------------------------------- Find the IDs behind a list of usernames
605:
606: sub idrget {
607: my ($udom,@unames)=@_;
608: my %returnhash=();
1.191 harris41 609: foreach (@unames) {
1.70 www 610: $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191 harris41 611: }
1.70 www 612: return %returnhash;
613: }
614:
615: # ------------------------------- Store away a list of names and associated IDs
616:
617: sub idput {
618: my ($udom,%ids)=@_;
619: my %servers=();
1.191 harris41 620: foreach (keys %ids) {
1.487 albertel 621: &cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70 www 622: my $uhom=&homeserver($_,$udom);
623: if ($uhom ne 'no_host') {
624: my $id=&escape($ids{$_});
625: $id=~tr/A-Z/a-z/;
626: my $unam=&escape($_);
627: if ($servers{$uhom}) {
628: $servers{$uhom}.='&'.$id.'='.$unam;
629: } else {
630: $servers{$uhom}=$id.'='.$unam;
631: }
632: }
1.191 harris41 633: }
634: foreach (keys %servers) {
1.70 www 635: &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191 harris41 636: }
1.344 www 637: }
638:
639: # --------------------------------------------------- Assign a key to a student
640:
641: sub assign_access_key {
1.364 www 642: #
643: # a valid key looks like uname:udom#comments
644: # comments are being appended
645: #
1.498 www 646: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
647: $kdom=
1.620 albertel 648: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 649: $knum=
1.620 albertel 650: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 651: $cdom=
1.620 albertel 652: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 653: $cnum=
1.620 albertel 654: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
655: $udom=$env{'user.name'} unless (defined($udom));
656: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 657: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 658: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 659: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 660: # assigned to this person
661: # - this should not happen,
1.345 www 662: # unless something went wrong
663: # the first time around
664: # ready to assign
1.364 www 665: $logentry=$1.'; '.$logentry;
1.496 www 666: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 667: $kdom,$knum) eq 'ok') {
1.345 www 668: # key now belongs to user
1.346 www 669: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 670: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
671: &appenv('environment.'.$envkey => $ckey);
672: return 'ok';
673: } else {
674: return
675: 'error: Count not permanently assign key, will need to be re-entered later.';
676: }
677: } else {
678: return 'error: Could not assign key, try again later.';
679: }
1.364 www 680: } elsif (!$existing{$ckey}) {
1.345 www 681: # the key does not exist
682: return 'error: The key does not exist';
683: } else {
684: # the key is somebody else's
685: return 'error: The key is already in use';
686: }
1.344 www 687: }
688:
1.364 www 689: # ------------------------------------------ put an additional comment on a key
690:
691: sub comment_access_key {
692: #
693: # a valid key looks like uname:udom#comments
694: # comments are being appended
695: #
696: my ($ckey,$cdom,$cnum,$logentry)=@_;
697: $cdom=
1.620 albertel 698: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 699: $cnum=
1.620 albertel 700: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 701: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
702: if ($existing{$ckey}) {
703: $existing{$ckey}.='; '.$logentry;
704: # ready to assign
1.367 www 705: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 706: $cdom,$cnum) eq 'ok') {
707: return 'ok';
708: } else {
709: return 'error: Count not store comment.';
710: }
711: } else {
712: # the key does not exist
713: return 'error: The key does not exist';
714: }
715: }
716:
1.344 www 717: # ------------------------------------------------------ Generate a set of keys
718:
719: sub generate_access_keys {
1.364 www 720: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 721: $cdom=
1.620 albertel 722: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 723: $cnum=
1.620 albertel 724: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 725: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 726: unless (($cdom) && ($cnum)) { return 0; }
727: if ($number>10000) { return 0; }
728: sleep(2); # make sure don't get same seed twice
729: srand(time()^($$+($$<<15))); # from "Programming Perl"
730: my $total=0;
731: for (my $i=1;$i<=$number;$i++) {
732: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
733: sprintf("%lx",int(100000*rand)).'-'.
734: sprintf("%lx",int(100000*rand));
735: $newkey=~s/1/g/g; # folks mix up 1 and l
736: $newkey=~s/0/h/g; # and also 0 and O
737: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
738: if ($existing{$newkey}) {
739: $i--;
740: } else {
1.364 www 741: if (&put('accesskeys',
742: { $newkey => '# generated '.localtime().
1.620 albertel 743: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 744: '; '.$logentry },
745: $cdom,$cnum) eq 'ok') {
1.344 www 746: $total++;
747: }
748: }
749: }
1.620 albertel 750: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 751: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
752: return $total;
753: }
754:
755: # ------------------------------------------------------- Validate an accesskey
756:
757: sub validate_access_key {
758: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
759: $cdom=
1.620 albertel 760: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 761: $cnum=
1.620 albertel 762: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
763: $udom=$env{'user.domain'} unless (defined($udom));
764: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 765: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 766: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 767: }
768:
769: # ------------------------------------- Find the section of student in a course
1.298 matthew 770:
771: sub getsection {
772: my ($udom,$unam,$courseid)=@_;
1.599 albertel 773: my $cachetime=1800;
1.298 matthew 774: $courseid=~s/\_/\//g;
775: $courseid=~s/^(\w)/\/$1/;
1.551 albertel 776:
777: my $hashid="$udom:$unam:$courseid";
1.599 albertel 778: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 779: if (defined($cached)) { return $result; }
780:
1.298 matthew 781: my %Pending;
782: my %Expired;
783: #
784: # Each role can either have not started yet (pending), be active,
785: # or have expired.
786: #
787: # If there is an active role, we are done.
788: #
789: # If there is more than one role which has not started yet,
790: # choose the one which will start sooner
791: # If there is one role which has not started yet, return it.
792: #
793: # If there is more than one expired role, choose the one which ended last.
794: # If there is a role which has expired, return it.
795: #
796: foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
797: &homeserver($unam,$udom)))) {
798: my ($key,$value)=split(/\=/,$_);
799: $key=&unescape($key);
1.479 albertel 800: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 801: my $section=$1;
802: if ($key eq $courseid.'_st') { $section=''; }
803: my ($dummy,$end,$start)=split(/\_/,&unescape($value));
804: my $now=time;
1.548 albertel 805: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 806: $Expired{$end}=$section;
807: next;
808: }
1.548 albertel 809: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 810: $Pending{$start}=$section;
811: next;
812: }
1.599 albertel 813: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 814: }
815: #
816: # Presumedly there will be few matching roles from the above
817: # loop and the sorting time will be negligible.
818: if (scalar(keys(%Pending))) {
819: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 820: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 821: }
822: if (scalar(keys(%Expired))) {
823: my @sorted = sort {$a <=> $b} keys(%Expired);
824: my $time = pop(@sorted);
1.599 albertel 825: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 826: }
1.599 albertel 827: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 828: }
1.70 www 829:
1.599 albertel 830: sub save_cache {
1.628 albertel 831: my ($r)=@_;
832: if (! $r->is_initial_req()) { return DECLINED; }
1.599 albertel 833: &purge_remembered();
1.620 albertel 834: undef(%env);
1.628 albertel 835: return OK;
1.599 albertel 836: }
1.452 albertel 837:
1.599 albertel 838: my $to_remember=-1;
839: my %remembered;
840: my %accessed;
841: my $kicks=0;
842: my $hits=0;
843: sub devalidate_cache_new {
844: my ($name,$id,$debug) = @_;
845: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
846: $id=&escape($name.':'.$id);
847: $memcache->delete($id);
848: delete($remembered{$id});
849: delete($accessed{$id});
850: }
851:
852: sub is_cached_new {
853: my ($name,$id,$debug) = @_;
854: $id=&escape($name.':'.$id);
855: if (exists($remembered{$id})) {
856: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
857: $accessed{$id}=[&gettimeofday()];
858: $hits++;
859: return ($remembered{$id},1);
860: }
861: my $value = $memcache->get($id);
862: if (!(defined($value))) {
863: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 864: return (undef,undef);
1.416 albertel 865: }
1.599 albertel 866: if ($value eq '__undef__') {
867: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
868: $value=undef;
869: }
870: &make_room($id,$value,$debug);
871: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
872: return ($value,1);
873: }
874:
875: sub do_cache_new {
876: my ($name,$id,$value,$time,$debug) = @_;
877: $id=&escape($name.':'.$id);
878: my $setvalue=$value;
879: if (!defined($setvalue)) {
880: $setvalue='__undef__';
881: }
1.623 albertel 882: if (!defined($time) ) {
883: $time=600;
884: }
1.599 albertel 885: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600 albertel 886: $memcache->set($id,$setvalue,$time);
887: # need to make a copy of $value
888: #&make_room($id,$value,$debug);
1.599 albertel 889: return $value;
890: }
891:
892: sub make_room {
893: my ($id,$value,$debug)=@_;
894: $remembered{$id}=$value;
895: if ($to_remember<0) { return; }
896: $accessed{$id}=[&gettimeofday()];
897: if (scalar(keys(%remembered)) <= $to_remember) { return; }
898: my $to_kick;
899: my $max_time=0;
900: foreach my $other (keys(%accessed)) {
901: if (&tv_interval($accessed{$other}) > $max_time) {
902: $to_kick=$other;
903: $max_time=&tv_interval($accessed{$other});
904: }
905: }
906: delete($remembered{$to_kick});
907: delete($accessed{$to_kick});
908: $kicks++;
909: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 910: return;
911: }
912:
1.599 albertel 913: sub purge_remembered {
1.604 albertel 914: #&logthis("Tossing ".scalar(keys(%remembered)));
915: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 916: undef(%remembered);
917: undef(%accessed);
1.428 albertel 918: }
1.70 www 919: # ------------------------------------- Read an entry from a user's environment
920:
921: sub userenvironment {
922: my ($udom,$unam,@what)=@_;
923: my %returnhash=();
924: my @answer=split(/\&/,
925: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
926: &homeserver($unam,$udom)));
927: my $i;
928: for ($i=0;$i<=$#what;$i++) {
929: $returnhash{$what[$i]}=&unescape($answer[$i]);
930: }
931: return %returnhash;
1.1 albertel 932: }
933:
1.617 albertel 934: # ---------------------------------------------------------- Get a studentphoto
935: sub studentphoto {
936: my ($udom,$unam,$ext) = @_;
937: my $home=&Apache::lonnet::homeserver($unam,$udom);
938: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext",$home);
939: my $url="/uploaded/$udom/$unam/internal/studentphoto.".$ext;
940: if ($ret ne 'ok') {
941: return '/adm/lonKaputt/lonlogo_broken.gif';
942: }
943: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
944: return $tokenurl;
945: }
946:
1.263 www 947: # -------------------------------------------------------------------- New chat
948:
949: sub chatsend {
950: my ($newentry,$anon)=@_;
1.620 albertel 951: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
952: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
953: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 954: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 955: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.263 www 956: &escape($newentry)),$chome);
1.292 www 957: }
958:
959: # ------------------------------------------ Find current version of a resource
960:
961: sub getversion {
962: my $fname=&clutter(shift);
963: unless ($fname=~/^\/res\//) { return -1; }
964: return ¤tversion(&filelocation('',$fname));
965: }
966:
967: sub currentversion {
968: my $fname=shift;
1.599 albertel 969: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 970: if (defined($cached)) { return $result; }
1.292 www 971: my $author=$fname;
972: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
973: my ($udom,$uname)=split(/\//,$author);
974: my $home=homeserver($uname,$udom);
975: if ($home eq 'no_host') {
976: return -1;
977: }
978: my $answer=reply("currentversion:$fname",$home);
979: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
980: return -1;
981: }
1.599 albertel 982: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 983: }
984:
1.1 albertel 985: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 986:
1.1 albertel 987: sub subscribe {
988: my $fname=shift;
1.312 www 989: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 990: $fname=~s/[\n\r]//g;
1.1 albertel 991: my $author=$fname;
992: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
993: my ($udom,$uname)=split(/\//,$author);
994: my $home=homeserver($uname,$udom);
1.335 albertel 995: if ($home eq 'no_host') {
996: return 'not_found';
1.1 albertel 997: }
998: my $answer=reply("sub:$fname",$home);
1.64 www 999: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1000: $answer.=' by '.$home;
1001: }
1.1 albertel 1002: return $answer;
1003: }
1004:
1.8 www 1005: # -------------------------------------------------------------- Replicate file
1006:
1007: sub repcopy {
1008: my $filename=shift;
1.23 www 1009: $filename=~s/\/+/\//g;
1.607 raeburn 1010: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1011: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1012: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1013: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1014: return &repcopy_userfile($filename);
1015: }
1.532 albertel 1016: $filename=~s/[\n\r]//g;
1.8 www 1017: my $transname="$filename.in.transfer";
1.607 raeburn 1018: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1019: my $remoteurl=subscribe($filename);
1.64 www 1020: if ($remoteurl =~ /^con_lost by/) {
1021: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1022: return 'unavailable';
1.8 www 1023: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1024: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1025: return 'not_found';
1.64 www 1026: } elsif ($remoteurl =~ /^rejected by/) {
1027: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1028: return 'forbidden';
1.20 www 1029: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1030: return 'ok';
1.8 www 1031: } else {
1.290 www 1032: my $author=$filename;
1033: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1034: my ($udom,$uname)=split(/\//,$author);
1035: my $home=homeserver($uname,$udom);
1036: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1037: my @parts=split(/\//,$filename);
1038: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1039: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1040: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1041: return 'bad_request';
1.8 www 1042: }
1043: my $count;
1044: for ($count=5;$count<$#parts;$count++) {
1045: $path.="/$parts[$count]";
1046: if ((-e $path)!=1) {
1047: mkdir($path,0777);
1048: }
1049: }
1050: my $ua=new LWP::UserAgent;
1051: my $request=new HTTP::Request('GET',"$remoteurl");
1052: my $response=$ua->request($request,$transname);
1053: if ($response->is_error()) {
1054: unlink($transname);
1055: my $message=$response->status_line;
1.12 www 1056: &logthis("<font color=blue>WARNING:"
1057: ." LWP get: $message: $filename</font>");
1.607 raeburn 1058: return 'unavailable';
1.8 www 1059: } else {
1.16 www 1060: if ($remoteurl!~/\.meta$/) {
1061: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1062: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1063: if ($mresponse->is_error()) {
1064: unlink($filename.'.meta');
1065: &logthis(
1066: "<font color=yellow>INFO: No metadata: $filename</font>");
1067: }
1068: }
1.8 www 1069: rename($transname,$filename);
1.607 raeburn 1070: return 'ok';
1.8 www 1071: }
1.290 www 1072: }
1.8 www 1073: }
1.330 www 1074: }
1075:
1076: # ------------------------------------------------ Get server side include body
1077: sub ssi_body {
1.381 albertel 1078: my ($filelink,%form)=@_;
1.606 matthew 1079: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1080: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1081: }
1.330 www 1082: my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381 albertel 1083: &ssi($filelink,%form));
1.565 albertel 1084: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1085: $output=~s/^.*?\<body[^\>]*\>//si;
1086: $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330 www 1087: return $output;
1.8 www 1088: }
1089:
1.15 www 1090: # --------------------------------------------------------- Server Side Include
1091:
1092: sub ssi {
1093:
1.23 www 1094: my ($fn,%form)=@_;
1.15 www 1095:
1096: my $ua=new LWP::UserAgent;
1.23 www 1097:
1098: my $request;
1099:
1100: if (%form) {
1101: $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201 albertel 1102: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23 www 1103: } else {
1104: $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
1105: }
1106:
1.15 www 1107: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1108: my $response=$ua->request($request);
1109:
1.324 www 1110: return $response->content;
1111: }
1112:
1113: sub externalssi {
1114: my ($url)=@_;
1115: my $ua=new LWP::UserAgent;
1116: my $request=new HTTP::Request('GET',$url);
1117: my $response=$ua->request($request);
1.15 www 1118: return $response->content;
1119: }
1.254 www 1120:
1.492 albertel 1121: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1122:
1123: sub allowuploaded {
1124: my ($srcurl,$url)=@_;
1125: $url=&clutter(&declutter($url));
1126: my $dir=$url;
1127: $dir=~s/\/[^\/]+$//;
1128: my %httpref=();
1129: my $httpurl=&hreflocation('',$url);
1130: $httpref{'httpref.'.$httpurl}=$srcurl;
1131: &Apache::lonnet::appenv(%httpref);
1.254 www 1132: }
1.477 raeburn 1133:
1.478 albertel 1134: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1135: # input: action, courseID, current domain, home server for course, intended
1.637 ! raeburn 1136: # path to file, source of file, instruction to parse file for objects,
! 1137: # ref to hash for embedded objects,
! 1138: # ref to hash for codebase of java objects.
! 1139: #
1.485 raeburn 1140: # output: url to file (if action was uploaddoc),
1141: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 1142: #
1.478 albertel 1143: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1144: # course.
1.477 raeburn 1145: #
1.478 albertel 1146: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1147: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1148: # course's home server.
1.477 raeburn 1149: #
1.478 albertel 1150: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1151: # be copied from $source (current location) to
1152: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1153: # and will then be copied to
1154: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1155: # course's home server.
1.485 raeburn 1156: #
1.481 raeburn 1157: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 1158: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 1159: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1160: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1161: # in course's home server.
1.637 ! raeburn 1162: #
1.477 raeburn 1163:
1164: sub process_coursefile {
1.637 ! raeburn 1165: my ($action,$docuname,$docudom,$docuhome,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 1166: my $fetchresult;
1167: if ($action eq 'propagate') {
1168: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file
1169: ,$docuhome);
1.481 raeburn 1170: } else {
1.477 raeburn 1171: my $fetchresult = '';
1172: my $fpath = '';
1173: my $fname = $file;
1.478 albertel 1174: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 1175: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 ! raeburn 1176: my $filepath = &build_filepath($fpath);
1.481 raeburn 1177: if ($action eq 'copy') {
1178: if ($source eq '') {
1179: $fetchresult = 'no source file';
1180: return $fetchresult;
1181: } else {
1182: my $destination = $filepath.'/'.$fname;
1183: rename($source,$destination);
1184: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1185: $docuhome);
1186: }
1187: } elsif ($action eq 'uploaddoc') {
1188: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 1189: print $fh $env{'form.'.$source};
1.481 raeburn 1190: close($fh);
1.637 ! raeburn 1191: if ($parser eq 'parse') {
! 1192: my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
! 1193: unless ($parse_result eq 'ok') {
! 1194: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
! 1195: }
! 1196: }
1.477 raeburn 1197: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1198: $docuhome);
1.481 raeburn 1199: if ($fetchresult eq 'ok') {
1200: return '/uploaded/'.$fpath.'/'.$fname;
1201: } else {
1202: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1203: ' to host '.$docuhome.': '.$fetchresult);
1204: return '/adm/notfound.html';
1205: }
1.477 raeburn 1206: }
1207: }
1.485 raeburn 1208: unless ( $fetchresult eq 'ok') {
1.477 raeburn 1209: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1210: ' to host '.$docuhome.': '.$fetchresult);
1211: }
1212: return $fetchresult;
1213: }
1214:
1.637 ! raeburn 1215: sub build_filepath {
! 1216: my ($fpath) = @_;
! 1217: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
! 1218: unless ($fpath eq '') {
! 1219: my @parts=split('/',$fpath);
! 1220: foreach my $part (@parts) {
! 1221: $filepath.= '/'.$part;
! 1222: if ((-e $filepath)!=1) {
! 1223: mkdir($filepath,0777);
! 1224: }
! 1225: }
! 1226: }
! 1227: return $filepath;
! 1228: }
! 1229:
! 1230: sub store_edited_file {
! 1231: my ($primary_url,$content,$docudom,$docuname,$docuhome,$fetchresult) = @_;
! 1232: my $file = $primary_url;
! 1233: $file =~ s#^/uploaded/$docudom/$docuname/##;
! 1234: my $fpath = '';
! 1235: my $fname = $file;
! 1236: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
! 1237: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
! 1238: my $filepath = &build_filepath($fpath);
! 1239: open(my $fh,'>'.$filepath.'/'.$fname);
! 1240: print $fh $content;
! 1241: close($fh);
! 1242: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
! 1243: $docuhome);
! 1244: if ($$fetchresult eq 'ok') {
! 1245: return '/uploaded/'.$fpath.'/'.$fname;
! 1246: } else {
! 1247: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file. ' to host '.$docuhome.': '.$$fetchresult);
! 1248: return '/adm/notfound.html';
! 1249: }
! 1250: }
! 1251:
1.531 albertel 1252: sub clean_filename {
1253: my ($fname)=@_;
1.315 www 1254: # Replace Windows backslashes by forward slashes
1.257 www 1255: $fname=~s/\\/\//g;
1.315 www 1256: # Get rid of everything but the actual filename
1.257 www 1257: $fname=~s/^.*\/([^\/]+)$/$1/;
1.315 www 1258: # Replace spaces by underscores
1259: $fname=~s/\s+/\_/g;
1260: # Replace all other weird characters by nothing
1.317 www 1261: $fname=~s/[^\w\.\-]//g;
1.540 albertel 1262: # Replace all .\d. sequences with _\d. so they no longer look like version
1263: # numbers
1264: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 1265: return $fname;
1266: }
1267:
1.608 albertel 1268: # --------------- Take an uploaded file and put it into the userfiles directory
1269: # input: name of form element, coursedoc=1 means this is for the course
1270: # output: url of file in userspace
1271:
1272:
1.531 albertel 1273: sub userfileupload {
1.637 ! raeburn 1274: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase)=@_;
1.531 albertel 1275: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 1276: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 1277: $fname=&clean_filename($fname);
1.315 www 1278: # See if there is anything left
1.257 www 1279: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 1280: chop($env{'form.'.$formname});
1.523 raeburn 1281: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
1282: my $now = time;
1283: my $filepath = 'tmp/helprequests/'.$now;
1284: my @parts=split(/\//,$filepath);
1285: my $fullpath = $perlvar{'lonDaemons'};
1286: for (my $i=0;$i<@parts;$i++) {
1287: $fullpath .= '/'.$parts[$i];
1288: if ((-e $fullpath)!=1) {
1289: mkdir($fullpath,0777);
1290: }
1291: }
1292: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 1293: print $fh $env{'form.'.$formname};
1.523 raeburn 1294: close($fh);
1295: return $fullpath.'/'.$fname;
1296: }
1.258 www 1297: # Create the directory if not present
1.259 www 1298: my $docuname='';
1299: my $docudom='';
1300: my $docuhome='';
1.493 albertel 1301: $fname="$subdir/$fname";
1.259 www 1302: if ($coursedoc) {
1.620 albertel 1303: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1304: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1305: $docuhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1306: if ($env{'form.folder'} =~ m/^default/) {
1.637 ! raeburn 1307: return &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname,$parser,$allfiles,$codebase);
1.481 raeburn 1308: } else {
1.620 albertel 1309: $fname=$env{'form.folder'}.'/'.$fname;
1.637 ! raeburn 1310: return &process_coursefile('uploaddoc',$docuname,$docudom,$docuhome,$fname,$formname,$parser,$allfiles,$codebase);
1.481 raeburn 1311: }
1.259 www 1312: } else {
1.620 albertel 1313: $docuname=$env{'user.name'};
1314: $docudom=$env{'user.domain'};
1315: $docuhome=$env{'user.home'};
1.637 ! raeburn 1316: return &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname,$parser,$allfiles,$codebase);
1.259 www 1317: }
1.271 www 1318: }
1319:
1320: sub finishuserfileupload {
1.637 ! raeburn 1321: my ($docuname,$docudom,$docuhome,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477 raeburn 1322: my $path=$docudom.'/'.$docuname.'/';
1.258 www 1323: my $filepath=$perlvar{'lonDocRoot'};
1.494 albertel 1324: my ($fnamepath,$file);
1325: $file=$fname;
1326: if ($fname=~m|/|) {
1327: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
1328: $path.=$fnamepath.'/';
1329: }
1.259 www 1330: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 1331: my $count;
1332: for ($count=4;$count<=$#parts;$count++) {
1333: $filepath.="/$parts[$count]";
1334: if ((-e $filepath)!=1) {
1335: mkdir($filepath,0777);
1336: }
1337: }
1338: # Save the file
1339: {
1.570 albertel 1340: open(FH,'>'.$filepath.'/'.$file);
1.620 albertel 1341: print FH $env{'form.'.$formname};
1.570 albertel 1342: close(FH);
1.258 www 1343: }
1.637 ! raeburn 1344: if ($parser eq 'parse') {
! 1345: my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,$codebase);
! 1346: unless ($parse_result eq 'ok') {
! 1347: &logthis('Failed to parse '.$filepath.$file.' for embedded media: '.$parse_result);
! 1348: }
! 1349: }
1.259 www 1350: # Notify homeserver to grep it
1351: #
1.494 albertel 1352: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 1353: if ($fetchresult eq 'ok') {
1.259 www 1354: #
1.258 www 1355: # Return the URL to it
1.494 albertel 1356: return '/uploaded/'.$path.$file;
1.263 www 1357: } else {
1.494 albertel 1358: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
1359: ': '.$fetchresult);
1.263 www 1360: return '/adm/notfound.html';
1361: }
1.493 albertel 1362: }
1363:
1.637 ! raeburn 1364: sub extract_embedded_items {
! 1365: my ($filepath,$file,$allfiles,$codebase) = @_;
! 1366: my @state = ();
! 1367: my %javafiles = (
! 1368: codebase => '',
! 1369: code => '',
! 1370: archive => ''
! 1371: );
! 1372: my %mediafiles = (
! 1373: src => '',
! 1374: movie => '',
! 1375: );
! 1376: my $p = HTML::Parser->new
! 1377: (
! 1378: xml_mode => 1,
! 1379: start_h =>
! 1380: [sub {
! 1381: my ($tagname, $attr) = @_;
! 1382: push (@state, $tagname);
! 1383: if (lc($tagname) eq 'img') {
! 1384: if (exists($$allfiles{$attr->{'src'}})) {
! 1385: unless (grep/^src$/,@{$$allfiles{$attr->{'src'}}}) {
! 1386: push (@{$$allfiles{$attr->{'src'}}},&escape('src'));
! 1387: }
! 1388: } else {
! 1389: @{$$allfiles{$attr->{'src'}}} = (&escape('src'));
! 1390: }
! 1391: }
! 1392: if (lc($tagname) eq 'object') {
! 1393: foreach my $item (keys (%javafiles)) {
! 1394: $javafiles{$item} = '';
! 1395: }
! 1396: }
! 1397: if (lc($state[-2]) eq 'object') {
! 1398: if (lc($tagname) eq 'param') {
! 1399: my $name = lc($attr->{'name'});
! 1400: foreach my $item (keys (%mediafiles)) {
! 1401: if ($name eq $item) {
! 1402: if (exists($$allfiles{$attr->{'value'}})) {
! 1403: unless(grep/^value$/,@{$$allfiles{$attr->{'value'}}}) {
! 1404: push(@{$$allfiles{$attr->{'value'}}},&escape('value'));
! 1405: }
! 1406: } else {
! 1407: @{$$allfiles{$attr->{'value'}}} = (&escape('value'));
! 1408: }
! 1409: last;
! 1410: }
! 1411: }
! 1412: foreach my $item (keys (%javafiles)) {
! 1413: if ($name eq $item) {
! 1414: $javafiles{$item} = $attr->{'value'};
! 1415: last;
! 1416: }
! 1417: }
! 1418: }
! 1419: }
! 1420: if (lc($tagname) eq 'embed') {
! 1421: unless (lc($state[-2]) eq 'object') {
! 1422: foreach my $item (keys (%javafiles)) {
! 1423: $javafiles{$item} = '';
! 1424: }
! 1425: }
! 1426: foreach my $item (keys (%javafiles)) {
! 1427: if ($attr->{$item}) {
! 1428: $javafiles{$item} = $attr->{$item};
! 1429: last;
! 1430: }
! 1431: }
! 1432: foreach my $item (keys (%mediafiles)) {
! 1433: if ($attr->{$item}) {
! 1434: if (exists($$allfiles{$attr->{$item}})) {
! 1435: unless (grep/^$item$/,@{$$allfiles{$item}}) {
! 1436: push(@{$$allfiles{$attr->{$item}}},&escape($item));
! 1437: }
! 1438: } else {
! 1439: @{$$allfiles{$attr->{$item}}} = (&escape($item));
! 1440: }
! 1441: last;
! 1442: }
! 1443: }
! 1444: }
! 1445: }, "tagname, attr"],
! 1446: text_h =>
! 1447: [sub {
! 1448: my ($text) = @_;
! 1449: }, "dtext"],
! 1450: end_h =>
! 1451: [sub {
! 1452: my ($tagname) = @_;
! 1453: unless ($javafiles{'codebase'} eq '') {
! 1454: $javafiles{'codebase'} .= '/';
! 1455: }
! 1456: if (lc($tagname) eq 'object') {
! 1457: &extract_java_items(\%javafiles,$allfiles,$codebase);
! 1458: }
! 1459: if (lc($tagname) eq 'embed') {
! 1460: unless (lc($state[-2]) eq 'object') {
! 1461: &extract_java_items(\%javafiles,$allfiles,$codebase);
! 1462: }
! 1463: }
! 1464: pop @state;
! 1465: }, "tagname"],
! 1466: );
! 1467: $p->parse_file($filepath.'/'.$file);
! 1468: $p->eof;
! 1469: return 'ok';
! 1470: }
! 1471:
! 1472: sub extract_java_items {
! 1473: my ($javafiles,$allfiles,$codebase) = @_;
! 1474: foreach my $item (keys (%{$javafiles})) {
! 1475: unless ($item eq 'codebase') {
! 1476: if ($$javafiles{$item} ne '') {
! 1477: if (exists($$allfiles{$$javafiles{'codebase'}.$$javafiles{$item}})) {
! 1478: unless (grep/^$item$/,@{$$allfiles{$$javafiles{'codebase'}.$$javafiles{$item}}}) {
! 1479: push(@{$$allfiles{$$javafiles{'codebase'}.$$javafiles{$item}}},&escape($item));
! 1480: }
! 1481: } else {
! 1482: @{$$allfiles{$$javafiles{'codebase'}.$$javafiles{$item}}} = (&escape($item));
! 1483: $$codebase{$$javafiles{'codebase'}.$$javafiles{$item}} = $$javafiles{'codebase'};
! 1484:
! 1485: }
! 1486: }
! 1487: }
! 1488: }
! 1489: }
! 1490:
1.493 albertel 1491: sub removeuploadedurl {
1492: my ($url)=@_;
1493: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 1494: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 1495: }
1496:
1497: sub removeuserfile {
1498: my ($docuname,$docudom,$fname)=@_;
1499: my $home=&homeserver($docuname,$docudom);
1500: return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257 www 1501: }
1.15 www 1502:
1.530 albertel 1503: sub mkdiruserfile {
1504: my ($docuname,$docudom,$dir)=@_;
1505: my $home=&homeserver($docuname,$docudom);
1506: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
1507: }
1508:
1.531 albertel 1509: sub renameuserfile {
1510: my ($docuname,$docudom,$old,$new)=@_;
1511: my $home=&homeserver($docuname,$docudom);
1512: return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
1513: &escape("$new"),$home);
1514: }
1515:
1.14 www 1516: # ------------------------------------------------------------------------- Log
1517:
1518: sub log {
1519: my ($dom,$nam,$hom,$what)=@_;
1.47 www 1520: return critical("log:$dom:$nam:$what",$hom);
1.157 www 1521: }
1522:
1523: # ------------------------------------------------------------------ Course Log
1.352 www 1524: #
1525: # This routine flushes several buffers of non-mission-critical nature
1526: #
1.157 www 1527:
1528: sub flushcourselogs {
1.352 www 1529: &logthis('Flushing log buffers');
1530: #
1531: # course logs
1532: # This is a log of all transactions in a course, which can be used
1533: # for data mining purposes
1534: #
1535: # It also collects the courseid database, which lists last transaction
1536: # times and course titles for all courseids
1537: #
1538: my %courseidbuffer=();
1.191 harris41 1539: foreach (keys %courselogs) {
1.157 www 1540: my $crsid=$_;
1.352 www 1541: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 1542: &escape($courselogs{$crsid}),
1543: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 1544: delete $courselogs{$crsid};
1545: } else {
1546: &logthis('Failed to flush log buffer for '.$crsid);
1547: if (length($courselogs{$crsid})>40000) {
1548: &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
1549: " exceeded maximum size, deleting.</font>");
1550: delete $courselogs{$crsid};
1551: }
1.352 www 1552: }
1553: if ($courseidbuffer{$coursehombuf{$crsid}}) {
1554: $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516 raeburn 1555: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.571 raeburn 1556: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
1.352 www 1557: } else {
1558: $courseidbuffer{$coursehombuf{$crsid}}=
1.516 raeburn 1559: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.571 raeburn 1560: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
1561: }
1.191 harris41 1562: }
1.352 www 1563: #
1564: # Write course id database (reverse lookup) to homeserver of courses
1565: # Is used in pickcourse
1566: #
1567: foreach (keys %courseidbuffer) {
1.353 www 1568: &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352 www 1569: }
1570: #
1571: # File accesses
1572: # Writes to the dynamic metadata of resources to get hit counts, etc.
1573: #
1.449 matthew 1574: foreach my $entry (keys(%accesshash)) {
1.458 matthew 1575: if ($entry =~ /___count$/) {
1576: my ($dom,$name);
1577: ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
1578: if (! defined($dom) || $dom eq '' ||
1579: ! defined($name) || $name eq '') {
1.620 albertel 1580: my $cid = $env{'request.course.id'};
1581: $dom = $env{'request.'.$cid.'.domain'};
1582: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 1583: }
1.450 matthew 1584: my $value = $accesshash{$entry};
1585: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
1586: my %temphash=($url => $value);
1.449 matthew 1587: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
1588: if ($result eq 'ok') {
1589: delete $accesshash{$entry};
1590: } elsif ($result eq 'unknown_cmd') {
1591: # Target server has old code running on it.
1.450 matthew 1592: my %temphash=($entry => $value);
1.449 matthew 1593: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1594: delete $accesshash{$entry};
1595: }
1596: }
1597: } else {
1.458 matthew 1598: my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450 matthew 1599: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 1600: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1601: delete $accesshash{$entry};
1602: }
1.185 www 1603: }
1.191 harris41 1604: }
1.352 www 1605: #
1606: # Roles
1607: # Reverse lookup of user roles for course faculty/staff and co-authorship
1608: #
1.349 www 1609: foreach (keys %userrolehash) {
1610: my $entry=$_;
1.351 www 1611: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 1612: split(/\:/,$entry);
1613: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 1614: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 1615: $rudom,$runame) eq 'ok') {
1616: delete $userrolehash{$entry};
1617: }
1618: }
1.186 www 1619: $dumpcount++;
1.157 www 1620: }
1621:
1622: sub courselog {
1623: my $what=shift;
1.158 www 1624: $what=time.':'.$what;
1.620 albertel 1625: unless ($env{'request.course.id'}) { return ''; }
1626: $coursedombuf{$env{'request.course.id'}}=
1627: $env{'course.'.$env{'request.course.id'}.'.domain'};
1628: $coursenumbuf{$env{'request.course.id'}}=
1629: $env{'course.'.$env{'request.course.id'}.'.num'};
1630: $coursehombuf{$env{'request.course.id'}}=
1631: $env{'course.'.$env{'request.course.id'}.'.home'};
1632: $coursedescrbuf{$env{'request.course.id'}}=
1633: $env{'course.'.$env{'request.course.id'}.'.description'};
1634: $courseinstcodebuf{$env{'request.course.id'}}=
1635: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
1636: $courseownerbuf{$env{'request.course.id'}}=
1637: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1638: if (defined $courselogs{$env{'request.course.id'}}) {
1639: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 1640: } else {
1.620 albertel 1641: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 1642: }
1.620 albertel 1643: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 1644: &flushcourselogs();
1645: }
1.158 www 1646: }
1647:
1648: sub courseacclog {
1649: my $fnsymb=shift;
1.620 albertel 1650: unless ($env{'request.course.id'}) { return ''; }
1651: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.408 www 1652: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|page)$/) {
1.187 www 1653: $what.=':POST';
1.583 matthew 1654: # FIXME: Probably ought to escape things....
1.620 albertel 1655: foreach (keys %env) {
1.158 www 1656: if ($_=~/^form\.(.*)/) {
1.620 albertel 1657: $what.=':'.$1.'='.$env{$_};
1.158 www 1658: }
1.191 harris41 1659: }
1.583 matthew 1660: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
1661: # FIXME: We should not be depending on a form parameter that someone
1662: # editing lonsearchcat.pm might change in the future.
1.620 albertel 1663: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 1664: $what.= ':POST';
1665: # FIXME: Probably ought to escape things....
1666: foreach my $element ('courseexp','crsfulltext','crsrelated',
1667: 'crsdiscuss') {
1.620 albertel 1668: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 1669: }
1670: }
1.158 www 1671: }
1672: &courselog($what);
1.149 www 1673: }
1674:
1.185 www 1675: sub countacc {
1676: my $url=&declutter(shift);
1.458 matthew 1677: return if (! defined($url) || $url eq '');
1.620 albertel 1678: unless ($env{'request.course.id'}) { return ''; }
1679: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 1680: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 1681: $accesshash{$key}++;
1.185 www 1682: }
1.349 www 1683:
1.361 www 1684: sub linklog {
1685: my ($from,$to)=@_;
1686: $from=&declutter($from);
1687: $to=&declutter($to);
1688: $accesshash{$from.'___'.$to.'___comefrom'}=1;
1689: $accesshash{$to.'___'.$from.'___goto'}=1;
1690: }
1691:
1.349 www 1692: sub userrolelog {
1693: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1694: if (($trole=~/^ca/) || ($trole=~/^in/) ||
1695: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.469 www 1696: ($trole=~/^cr/) || ($trole=~/^ta/)) {
1.350 www 1697: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
1698: $userrolehash
1699: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 1700: =$tend.':'.$tstart;
1701: }
1.351 www 1702: }
1703:
1704: sub get_course_adv_roles {
1705: my $cid=shift;
1.620 albertel 1706: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 1707: my %coursehash=&coursedescription($cid);
1.470 www 1708: my %nothide=();
1709: foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1710: $nothide{join(':',split(/[\@\:]/,$_))}=1;
1711: }
1.351 www 1712: my %returnhash=();
1713: my %dumphash=
1714: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
1715: my $now=time;
1716: foreach (keys %dumphash) {
1717: my ($tend,$tstart)=split(/\:/,$dumphash{$_});
1718: if (($tstart) && ($tstart<0)) { next; }
1719: if (($tend) && ($tend<$now)) { next; }
1720: if (($tstart) && ($now<$tstart)) { next; }
1721: my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576 albertel 1722: if ($username eq '' || $domain eq '') { next; }
1.470 www 1723: if ((&privileged($username,$domain)) &&
1724: (!$nothide{$username.':'.$domain})) { next; }
1.351 www 1725: my $key=&plaintext($role);
1726: if ($section) { $key.=' (Sec/Grp '.$section.')'; }
1727: if ($returnhash{$key}) {
1728: $returnhash{$key}.=','.$username.':'.$domain;
1729: } else {
1730: $returnhash{$key}=$username.':'.$domain;
1731: }
1.400 www 1732: }
1733: return %returnhash;
1734: }
1735:
1736: sub get_my_roles {
1737: my ($uname,$udom)=@_;
1.620 albertel 1738: unless (defined($uname)) { $uname=$env{'user.name'}; }
1739: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400 www 1740: my %dumphash=
1741: &dump('nohist_userroles',$udom,$uname);
1742: my %returnhash=();
1743: my $now=time;
1744: foreach (keys %dumphash) {
1745: my ($tend,$tstart)=split(/\:/,$dumphash{$_});
1746: if (($tstart) && ($tstart<0)) { next; }
1747: if (($tend) && ($tend<$now)) { next; }
1748: if (($tstart) && ($now<$tstart)) { next; }
1749: my ($role,$username,$domain,$section)=split(/\:/,$_);
1750: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373 www 1751: }
1752: return %returnhash;
1.399 www 1753: }
1754:
1755: # ----------------------------------------------------- Frontpage Announcements
1756: #
1757: #
1758:
1759: sub postannounce {
1760: my ($server,$text)=@_;
1761: unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
1762: unless ($text=~/\w/) { $text=''; }
1763: return &reply('setannounce:'.&escape($text),$server);
1764: }
1765:
1766: sub getannounce {
1.448 albertel 1767:
1768: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 1769: my $announcement='';
1770: while (<$fh>) { $announcement .=$_; }
1.448 albertel 1771: close($fh);
1.399 www 1772: if ($announcement=~/\w/) {
1773: return
1774: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 1775: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 1776: } else {
1777: return '';
1778: }
1779: } else {
1780: return '';
1781: }
1.351 www 1782: }
1.353 www 1783:
1784: # ---------------------------------------------------------- Course ID routines
1785: # Deal with domain's nohist_courseid.db files
1786: #
1787:
1788: sub courseidput {
1789: my ($domain,$what,$coursehome)=@_;
1790: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
1791: }
1792:
1793: sub courseiddump {
1.622 raeburn 1794: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref)=@_;
1.353 www 1795: my %returnhash=();
1.355 www 1796: unless ($domfilter) { $domfilter=''; }
1.353 www 1797: foreach my $tryserver (keys %libserv) {
1.511 raeburn 1798: if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506 raeburn 1799: if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1800: foreach (
1801: split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571 raeburn 1802: $sincefilter.':'.&escape($descfilter).':'.
1.622 raeburn 1803: &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter),
1.354 www 1804: $tryserver))) {
1.506 raeburn 1805: my ($key,$value)=split(/\=/,$_);
1806: if (($key) && ($value)) {
1.516 raeburn 1807: $returnhash{&unescape($key)}=$value;
1.506 raeburn 1808: }
1.353 www 1809: }
1810: }
1811: }
1812: }
1813: return %returnhash;
1814: }
1815:
1816: #
1.149 www 1817: # ----------------------------------------------------------- Check out an item
1818:
1.504 albertel 1819: sub get_first_access {
1820: my ($type,$argsymb)=@_;
1821: my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
1822: if ($argsymb) { $symb=$argsymb; }
1823: my ($map,$id,$res)=&decode_symb($symb);
1.588 albertel 1824: if ($type eq 'map') {
1825: $res=&symbread($map);
1826: } else {
1827: $res=$symb;
1828: }
1829: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
1830: return $times{"$courseid\0$res"};
1.504 albertel 1831: }
1832:
1833: sub set_first_access {
1834: my ($type)=@_;
1835: my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
1836: my ($map,$id,$res)=&decode_symb($symb);
1.588 albertel 1837: if ($type eq 'map') {
1838: $res=&symbread($map);
1839: } else {
1840: $res=$symb;
1841: }
1842: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 1843: if (!$firstaccess) {
1.588 albertel 1844: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 1845: }
1846: return 'already_set';
1.504 albertel 1847: }
1848:
1.149 www 1849: sub checkout {
1850: my ($symb,$tuname,$tudom,$tcrsid)=@_;
1851: my $now=time;
1852: my $lonhost=$perlvar{'lonHostID'};
1853: my $infostr=&escape(
1.234 www 1854: 'CHECKOUTTOKEN&'.
1.149 www 1855: $tuname.'&'.
1856: $tudom.'&'.
1857: $tcrsid.'&'.
1858: $symb.'&'.
1859: $now.'&'.$ENV{'REMOTE_ADDR'});
1860: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 1861: if ($token=~/^error\:/) {
1862: &logthis("<font color=blue>WARNING: ".
1863: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
1864: "</font>");
1865: return '';
1866: }
1867:
1.149 www 1868: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
1869: $token=~tr/a-z/A-Z/;
1870:
1.153 www 1871: my %infohash=('resource.0.outtoken' => $token,
1872: 'resource.0.checkouttime' => $now,
1873: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 1874:
1875: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
1876: return '';
1.151 www 1877: } else {
1878: &logthis("<font color=blue>WARNING: ".
1879: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
1880: "</font>");
1.149 www 1881: }
1882:
1883: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
1884: &escape('Checkout '.$infostr.' - '.
1885: $token)) ne 'ok') {
1886: return '';
1.151 www 1887: } else {
1888: &logthis("<font color=blue>WARNING: ".
1889: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
1890: "</font>");
1.149 www 1891: }
1.151 www 1892: return $token;
1.149 www 1893: }
1894:
1895: # ------------------------------------------------------------ Check in an item
1896:
1897: sub checkin {
1898: my $token=shift;
1.150 www 1899: my $now=time;
1900: my ($ta,$tb,$lonhost)=split(/\*/,$token);
1901: $lonhost=~tr/A-Z/a-z/;
1.595 albertel 1902: my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150 www 1903: $dtoken=~s/\W/\_/g;
1.234 www 1904: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 1905: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
1906:
1.154 www 1907: unless (($tuname) && ($tudom)) {
1908: &logthis('Check in '.$token.' ('.$dtoken.') failed');
1909: return '';
1910: }
1911:
1912: unless (&allowed('mgr',$tcrsid)) {
1913: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 1914: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 1915: return '';
1916: }
1917:
1.153 www 1918: my %infohash=('resource.0.intoken' => $token,
1919: 'resource.0.checkintime' => $now,
1920: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 1921:
1922: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
1923: return '';
1924: }
1925:
1926: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
1927: &escape('Checkin - '.$token)) ne 'ok') {
1928: return '';
1929: }
1930:
1931: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 1932: }
1933:
1934: # --------------------------------------------- Set Expire Date for Spreadsheet
1935:
1936: sub expirespread {
1937: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 1938: my $cid=$env{'request.course.id'};
1.110 www 1939: if ($cid) {
1940: my $now=time;
1941: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 1942: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
1943: $env{'course.'.$cid.'.num'}.
1.110 www 1944: ':nohist_expirationdates:'.
1945: &escape($key).'='.$now,
1.620 albertel 1946: $env{'course.'.$cid.'.home'})
1.110 www 1947: }
1948: return 'ok';
1.14 www 1949: }
1950:
1.109 www 1951: # ----------------------------------------------------- Devalidate Spreadsheets
1952:
1953: sub devalidate {
1.325 www 1954: my ($symb,$uname,$udom)=@_;
1.620 albertel 1955: my $cid=$env{'request.course.id'};
1.109 www 1956: if ($cid) {
1.391 matthew 1957: # delete the stored spreadsheets for
1958: # - the student level sheet of this user in course's homespace
1959: # - the assessment level sheet for this resource
1960: # for this user in user's homespace
1.553 albertel 1961: # - current conditional state info
1.325 www 1962: my $key=$uname.':'.$udom.':';
1.109 www 1963: my $status=
1.299 matthew 1964: &del('nohist_calculatedsheets',
1.391 matthew 1965: [$key.'studentcalc:'],
1.620 albertel 1966: $env{'course.'.$cid.'.domain'},
1967: $env{'course.'.$cid.'.num'})
1.133 albertel 1968: .' '.
1969: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 1970: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 1971: unless ($status eq 'ok ok') {
1972: &logthis('Could not devalidate spreadsheet '.
1.325 www 1973: $uname.' at '.$udom.' for '.
1.109 www 1974: $symb.': '.$status);
1.133 albertel 1975: }
1.553 albertel 1976: &delenv('user.state.'.$cid);
1.109 www 1977: }
1978: }
1979:
1.265 albertel 1980: sub get_scalar {
1981: my ($string,$end) = @_;
1982: my $value;
1983: if ($$string =~ s/^([^&]*?)($end)/$2/) {
1984: $value = $1;
1985: } elsif ($$string =~ s/^([^&]*?)&//) {
1986: $value = $1;
1987: }
1988: return &unescape($value);
1989: }
1990:
1991: sub array2str {
1992: my (@array) = @_;
1993: my $result=&arrayref2str(\@array);
1994: $result=~s/^__ARRAY_REF__//;
1995: $result=~s/__END_ARRAY_REF__$//;
1996: return $result;
1997: }
1998:
1.204 albertel 1999: sub arrayref2str {
2000: my ($arrayref) = @_;
1.265 albertel 2001: my $result='__ARRAY_REF__';
1.204 albertel 2002: foreach my $elem (@$arrayref) {
1.265 albertel 2003: if(ref($elem) eq 'ARRAY') {
2004: $result.=&arrayref2str($elem).'&';
2005: } elsif(ref($elem) eq 'HASH') {
2006: $result.=&hashref2str($elem).'&';
2007: } elsif(ref($elem)) {
2008: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 2009: } else {
2010: $result.=&escape($elem).'&';
2011: }
2012: }
2013: $result=~s/\&$//;
1.265 albertel 2014: $result .= '__END_ARRAY_REF__';
1.204 albertel 2015: return $result;
2016: }
2017:
1.168 albertel 2018: sub hash2str {
1.204 albertel 2019: my (%hash) = @_;
2020: my $result=&hashref2str(\%hash);
1.265 albertel 2021: $result=~s/^__HASH_REF__//;
2022: $result=~s/__END_HASH_REF__$//;
1.204 albertel 2023: return $result;
2024: }
2025:
2026: sub hashref2str {
2027: my ($hashref)=@_;
1.265 albertel 2028: my $result='__HASH_REF__';
1.495 albertel 2029: foreach (sort(keys(%$hashref))) {
1.204 albertel 2030: if (ref($_) eq 'ARRAY') {
1.265 albertel 2031: $result.=&arrayref2str($_).'=';
1.204 albertel 2032: } elsif (ref($_) eq 'HASH') {
1.265 albertel 2033: $result.=&hashref2str($_).'=';
1.204 albertel 2034: } elsif (ref($_)) {
1.265 albertel 2035: $result.='=';
2036: #print("Got a ref of ".(ref($_))." skipping.");
1.204 albertel 2037: } else {
1.265 albertel 2038: if ($_) {$result.=&escape($_).'=';} else { last; }
1.204 albertel 2039: }
2040:
1.265 albertel 2041: if(ref($hashref->{$_}) eq 'ARRAY') {
2042: $result.=&arrayref2str($hashref->{$_}).'&';
2043: } elsif(ref($hashref->{$_}) eq 'HASH') {
2044: $result.=&hashref2str($hashref->{$_}).'&';
2045: } elsif(ref($hashref->{$_})) {
2046: $result.='&';
2047: #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204 albertel 2048: } else {
1.265 albertel 2049: $result.=&escape($hashref->{$_}).'&';
1.204 albertel 2050: }
2051: }
1.168 albertel 2052: $result=~s/\&$//;
1.265 albertel 2053: $result .= '__END_HASH_REF__';
1.168 albertel 2054: return $result;
2055: }
2056:
2057: sub str2hash {
1.265 albertel 2058: my ($string)=@_;
2059: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
2060: return %$hash;
2061: }
2062:
2063: sub str2hashref {
1.168 albertel 2064: my ($string) = @_;
1.265 albertel 2065:
2066: my %hash;
2067:
2068: if($string !~ /^__HASH_REF__/) {
2069: if (! ($string eq '' || !defined($string))) {
2070: $hash{'error'}='Not hash reference';
2071: }
2072: return (\%hash, $string);
2073: }
2074:
2075: $string =~ s/^__HASH_REF__//;
2076:
2077: while($string !~ /^__END_HASH_REF__/) {
2078: #key
2079: my $key='';
2080: if($string =~ /^__HASH_REF__/) {
2081: ($key, $string)=&str2hashref($string);
2082: if(defined($key->{'error'})) {
2083: $hash{'error'}='Bad data';
2084: return (\%hash, $string);
2085: }
2086: } elsif($string =~ /^__ARRAY_REF__/) {
2087: ($key, $string)=&str2arrayref($string);
2088: if($key->[0] eq 'Array reference error') {
2089: $hash{'error'}='Bad data';
2090: return (\%hash, $string);
2091: }
2092: } else {
2093: $string =~ s/^(.*?)=//;
1.267 albertel 2094: $key=&unescape($1);
1.265 albertel 2095: }
2096: $string =~ s/^=//;
2097:
2098: #value
2099: my $value='';
2100: if($string =~ /^__HASH_REF__/) {
2101: ($value, $string)=&str2hashref($string);
2102: if(defined($value->{'error'})) {
2103: $hash{'error'}='Bad data';
2104: return (\%hash, $string);
2105: }
2106: } elsif($string =~ /^__ARRAY_REF__/) {
2107: ($value, $string)=&str2arrayref($string);
2108: if($value->[0] eq 'Array reference error') {
2109: $hash{'error'}='Bad data';
2110: return (\%hash, $string);
2111: }
2112: } else {
2113: $value=&get_scalar(\$string,'__END_HASH_REF__');
2114: }
2115: $string =~ s/^&//;
2116:
2117: $hash{$key}=$value;
1.204 albertel 2118: }
1.265 albertel 2119:
2120: $string =~ s/^__END_HASH_REF__//;
2121:
2122: return (\%hash, $string);
1.204 albertel 2123: }
2124:
2125: sub str2array {
1.265 albertel 2126: my ($string)=@_;
2127: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
2128: return @$array;
2129: }
2130:
2131: sub str2arrayref {
1.204 albertel 2132: my ($string) = @_;
1.265 albertel 2133: my @array;
2134:
2135: if($string !~ /^__ARRAY_REF__/) {
2136: if (! ($string eq '' || !defined($string))) {
2137: $array[0]='Array reference error';
2138: }
2139: return (\@array, $string);
2140: }
2141:
2142: $string =~ s/^__ARRAY_REF__//;
2143:
2144: while($string !~ /^__END_ARRAY_REF__/) {
2145: my $value='';
2146: if($string =~ /^__HASH_REF__/) {
2147: ($value, $string)=&str2hashref($string);
2148: if(defined($value->{'error'})) {
2149: $array[0] ='Array reference error';
2150: return (\@array, $string);
2151: }
2152: } elsif($string =~ /^__ARRAY_REF__/) {
2153: ($value, $string)=&str2arrayref($string);
2154: if($value->[0] eq 'Array reference error') {
2155: $array[0] ='Array reference error';
2156: return (\@array, $string);
2157: }
2158: } else {
2159: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
2160: }
2161: $string =~ s/^&//;
2162:
2163: push(@array, $value);
1.191 harris41 2164: }
1.265 albertel 2165:
2166: $string =~ s/^__END_ARRAY_REF__//;
2167:
2168: return (\@array, $string);
1.168 albertel 2169: }
2170:
1.167 albertel 2171: # -------------------------------------------------------------------Temp Store
2172:
1.168 albertel 2173: sub tmpreset {
2174: my ($symb,$namespace,$domain,$stuname) = @_;
2175: if (!$symb) {
2176: $symb=&symbread();
1.620 albertel 2177: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2178: }
2179: $symb=escape($symb);
2180:
1.620 albertel 2181: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 2182: $namespace=~s/\//\_/g;
2183: $namespace=~s/\W//g;
2184:
1.620 albertel 2185: if (!$domain) { $domain=$env{'user.domain'}; }
2186: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2187: if ($domain eq 'public' && $stuname eq 'public') {
2188: $stuname=$ENV{'REMOTE_ADDR'};
2189: }
1.168 albertel 2190: my $path=$perlvar{'lonDaemons'}.'/tmp';
2191: my %hash;
2192: if (tie(%hash,'GDBM_File',
2193: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2194: &GDBM_WRCREAT(),0640)) {
1.168 albertel 2195: foreach my $key (keys %hash) {
1.180 albertel 2196: if ($key=~ /:$symb/) {
1.168 albertel 2197: delete($hash{$key});
2198: }
2199: }
2200: }
2201: }
2202:
1.167 albertel 2203: sub tmpstore {
1.168 albertel 2204: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2205:
2206: if (!$symb) {
2207: $symb=&symbread();
1.620 albertel 2208: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2209: }
2210: $symb=escape($symb);
2211:
2212: if (!$namespace) {
2213: # I don't think we would ever want to store this for a course.
2214: # it seems this will only be used if we don't have a course.
1.620 albertel 2215: #$namespace=$env{'request.course.id'};
1.168 albertel 2216: #if (!$namespace) {
1.620 albertel 2217: $namespace=$env{'request.state'};
1.168 albertel 2218: #}
2219: }
2220: $namespace=~s/\//\_/g;
2221: $namespace=~s/\W//g;
1.620 albertel 2222: if (!$domain) { $domain=$env{'user.domain'}; }
2223: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2224: if ($domain eq 'public' && $stuname eq 'public') {
2225: $stuname=$ENV{'REMOTE_ADDR'};
2226: }
1.168 albertel 2227: my $now=time;
2228: my %hash;
2229: my $path=$perlvar{'lonDaemons'}.'/tmp';
2230: if (tie(%hash,'GDBM_File',
2231: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2232: &GDBM_WRCREAT(),0640)) {
1.168 albertel 2233: $hash{"version:$symb"}++;
2234: my $version=$hash{"version:$symb"};
2235: my $allkeys='';
2236: foreach my $key (keys(%$storehash)) {
2237: $allkeys.=$key.':';
1.591 albertel 2238: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 2239: }
2240: $hash{"$version:$symb:timestamp"}=$now;
2241: $allkeys.='timestamp';
2242: $hash{"$version:keys:$symb"}=$allkeys;
2243: if (untie(%hash)) {
2244: return 'ok';
2245: } else {
2246: return "error:$!";
2247: }
2248: } else {
2249: return "error:$!";
2250: }
2251: }
1.167 albertel 2252:
1.168 albertel 2253: # -----------------------------------------------------------------Temp Restore
1.167 albertel 2254:
1.168 albertel 2255: sub tmprestore {
2256: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 2257:
1.168 albertel 2258: if (!$symb) {
2259: $symb=&symbread();
1.620 albertel 2260: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2261: }
2262: $symb=escape($symb);
2263:
1.620 albertel 2264: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 2265:
1.620 albertel 2266: if (!$domain) { $domain=$env{'user.domain'}; }
2267: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2268: if ($domain eq 'public' && $stuname eq 'public') {
2269: $stuname=$ENV{'REMOTE_ADDR'};
2270: }
1.168 albertel 2271: my %returnhash;
2272: $namespace=~s/\//\_/g;
2273: $namespace=~s/\W//g;
2274: my %hash;
2275: my $path=$perlvar{'lonDaemons'}.'/tmp';
2276: if (tie(%hash,'GDBM_File',
2277: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2278: &GDBM_READER(),0640)) {
1.168 albertel 2279: my $version=$hash{"version:$symb"};
2280: $returnhash{'version'}=$version;
2281: my $scope;
2282: for ($scope=1;$scope<=$version;$scope++) {
2283: my $vkeys=$hash{"$scope:keys:$symb"};
2284: my @keys=split(/:/,$vkeys);
2285: my $key;
2286: $returnhash{"$scope:keys"}=$vkeys;
2287: foreach $key (@keys) {
1.591 albertel 2288: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
2289: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 2290: }
2291: }
1.168 albertel 2292: if (!(untie(%hash))) {
2293: return "error:$!";
2294: }
2295: } else {
2296: return "error:$!";
2297: }
2298: return %returnhash;
1.167 albertel 2299: }
2300:
1.9 www 2301: # ----------------------------------------------------------------------- Store
2302:
2303: sub store {
1.124 www 2304: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2305: my $home='';
2306:
1.168 albertel 2307: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2308:
1.213 www 2309: $symb=&symbclean($symb);
1.122 albertel 2310: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 2311:
1.620 albertel 2312: if (!$domain) { $domain=$env{'user.domain'}; }
2313: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 2314:
2315: &devalidate($symb,$stuname,$domain);
1.109 www 2316:
2317: $symb=escape($symb);
1.187 www 2318: if (!$namespace) {
1.620 albertel 2319: unless ($namespace=$env{'request.course.id'}) {
1.187 www 2320: return '';
2321: }
2322: }
1.620 albertel 2323: if (!$home) { $home=$env{'user.home'}; }
1.447 www 2324:
2325: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2326: $$storehash{'host'}=$perlvar{'lonHostID'};
2327:
1.12 www 2328: my $namevalue='';
1.191 harris41 2329: foreach (keys %$storehash) {
1.591 albertel 2330: $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191 harris41 2331: }
1.12 www 2332: $namevalue=~s/\&$//;
1.187 www 2333: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 2334: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 2335: }
2336:
1.47 www 2337: # -------------------------------------------------------------- Critical Store
2338:
2339: sub cstore {
1.124 www 2340: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2341: my $home='';
2342:
1.168 albertel 2343: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2344:
1.213 www 2345: $symb=&symbclean($symb);
1.122 albertel 2346: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 2347:
1.620 albertel 2348: if (!$domain) { $domain=$env{'user.domain'}; }
2349: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 2350:
2351: &devalidate($symb,$stuname,$domain);
1.109 www 2352:
2353: $symb=escape($symb);
1.187 www 2354: if (!$namespace) {
1.620 albertel 2355: unless ($namespace=$env{'request.course.id'}) {
1.187 www 2356: return '';
2357: }
2358: }
1.620 albertel 2359: if (!$home) { $home=$env{'user.home'}; }
1.447 www 2360:
2361: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2362: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 2363:
1.47 www 2364: my $namevalue='';
1.191 harris41 2365: foreach (keys %$storehash) {
1.591 albertel 2366: $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191 harris41 2367: }
1.47 www 2368: $namevalue=~s/\&$//;
1.187 www 2369: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 2370: return critical
2371: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 2372: }
2373:
1.9 www 2374: # --------------------------------------------------------------------- Restore
2375:
2376: sub restore {
1.124 www 2377: my ($symb,$namespace,$domain,$stuname) = @_;
2378: my $home='';
2379:
1.168 albertel 2380: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2381:
1.122 albertel 2382: if (!$symb) {
2383: unless ($symb=escape(&symbread())) { return ''; }
2384: } else {
1.213 www 2385: $symb=&escape(&symbclean($symb));
1.122 albertel 2386: }
1.188 www 2387: if (!$namespace) {
1.620 albertel 2388: unless ($namespace=$env{'request.course.id'}) {
1.188 www 2389: return '';
2390: }
2391: }
1.620 albertel 2392: if (!$domain) { $domain=$env{'user.domain'}; }
2393: if (!$stuname) { $stuname=$env{'user.name'}; }
2394: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 2395: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
2396:
1.12 www 2397: my %returnhash=();
1.191 harris41 2398: foreach (split(/\&/,$answer)) {
1.12 www 2399: my ($name,$value)=split(/\=/,$_);
1.591 albertel 2400: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 2401: }
1.75 www 2402: my $version;
2403: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191 harris41 2404: foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75 www 2405: $returnhash{$_}=$returnhash{$version.':'.$_};
1.191 harris41 2406: }
1.75 www 2407: }
1.13 www 2408: return %returnhash;
1.34 www 2409: }
2410:
2411: # ---------------------------------------------------------- Course Description
2412:
2413: sub coursedescription {
2414: my $courseid=shift;
2415: $courseid=~s/^\///;
1.49 www 2416: $courseid=~s/\_/\//g;
1.34 www 2417: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 2418: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 2419: my $normalid=$cdomain.'_'.$cnum;
2420: # need to always cache even if we get errors otherwise we keep
2421: # trying and trying and trying to get the course description.
2422: my %envhash=();
2423: my %returnhash=();
2424: $envhash{'course.'.$normalid.'.last_cache'}=time;
1.34 www 2425: if ($chome ne 'no_host') {
1.302 albertel 2426: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 2427: if (!exists($returnhash{'con_lost'})) {
2428: $returnhash{'home'}= $chome;
2429: $returnhash{'domain'} = $cdomain;
2430: $returnhash{'num'} = $cnum;
1.130 albertel 2431: while (my ($name,$value) = each %returnhash) {
1.53 www 2432: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 2433: }
1.270 www 2434: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 2435: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 2436: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 2437: $envhash{'course.'.$normalid.'.home'}=$chome;
2438: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
2439: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 2440: }
2441: }
1.302 albertel 2442: &appenv(%envhash);
2443: return %returnhash;
1.461 www 2444: }
2445:
2446: # -------------------------------------------------See if a user is privileged
2447:
2448: sub privileged {
2449: my ($username,$domain)=@_;
2450: my $rolesdump=&reply("dump:$domain:$username:roles",
2451: &homeserver($username,$domain));
2452: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
2453: my $now=time;
2454: if ($rolesdump ne '') {
2455: foreach (split(/&/,$rolesdump)) {
1.586 albertel 2456: if ($_!~/^rolesdef_/) {
1.461 www 2457: my ($area,$role)=split(/=/,$_);
2458: $area=~s/\_\w\w$//;
2459: my ($trole,$tend,$tstart)=split(/_/,$role);
2460: if (($trole eq 'dc') || ($trole eq 'su')) {
2461: my $active=1;
2462: if ($tend) {
2463: if ($tend<$now) { $active=0; }
2464: }
2465: if ($tstart) {
2466: if ($tstart>$now) { $active=0; }
2467: }
2468: if ($active) { return 1; }
2469: }
2470: }
2471: }
2472: }
2473: return 0;
1.9 www 2474: }
1.1 albertel 2475:
1.103 harris41 2476: # -------------------------------------------------------- Get user privileges
1.11 www 2477:
2478: sub rolesinit {
2479: my ($domain,$username,$authhost)=@_;
2480: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12 www 2481: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11 www 2482: my %allroles=();
2483: my $now=time;
1.21 www 2484: my $userroles="user.login.time=$now\n";
1.11 www 2485:
2486: if ($rolesdump ne '') {
1.191 harris41 2487: foreach (split(/&/,$rolesdump)) {
1.586 albertel 2488: if ($_!~/^rolesdef_/) {
1.11 www 2489: my ($area,$role)=split(/=/,$_);
1.587 albertel 2490: $area=~s/\_\w\w$//;
2491:
2492: my ($trole,$tend,$tstart);
2493: if ($role=~/^cr/) {
2494: ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
2495: ($tend,$tstart)=split('_',$trest);
2496: } else {
2497: ($trole,$tend,$tstart)=split(/_/,$role);
2498: }
1.576 albertel 2499: $userroles.=&set_arearole($trole,$area,$tstart,$tend,$domain,$username);
1.567 raeburn 2500: if (($tend!=0) && ($tend<$now)) { $trole=''; }
2501: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 2502: if (($area ne '') && ($trole ne '')) {
1.347 albertel 2503: my $spec=$trole.'.'.$area;
2504: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
2505: if ($trole =~ /^cr\//) {
1.567 raeburn 2506: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.347 albertel 2507: } else {
1.567 raeburn 2508: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 2509: }
1.12 www 2510: }
2511: }
1.191 harris41 2512: }
1.567 raeburn 2513: my ($author,$adv) = &set_userprivs(\$userroles,\%allroles);
1.128 www 2514: $userroles.='user.adv='.$adv."\n".
2515: 'user.author='.$author."\n";
1.620 albertel 2516: $env{'user.adv'}=$adv;
1.11 www 2517: }
2518: return $userroles;
2519: }
2520:
1.567 raeburn 2521: sub set_arearole {
2522: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
2523: # log the associated role with the area
2524: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
2525: return 'user.role.'.$trole.'.'.$area.'='.$tstart.'.'.$tend."\n";
2526: }
2527:
2528: sub custom_roleprivs {
2529: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
2530: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
2531: my $homsvr=homeserver($rauthor,$rdomain);
2532: if ($hostname{$homsvr} ne '') {
2533: my ($rdummy,$roledef)=
2534: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
2535: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
2536: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
2537: if (defined($syspriv)) {
2538: $$allroles{'cm./'}.=':'.$syspriv;
2539: $$allroles{$spec.'./'}.=':'.$syspriv;
2540: }
2541: if ($tdomain ne '') {
2542: if (defined($dompriv)) {
2543: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
2544: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
2545: }
2546: if (($trest ne '') && (defined($coursepriv))) {
2547: $$allroles{'cm.'.$area}.=':'.$coursepriv;
2548: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
2549: }
2550: }
2551: }
2552: }
2553: }
2554:
2555:
2556: sub standard_roleprivs {
2557: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
2558: if (defined($pr{$trole.':s'})) {
2559: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
2560: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
2561: }
2562: if ($tdomain ne '') {
2563: if (defined($pr{$trole.':d'})) {
2564: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
2565: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
2566: }
2567: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
2568: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
2569: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
2570: }
2571: }
2572: }
2573:
2574: sub set_userprivs {
2575: my ($userroles,$allroles) = @_;
2576: my $author=0;
2577: my $adv=0;
2578: foreach (keys %{$allroles}) {
2579: my %thesepriv=();
2580: if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
2581: foreach (split(/:/,$$allroles{$_})) {
2582: if ($_ ne '') {
2583: my ($privilege,$restrictions)=split(/&/,$_);
2584: if ($restrictions eq '') {
2585: $thesepriv{$privilege}='F';
2586: } elsif ($thesepriv{$privilege} ne 'F') {
2587: $thesepriv{$privilege}.=$restrictions;
2588: }
2589: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
2590: }
2591: }
2592: my $thesestr='';
2593: foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
2594: $$userroles.='user.priv.'.$_.'='.$thesestr."\n";
2595: }
2596: return ($author,$adv);
2597: }
2598:
1.12 www 2599: # --------------------------------------------------------------- get interface
2600:
2601: sub get {
1.131 albertel 2602: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 2603: my $items='';
1.191 harris41 2604: foreach (@$storearr) {
1.12 www 2605: $items.=escape($_).'&';
1.191 harris41 2606: }
1.12 www 2607: $items=~s/\&$//;
1.620 albertel 2608: if (!$udomain) { $udomain=$env{'user.domain'}; }
2609: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 2610: my $uhome=&homeserver($uname,$udomain);
2611:
1.133 albertel 2612: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 2613: my @pairs=split(/\&/,$rep);
1.273 albertel 2614: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2615: return @pairs;
2616: }
1.15 www 2617: my %returnhash=();
1.42 www 2618: my $i=0;
1.191 harris41 2619: foreach (@$storearr) {
1.557 albertel 2620: $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42 www 2621: $i++;
1.191 harris41 2622: }
1.15 www 2623: return %returnhash;
1.27 www 2624: }
2625:
2626: # --------------------------------------------------------------- del interface
2627:
2628: sub del {
1.133 albertel 2629: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 2630: my $items='';
1.191 harris41 2631: foreach (@$storearr) {
1.27 www 2632: $items.=escape($_).'&';
1.191 harris41 2633: }
1.27 www 2634: $items=~s/\&$//;
1.620 albertel 2635: if (!$udomain) { $udomain=$env{'user.domain'}; }
2636: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 2637: my $uhome=&homeserver($uname,$udomain);
2638:
2639: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 2640: }
2641:
2642: # -------------------------------------------------------------- dump interface
2643:
2644: sub dump {
1.193 www 2645: my ($namespace,$udomain,$uname,$regexp)=@_;
1.620 albertel 2646: if (!$udomain) { $udomain=$env{'user.domain'}; }
2647: if (!$uname) { $uname=$env{'user.name'}; }
1.129 albertel 2648: my $uhome=&homeserver($uname,$udomain);
1.193 www 2649: if ($regexp) {
2650: $regexp=&escape($regexp);
2651: } else {
2652: $regexp='.';
2653: }
2654: my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
1.12 www 2655: my @pairs=split(/\&/,$rep);
2656: my %returnhash=();
1.191 harris41 2657: foreach (@pairs) {
1.12 www 2658: my ($key,$value)=split(/=/,$_);
1.557 albertel 2659: $returnhash{unescape($key)}=&thaw_unescape($value);
1.318 matthew 2660: }
2661: return %returnhash;
1.407 www 2662: }
2663:
2664: # -------------------------------------------------------------- keys interface
2665:
2666: sub getkeys {
2667: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 2668: if (!$udomain) { $udomain=$env{'user.domain'}; }
2669: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 2670: my $uhome=&homeserver($uname,$udomain);
2671: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
2672: my @keyarray=();
2673: foreach (split(/\&/,$rep)) {
2674: push (@keyarray,&unescape($_));
2675: }
2676: return @keyarray;
1.318 matthew 2677: }
2678:
1.319 matthew 2679: # --------------------------------------------------------------- currentdump
2680: sub currentdump {
1.328 matthew 2681: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 2682: $courseid = $env{'request.course.id'} if (! defined($courseid));
2683: $sdom = $env{'user.domain'} if (! defined($sdom));
2684: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 2685: my $uhome = &homeserver($sname,$sdom);
2686: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 2687: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 2688: #
1.318 matthew 2689: my %returnhash=();
1.319 matthew 2690: #
2691: if ($rep eq "unknown_cmd") {
2692: # an old lond will not know currentdump
2693: # Do a dump and make it look like a currentdump
1.326 matthew 2694: my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319 matthew 2695: return if ($tmp[0] =~ /^(error:|no_such_host)/);
2696: my %hash = @tmp;
2697: @tmp=();
1.424 matthew 2698: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 2699: } else {
2700: my @pairs=split(/\&/,$rep);
2701: foreach (@pairs) {
2702: my ($key,$value)=split(/=/,$_);
2703: my ($symb,$param) = split(/:/,$key);
2704: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 2705: &thaw_unescape($value);
1.319 matthew 2706: }
1.191 harris41 2707: }
1.12 www 2708: return %returnhash;
1.424 matthew 2709: }
2710:
2711: sub convert_dump_to_currentdump{
2712: my %hash = %{shift()};
2713: my %returnhash;
2714: # Code ripped from lond, essentially. The only difference
2715: # here is the unescaping done by lonnet::dump(). Conceivably
2716: # we might run in to problems with parameter names =~ /^v\./
2717: while (my ($key,$value) = each(%hash)) {
2718: my ($v,$symb,$param) = split(/:/,$key);
2719: next if ($v eq 'version' || $symb eq 'keys');
2720: next if (exists($returnhash{$symb}) &&
2721: exists($returnhash{$symb}->{$param}) &&
2722: $returnhash{$symb}->{'v.'.$param} > $v);
2723: $returnhash{$symb}->{$param}=$value;
2724: $returnhash{$symb}->{'v.'.$param}=$v;
2725: }
2726: #
2727: # Remove all of the keys in the hashes which keep track of
2728: # the version of the parameter.
2729: while (my ($symb,$param_hash) = each(%returnhash)) {
2730: # use a foreach because we are going to delete from the hash.
2731: foreach my $key (keys(%$param_hash)) {
2732: delete($param_hash->{$key}) if ($key =~ /^v\./);
2733: }
2734: }
2735: return \%returnhash;
1.12 www 2736: }
2737:
1.627 albertel 2738: # ------------------------------------------------------ critical inc interface
2739:
2740: sub cinc {
2741: return &inc(@_,'critical');
2742: }
2743:
1.449 matthew 2744: # --------------------------------------------------------------- inc interface
2745:
2746: sub inc {
1.627 albertel 2747: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 2748: if (!$udomain) { $udomain=$env{'user.domain'}; }
2749: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 2750: my $uhome=&homeserver($uname,$udomain);
2751: my $items='';
2752: if (! ref($store)) {
2753: # got a single value, so use that instead
2754: $items = &escape($store).'=&';
2755: } elsif (ref($store) eq 'SCALAR') {
2756: $items = &escape($$store).'=&';
2757: } elsif (ref($store) eq 'ARRAY') {
2758: $items = join('=&',map {&escape($_);} @{$store});
2759: } elsif (ref($store) eq 'HASH') {
2760: while (my($key,$value) = each(%{$store})) {
2761: $items.= &escape($key).'='.&escape($value).'&';
2762: }
2763: }
2764: $items=~s/\&$//;
1.627 albertel 2765: if ($critical) {
2766: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
2767: } else {
2768: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
2769: }
1.449 matthew 2770: }
2771:
1.12 www 2772: # --------------------------------------------------------------- put interface
2773:
2774: sub put {
1.134 albertel 2775: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 2776: if (!$udomain) { $udomain=$env{'user.domain'}; }
2777: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 2778: my $uhome=&homeserver($uname,$udomain);
1.12 www 2779: my $items='';
1.191 harris41 2780: foreach (keys %$storehash) {
1.557 albertel 2781: $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191 harris41 2782: }
1.12 www 2783: $items=~s/\&$//;
1.134 albertel 2784: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 2785: }
2786:
1.631 albertel 2787: # ------------------------------------------------------------ newput interface
2788:
2789: sub newput {
2790: my ($namespace,$storehash,$udomain,$uname)=@_;
2791: if (!$udomain) { $udomain=$env{'user.domain'}; }
2792: if (!$uname) { $uname=$env{'user.name'}; }
2793: my $uhome=&homeserver($uname,$udomain);
2794: my $items='';
2795: foreach my $key (keys(%$storehash)) {
2796: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
2797: }
2798: $items=~s/\&$//;
2799: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
2800: }
2801:
2802: # --------------------------------------------------------- putstore interface
2803:
1.524 raeburn 2804: sub putstore {
2805: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 2806: if (!$udomain) { $udomain=$env{'user.domain'}; }
2807: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 2808: my $uhome=&homeserver($uname,$udomain);
2809: my $items='';
2810: my %allitems = ();
2811: foreach (keys %$storehash) {
2812: if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
2813: my $key = $1.':keys:'.$2;
2814: $allitems{$key} .= $3.':';
2815: }
1.591 albertel 2816: $items.=$_.'='.&freeze_escape($$storehash{$_}).'&';
1.524 raeburn 2817: }
2818: foreach (keys %allitems) {
2819: $allitems{$_} =~ s/\:$//;
2820: $items.= $_.'='.$allitems{$_}.'&';
2821: }
2822: $items=~s/\&$//;
2823: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
2824: }
2825:
1.47 www 2826: # ------------------------------------------------------ critical put interface
2827:
2828: sub cput {
1.134 albertel 2829: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 2830: if (!$udomain) { $udomain=$env{'user.domain'}; }
2831: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 2832: my $uhome=&homeserver($uname,$udomain);
1.47 www 2833: my $items='';
1.191 harris41 2834: foreach (keys %$storehash) {
1.557 albertel 2835: $items.=escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191 harris41 2836: }
1.47 www 2837: $items=~s/\&$//;
1.134 albertel 2838: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 2839: }
2840:
2841: # -------------------------------------------------------------- eget interface
2842:
2843: sub eget {
1.133 albertel 2844: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 2845: my $items='';
1.191 harris41 2846: foreach (@$storearr) {
1.12 www 2847: $items.=escape($_).'&';
1.191 harris41 2848: }
1.12 www 2849: $items=~s/\&$//;
1.620 albertel 2850: if (!$udomain) { $udomain=$env{'user.domain'}; }
2851: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 2852: my $uhome=&homeserver($uname,$udomain);
2853: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 2854: my @pairs=split(/\&/,$rep);
2855: my %returnhash=();
1.42 www 2856: my $i=0;
1.191 harris41 2857: foreach (@$storearr) {
1.557 albertel 2858: $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42 www 2859: $i++;
1.191 harris41 2860: }
1.12 www 2861: return %returnhash;
2862: }
2863:
1.341 www 2864: # ---------------------------------------------- Custom access rule evaluation
2865:
2866: sub customaccess {
2867: my ($priv,$uri)=@_;
1.620 albertel 2868: my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343 www 2869: $urealm=~s/^\W//;
2870: my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341 www 2871: my $access=0;
2872: foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342 www 2873: my ($effect,$realm,$role)=split(/\:/,$_);
1.343 www 2874: if ($role) {
2875: if ($role ne $urole) { next; }
2876: }
2877: foreach (split(/\s*\,\s*/,$realm)) {
2878: my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
2879: if ($tdom) {
2880: if ($tdom ne $udom) { next; }
2881: }
2882: if ($tcrs) {
2883: if ($tcrs ne $ucrs) { next; }
2884: }
2885: if ($tsec) {
2886: if ($tsec ne $usec) { next; }
2887: }
2888: $access=($effect eq 'allow');
2889: last;
1.342 www 2890: }
1.402 bowersj2 2891: if ($realm eq '' && $role eq '') {
2892: $access=($effect eq 'allow');
2893: }
1.341 www 2894: }
2895: return $access;
2896: }
2897:
1.103 harris41 2898: # ------------------------------------------------- Check for a user privilege
1.12 www 2899:
2900: sub allowed {
1.579 albertel 2901: my ($priv,$uri,$symb)=@_;
1.439 www 2902: $uri=&deversion($uri);
1.152 www 2903: my $orguri=$uri;
1.52 www 2904: $uri=&declutter($uri);
1.545 banghart 2905:
2906:
2907:
1.620 albertel 2908: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 2909: # Free bre access to adm and meta resources
1.529 albertel 2910: if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|))
2911: || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14 www 2912: return 'F';
1.159 www 2913: }
2914:
1.545 banghart 2915: # Free bre access to user's own portfolio contents
1.546 albertel 2916: my ($space,$domain,$name,$dir)=split('/',$uri);
1.620 albertel 2917: if (($space=~/^(uploaded|ediupload)$/) && ($env{'user.name'} eq $name) &&
2918: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir)) {
1.545 banghart 2919: return 'F';
2920: }
2921:
1.159 www 2922: # Free bre to public access
2923:
2924: if ($priv eq 'bre') {
1.238 www 2925: my $copyright=&metadata($uri,'copyright');
1.620 albertel 2926: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 2927: return 'F';
2928: }
1.238 www 2929: if ($copyright eq 'priv') {
2930: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 2931: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 2932: return '';
2933: }
2934: }
2935: if ($copyright eq 'domain') {
2936: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 2937: unless (($env{'user.domain'} eq $1) ||
2938: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 2939: return '';
2940: }
1.262 matthew 2941: }
1.620 albertel 2942: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 2943: # Library role, so allow browsing of resources in this domain.
2944: return 'F';
1.238 www 2945: }
1.341 www 2946: if ($copyright eq 'custom') {
2947: unless (&customaccess($priv,$uri)) { return ''; }
2948: }
1.14 www 2949: }
1.264 matthew 2950: # Domain coordinator is trying to create a course
1.620 albertel 2951: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 2952: # uri is the requested domain in this case.
2953: # comparison to 'request.role.domain' shows if the user has selected
2954: # a role of dc for the domain in question.
1.620 albertel 2955: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 2956: }
1.29 www 2957:
1.52 www 2958: my $thisallowed='';
2959: my $statecond=0;
2960: my $courseprivid='';
2961:
2962: # Course
2963:
1.620 albertel 2964: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 2965: $thisallowed.=$1;
2966: }
1.29 www 2967:
1.52 www 2968: # Domain
2969:
1.620 albertel 2970: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 2971: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 2972: $thisallowed.=$1;
2973: }
1.52 www 2974:
2975: # Course: uri itself is a course
1.66 www 2976: my $courseuri=$uri;
2977: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 2978: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 2979:
1.620 albertel 2980: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 2981: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 2982: $thisallowed.=$1;
2983: }
1.29 www 2984:
1.314 www 2985: # URI is an uploaded document for this course
1.611 albertel 2986: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 2987: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.620 albertel 2988: my $refuri=$env{'httpref.'.$orguri};
1.492 albertel 2989: if ($refuri) {
2990: if ($refuri =~ m|^/adm/|) {
2991: $thisallowed='F';
2992: }
2993: }
1.314 www 2994: }
1.492 albertel 2995:
1.52 www 2996: # Full access at system, domain or course-wide level? Exit.
1.29 www 2997:
2998: if ($thisallowed=~/F/) {
2999: return 'F';
3000: }
3001:
1.52 www 3002: # If this is generating or modifying users, exit with special codes
1.29 www 3003:
1.479 albertel 3004: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:\Q$priv\E\:/) {
1.52 www 3005: return $thisallowed;
3006: }
3007: #
1.103 harris41 3008: # Gathered so far: system, domain and course wide privileges
1.52 www 3009: #
3010: # Course: See if uri or referer is an individual resource that is part of
3011: # the course
3012:
1.620 albertel 3013: if ($env{'request.course.id'}) {
1.232 www 3014:
1.620 albertel 3015: $courseprivid=$env{'request.course.id'};
3016: if ($env{'request.course.sec'}) {
3017: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 3018: }
3019: $courseprivid=~s/\_/\//;
3020: my $checkreferer=1;
1.232 www 3021: my ($match,$cond)=&is_on_map($uri);
3022: if ($match) {
3023: $statecond=$cond;
1.620 albertel 3024: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 3025: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 3026: $thisallowed.=$1;
3027: $checkreferer=0;
3028: }
1.29 www 3029: }
1.83 www 3030:
1.148 www 3031: if ($checkreferer) {
1.620 albertel 3032: my $refuri=$env{'httpref.'.$orguri};
1.148 www 3033: unless ($refuri) {
1.620 albertel 3034: foreach (keys %env) {
1.148 www 3035: if ($_=~/^httpref\..*\*/) {
3036: my $pattern=$_;
1.156 www 3037: $pattern=~s/^httpref\.\/res\///;
1.148 www 3038: $pattern=~s/\*/\[\^\/\]\+/g;
3039: $pattern=~s/\//\\\//g;
1.152 www 3040: if ($orguri=~/$pattern/) {
1.620 albertel 3041: $refuri=$env{$_};
1.148 www 3042: }
3043: }
1.191 harris41 3044: }
1.148 www 3045: }
1.232 www 3046:
1.148 www 3047: if ($refuri) {
1.152 www 3048: $refuri=&declutter($refuri);
1.232 www 3049: my ($match,$cond)=&is_on_map($refuri);
3050: if ($match) {
3051: my $refstatecond=$cond;
1.620 albertel 3052: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 3053: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 3054: $thisallowed.=$1;
1.53 www 3055: $uri=$refuri;
3056: $statecond=$refstatecond;
1.52 www 3057: }
3058: }
1.148 www 3059: }
1.29 www 3060: }
1.52 www 3061: }
1.29 www 3062:
1.52 www 3063: #
1.103 harris41 3064: # Gathered now: all privileges that could apply, and condition number
1.52 www 3065: #
3066: #
3067: # Full or no access?
3068: #
1.29 www 3069:
1.52 www 3070: if ($thisallowed=~/F/) {
3071: return 'F';
3072: }
1.29 www 3073:
1.52 www 3074: unless ($thisallowed) {
3075: return '';
3076: }
1.29 www 3077:
1.52 www 3078: # Restrictions exist, deal with them
3079: #
3080: # C:according to course preferences
3081: # R:according to resource settings
3082: # L:unless locked
3083: # X:according to user session state
3084: #
3085:
3086: # Possibly locked functionality, check all courses
1.54 www 3087: # Locks might take effect only after 10 minutes cache expiration for other
3088: # courses, and 2 minutes for current course
1.52 www 3089:
3090: my $envkey;
3091: if ($thisallowed=~/L/) {
1.620 albertel 3092: foreach $envkey (keys %env) {
1.54 www 3093: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
3094: my $courseid=$2;
3095: my $roleid=$1.'.'.$2;
1.92 www 3096: $courseid=~s/^\///;
1.54 www 3097: my $expiretime=600;
1.620 albertel 3098: if ($env{'request.role'} eq $roleid) {
1.54 www 3099: $expiretime=120;
3100: }
3101: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
3102: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 3103: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.54 www 3104: &coursedescription($courseid);
3105: }
1.620 albertel 3106: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
3107: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
3108: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
3109: &log($env{'user.domain'},$env{'user.name'},
3110: $env{'user.home'},
1.57 www 3111: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 3112: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 3113: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 3114: return '';
3115: }
3116: }
1.620 albertel 3117: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
3118: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
3119: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
3120: &log($env{'user.domain'},$env{'user.name'},
3121: $env{'user.home'},
1.57 www 3122: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 3123: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 3124: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 3125: return '';
3126: }
3127: }
3128: }
1.29 www 3129: }
1.52 www 3130: }
3131:
3132: #
3133: # Rest of the restrictions depend on selected course
3134: #
3135:
1.620 albertel 3136: unless ($env{'request.course.id'}) {
1.52 www 3137: return '1';
3138: }
1.29 www 3139:
1.52 www 3140: #
3141: # Now user is definitely in a course
3142: #
1.53 www 3143:
3144:
3145: # Course preferences
3146:
3147: if ($thisallowed=~/C/) {
1.620 albertel 3148: my $rolecode=(split(/\./,$env{'request.role'}))[0];
3149: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
3150: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 3151: =~/\Q$rolecode\E/) {
1.620 albertel 3152: &log($env{'user.domain'},$env{'user.name'},$env{'user.host'},
1.57 www 3153: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
1.620 albertel 3154: $env{'request.course.id'});
1.237 www 3155: return '';
3156: }
3157:
1.620 albertel 3158: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 3159: =~/\Q$unamedom\E/) {
1.620 albertel 3160: &log($env{'user.domain'},$env{'user.name'},$env{'user.host'},
1.237 www 3161: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
1.620 albertel 3162: $env{'request.course.id'});
1.54 www 3163: return '';
3164: }
1.53 www 3165: }
3166:
3167: # Resource preferences
3168:
3169: if ($thisallowed=~/R/) {
1.620 albertel 3170: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 3171: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.620 albertel 3172: &log($env{'user.domain'},$env{'user.name'},$env{'user.host'},
1.57 www 3173: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
1.341 www 3174: return '';
1.54 www 3175: }
1.53 www 3176: }
1.30 www 3177:
1.246 www 3178: # Restricted by state or randomout?
1.30 www 3179:
1.52 www 3180: if ($thisallowed=~/X/) {
1.620 albertel 3181: if ($env{'acc.randomout'}) {
1.579 albertel 3182: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 3183: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 3184: return '';
3185: }
1.247 www 3186: }
3187: if (&condval($statecond)) {
1.52 www 3188: return '2';
3189: } else {
3190: return '';
3191: }
3192: }
1.30 www 3193:
1.52 www 3194: return 'F';
1.232 www 3195: }
3196:
3197: # --------------------------------------------------- Is a resource on the map?
3198:
3199: sub is_on_map {
3200: my $uri=&declutter(shift);
1.435 www 3201: $uri=~s/\.\d+\.(\w+)$/\.$1/;
1.232 www 3202: my @uriparts=split(/\//,$uri);
3203: my $filename=$uriparts[$#uriparts];
3204: my $pathname=$uri;
1.289 bowersj2 3205: $pathname=~s|/\Q$filename\E$||;
1.332 www 3206: $pathname=~s/^adm\/wrapper\///;
1.289 bowersj2 3207: #Trying to find the conditional for the file
1.620 albertel 3208: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 3209: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 3210: if ($match) {
1.289 bowersj2 3211: return (1,$1);
3212: } else {
1.434 www 3213: return (0,0);
1.289 bowersj2 3214: }
1.12 www 3215: }
3216:
1.427 www 3217: # --------------------------------------------------------- Get symb from alias
3218:
3219: sub get_symb_from_alias {
3220: my $symb=shift;
3221: my ($map,$resid,$url)=&decode_symb($symb);
3222: # Already is a symb
3223: if ($url) { return $symb; }
3224: # Must be an alias
3225: my $aliassymb='';
3226: my %bighash;
1.620 albertel 3227: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 3228: &GDBM_READER(),0640)) {
3229: my $rid=$bighash{'mapalias_'.$symb};
3230: if ($rid) {
3231: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 3232: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
3233: $resid,$bighash{'src_'.$rid});
1.427 www 3234: }
3235: untie %bighash;
3236: }
3237: return $aliassymb;
3238: }
3239:
1.12 www 3240: # ----------------------------------------------------------------- Define Role
3241:
3242: sub definerole {
3243: if (allowed('mcr','/')) {
3244: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392 www 3245: foreach (split(':',$sysrole)) {
1.21 www 3246: my ($crole,$cqual)=split(/\&/,$_);
1.479 albertel 3247: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
3248: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
3249: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 3250: return "refused:s:$crole&$cqual";
3251: }
3252: }
1.191 harris41 3253: }
1.392 www 3254: foreach (split(':',$domrole)) {
1.21 www 3255: my ($crole,$cqual)=split(/\&/,$_);
1.479 albertel 3256: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
3257: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
3258: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 3259: return "refused:d:$crole&$cqual";
3260: }
3261: }
1.191 harris41 3262: }
1.392 www 3263: foreach (split(':',$courole)) {
1.21 www 3264: my ($crole,$cqual)=split(/\&/,$_);
1.479 albertel 3265: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
3266: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
3267: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 3268: return "refused:c:$crole&$cqual";
3269: }
3270: }
1.191 harris41 3271: }
1.620 albertel 3272: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
3273: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 3274: "rolesdef_$rolename=".
3275: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 3276: return reply($command,$env{'user.home'});
1.12 www 3277: } else {
3278: return 'refused';
3279: }
1.105 harris41 3280: }
3281:
3282: # ---------------- Make a metadata query against the network of library servers
3283:
3284: sub metadata_query {
1.244 matthew 3285: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 3286: my %rhash;
1.244 matthew 3287: my @server_list = (defined($server_array) ? @$server_array
3288: : keys(%libserv) );
3289: for my $server (@server_list) {
1.118 harris41 3290: unless ($custom or $customshow) {
3291: my $reply=&reply("querysend:".&escape($query),$server);
3292: $rhash{$server}=$reply;
3293: }
3294: else {
3295: my $reply=&reply("querysend:".&escape($query).':'.
3296: &escape($custom).':'.&escape($customshow),
3297: $server);
3298: $rhash{$server}=$reply;
3299: }
1.112 harris41 3300: }
1.118 harris41 3301: return \%rhash;
1.240 www 3302: }
3303:
3304: # ----------------------------------------- Send log queries and wait for reply
3305:
3306: sub log_query {
3307: my ($uname,$udom,$query,%filters)=@_;
3308: my $uhome=&homeserver($uname,$udom);
3309: if ($uhome eq 'no_host') { return 'error: no_host'; }
3310: my $uhost=$hostname{$uhome};
1.241 www 3311: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240 www 3312: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
3313: $uhome);
1.479 albertel 3314: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 3315: return get_query_reply($queryid);
3316: }
3317:
1.508 raeburn 3318: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 3319:
3320: sub fetch_enrollment_query {
1.511 raeburn 3321: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 3322: my $homeserver;
1.547 raeburn 3323: my $maxtries = 1;
1.508 raeburn 3324: if ($context eq 'automated') {
3325: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 3326: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 3327: } else {
3328: $homeserver = &homeserver($cnum,$dom);
3329: }
1.506 raeburn 3330: my $host=$hostname{$homeserver};
3331: my $cmd = '';
3332: foreach (keys %{$affiliatesref}) {
1.508 raeburn 3333: $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506 raeburn 3334: }
3335: $cmd =~ s/%%$//;
3336: $cmd = &escape($cmd);
3337: my $query = 'fetchenrollment';
1.620 albertel 3338: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 3339: unless ($queryid=~/^\Q$host\E\_/) {
3340: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
3341: return 'error: '.$queryid;
3342: }
1.506 raeburn 3343: my $reply = &get_query_reply($queryid);
1.547 raeburn 3344: my $tries = 1;
3345: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
3346: $reply = &get_query_reply($queryid);
3347: $tries ++;
3348: }
1.526 raeburn 3349: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 3350: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 3351: } else {
1.515 raeburn 3352: my @responses = split/:/,$reply;
3353: if ($homeserver eq $perlvar{'lonHostID'}) {
3354: foreach (@responses) {
3355: my ($key,$value) = split/=/,$_;
3356: $$replyref{$key} = $value;
3357: }
3358: } else {
1.506 raeburn 3359: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
3360: foreach (@responses) {
3361: my ($key,$value) = split/=/,$_;
3362: $$replyref{$key} = $value;
3363: if ($value > 0) {
3364: foreach (@{$$affiliatesref{$key}}) {
3365: my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
3366: my $destname = $pathname.'/'.$filename;
3367: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 3368: if ($xml_classlist =~ /^error/) {
3369: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
3370: } else {
1.506 raeburn 3371: if ( open(FILE,">$destname") ) {
3372: print FILE &unescape($xml_classlist);
3373: close(FILE);
1.526 raeburn 3374: } else {
3375: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 3376: }
3377: }
3378: }
3379: }
3380: }
3381: }
3382: return 'ok';
3383: }
3384: return 'error';
3385: }
3386:
1.242 www 3387: sub get_query_reply {
3388: my $queryid=shift;
1.240 www 3389: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
3390: my $reply='';
3391: for (1..100) {
3392: sleep 2;
3393: if (-e $replyfile.'.end') {
1.448 albertel 3394: if (open(my $fh,$replyfile)) {
1.240 www 3395: $reply.=<$fh>;
1.448 albertel 3396: close($fh);
1.240 www 3397: } else { return 'error: reply_file_error'; }
1.242 www 3398: return &unescape($reply);
3399: }
1.240 www 3400: }
1.242 www 3401: return 'timeout:'.$queryid;
1.240 www 3402: }
3403:
3404: sub courselog_query {
1.241 www 3405: #
3406: # possible filters:
3407: # url: url or symb
3408: # username
3409: # domain
3410: # action: view, submit, grade
3411: # start: timestamp
3412: # end: timestamp
3413: #
1.240 www 3414: my (%filters)=@_;
1.620 albertel 3415: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 3416: if ($filters{'url'}) {
3417: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
3418: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
3419: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
3420: }
1.620 albertel 3421: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
3422: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 3423: return &log_query($cname,$cdom,'courselog',%filters);
3424: }
3425:
3426: sub userlog_query {
3427: my ($uname,$udom,%filters)=@_;
3428: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 3429: }
3430:
1.506 raeburn 3431: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
3432:
3433: sub auto_run {
1.508 raeburn 3434: my ($cnum,$cdom) = @_;
3435: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 3436: my $response = &reply('autorun:'.$cdom,$homeserver);
1.506 raeburn 3437: return $response;
3438: }
3439:
3440: sub auto_get_sections {
1.508 raeburn 3441: my ($cnum,$cdom,$inst_coursecode) = @_;
3442: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 3443: my @secs = ();
1.511 raeburn 3444: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 3445: unless ($response eq 'refused') {
3446: @secs = split/:/,$response;
3447: }
3448: return @secs;
3449: }
3450:
3451: sub auto_new_course {
1.508 raeburn 3452: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
3453: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 3454: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 3455: return $response;
3456: }
3457:
3458: sub auto_validate_courseID {
1.508 raeburn 3459: my ($cnum,$cdom,$inst_course_id) = @_;
3460: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 3461: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 3462: return $response;
3463: }
3464:
3465: sub auto_create_password {
1.508 raeburn 3466: my ($cnum,$cdom,$authparam) = @_;
3467: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 3468: my $create_passwd = 0;
3469: my $authchk = '';
1.511 raeburn 3470: my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506 raeburn 3471: if ($response eq 'refused') {
3472: $authchk = 'refused';
3473: } else {
3474: ($authparam,$create_passwd,$authchk) = split/:/,$response;
3475: }
3476: return ($authparam,$create_passwd,$authchk);
3477: }
3478:
1.521 raeburn 3479: sub auto_instcode_format {
3480: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
3481: my $courses = '';
3482: my $homeserver;
3483: if ($caller eq 'global') {
1.584 raeburn 3484: foreach my $tryserver (keys %libserv) {
3485: if ($hostdom{$tryserver} eq $codedom) {
3486: $homeserver = $tryserver;
3487: last;
3488: }
3489: }
1.620 albertel 3490: if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
3491: $homeserver = &homeserver($env{'user.name'},$codedom);
1.584 raeburn 3492: }
1.521 raeburn 3493: } else {
3494: $homeserver = &homeserver($caller,$codedom);
3495: }
3496: foreach (keys %{$instcodes}) {
3497: $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
3498: }
3499: chop($courses);
3500: my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
3501: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
3502: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
3503: %{$codes} = &str2hash($codes_str);
3504: @{$codetitles} = &str2array($codetitles_str);
3505: %{$cat_titles} = &str2hash($cat_titles_str);
3506: %{$cat_order} = &str2hash($cat_order_str);
3507: return 'ok';
3508: }
3509: return $response;
3510: }
3511:
1.12 www 3512: # ------------------------------------------------------------------ Plain Text
3513:
3514: sub plaintext {
1.22 www 3515: my $short=shift;
1.414 www 3516: return &mt($prp{$short});
1.12 www 3517: }
3518:
3519: # ----------------------------------------------------------------- Assign Role
3520:
3521: sub assignrole {
1.357 www 3522: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21 www 3523: my $mrole;
3524: if ($role =~ /^cr\//) {
1.393 www 3525: my $cwosec=$url;
3526: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
3527: unless (&allowed('ccr',$cwosec)) {
1.104 www 3528: &logthis('Refused custom assignrole: '.
3529: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 3530: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 3531: return 'refused';
3532: }
1.21 www 3533: $mrole='cr';
3534: } else {
1.82 www 3535: my $cwosec=$url;
1.83 www 3536: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373 www 3537: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
1.104 www 3538: &logthis('Refused assignrole: '.
3539: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 3540: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 3541: return 'refused';
3542: }
1.21 www 3543: $mrole=$role;
3544: }
1.620 albertel 3545: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 3546: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 3547: if ($end) { $command.='_'.$end; }
1.21 www 3548: if ($start) {
3549: if ($end) {
1.81 www 3550: $command.='_'.$start;
1.21 www 3551: } else {
1.81 www 3552: $command.='_0_'.$start;
1.21 www 3553: }
3554: }
1.357 www 3555: # actually delete
3556: if ($deleteflag) {
1.373 www 3557: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 3558: # modify command to delete the role
1.620 albertel 3559: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 3560: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 3561: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 3562: # set start and finish to negative values for userrolelog
3563: $start=-1;
3564: $end=-1;
3565: }
3566: }
3567: # send command
1.349 www 3568: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 3569: # log new user role if status is ok
1.349 www 3570: if ($answer eq 'ok') {
3571: &userrolelog($mrole,$uname,$udom,$url,$start,$end);
3572: }
3573: return $answer;
1.169 harris41 3574: }
3575:
3576: # -------------------------------------------------- Modify user authentication
1.197 www 3577: # Overrides without validation
3578:
1.169 harris41 3579: sub modifyuserauth {
3580: my ($udom,$uname,$umode,$upass)=@_;
3581: my $uhome=&homeserver($uname,$udom);
1.197 www 3582: unless (&allowed('mau',$udom)) { return 'refused'; }
3583: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 3584: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
3585: ' in domain '.$env{'request.role.domain'});
1.169 harris41 3586: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
3587: &escape($upass),$uhome);
1.620 albertel 3588: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 3589: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
3590: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
3591: &log($udom,,$uname,$uhome,
1.620 albertel 3592: 'Authentication changed by '.$env{'user.domain'}.', '.
3593: $env{'user.name'}.', '.$umode.
1.197 www 3594: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 3595: unless ($reply eq 'ok') {
1.197 www 3596: &logthis('Authentication mode error: '.$reply);
1.169 harris41 3597: return 'error: '.$reply;
3598: }
1.170 harris41 3599: return 'ok';
1.80 www 3600: }
3601:
1.81 www 3602: # --------------------------------------------------------------- Modify a user
1.80 www 3603:
1.81 www 3604: sub modifyuser {
1.206 matthew 3605: my ($udom, $uname, $uid,
3606: $umode, $upass, $first,
3607: $middle, $last, $gene,
1.387 www 3608: $forceid, $desiredhome, $email)=@_;
1.198 www 3609: $udom=~s/\W//g;
3610: $uname=~s/\W//g;
1.81 www 3611: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 3612: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 3613: $last.', '.$gene.'(forceid: '.$forceid.')'.
3614: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
3615: ' desiredhome not specified').
1.620 albertel 3616: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
3617: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 3618: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 3619: # ----------------------------------------------------------------- Create User
1.406 albertel 3620: if (($uhome eq 'no_host') &&
3621: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 3622: my $unhome='';
1.209 matthew 3623: if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) {
3624: $unhome = $desiredhome;
1.620 albertel 3625: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
3626: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 3627: } else { # load balancing routine for determining $unhome
1.80 www 3628: my $tryserver;
1.81 www 3629: my $loadm=10000000;
1.80 www 3630: foreach $tryserver (keys %libserv) {
3631: if ($hostdom{$tryserver} eq $udom) {
3632: my $answer=reply('load',$tryserver);
3633: if (($answer=~/\d+/) && ($answer<$loadm)) {
3634: $loadm=$answer;
3635: $unhome=$tryserver;
3636: }
3637: }
3638: }
3639: }
3640: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 3641: return 'error: unable to find a home server for '.$uname.
3642: ' in domain '.$udom;
1.80 www 3643: }
3644: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
3645: &escape($upass),$unhome);
3646: unless ($reply eq 'ok') {
3647: return 'error: '.$reply;
3648: }
1.230 stredwic 3649: $uhome=&homeserver($uname,$udom,'true');
1.80 www 3650: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 3651: return 'error: unable verify users home machine.';
1.80 www 3652: }
1.209 matthew 3653: } # End of creation of new user
1.80 www 3654: # ---------------------------------------------------------------------- Add ID
3655: if ($uid) {
3656: $uid=~tr/A-Z/a-z/;
3657: my %uidhash=&idrget($udom,$uname);
1.196 www 3658: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
3659: && (!$forceid)) {
1.80 www 3660: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 3661: return 'error: user id "'.$uid.'" does not match '.
3662: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 3663: }
3664: } else {
3665: &idput($udom,($uname => $uid));
3666: }
3667: }
3668: # -------------------------------------------------------------- Add names, etc
1.313 matthew 3669: my @tmp=&get('environment',
1.134 albertel 3670: ['firstname','middlename','lastname','generation'],
3671: $udom,$uname);
1.313 matthew 3672: my %names;
3673: if ($tmp[0] =~ m/^error:.*/) {
3674: %names=();
3675: } else {
3676: %names = @tmp;
3677: }
1.388 www 3678: #
3679: # Make sure to not trash student environment if instructor does not bother
3680: # to supply name and email information
3681: #
3682: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 3683: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 3684: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 3685: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 3686: if ($email) {
3687: $email=~s/[^\w\@\.\-\,]//gs;
3688: if ($email=~/\@/) { $names{'notification'} = $email;
3689: $names{'critnotification'} = $email;
3690: $names{'permanentemail'} = $email; }
3691: }
1.134 albertel 3692: my $reply = &put('environment', \%names, $udom,$uname);
3693: if ($reply ne 'ok') { return 'error: '.$reply; }
1.81 www 3694: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 3695: $umode.', '.$first.', '.$middle.', '.
3696: $last.', '.$gene.' by '.
1.620 albertel 3697: $env{'user.name'}.' at '.$env{'user.domain'});
1.134 albertel 3698: return 'ok';
1.80 www 3699: }
3700:
1.81 www 3701: # -------------------------------------------------------------- Modify student
1.80 www 3702:
1.81 www 3703: sub modifystudent {
3704: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515 raeburn 3705: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455 albertel 3706: if (!$cid) {
1.620 albertel 3707: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 3708: return 'not_in_class';
3709: }
1.80 www 3710: }
3711: # --------------------------------------------------------------- Make the user
1.81 www 3712: my $reply=&modifyuser
1.209 matthew 3713: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 3714: $desiredhome,$email);
1.80 www 3715: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 3716: # This will cause &modify_student_enrollment to get the uid from the
3717: # students environment
3718: $uid = undef if (!$forceid);
1.455 albertel 3719: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515 raeburn 3720: $gene,$usec,$end,$start,$type,$locktype,$cid);
1.297 matthew 3721: return $reply;
3722: }
3723:
3724: sub modify_student_enrollment {
1.515 raeburn 3725: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455 albertel 3726: my ($cdom,$cnum,$chome);
3727: if (!$cid) {
1.620 albertel 3728: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 3729: return 'not_in_class';
3730: }
1.620 albertel 3731: $cdom=$env{'course.'.$cid.'.domain'};
3732: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 3733: } else {
3734: ($cdom,$cnum)=split(/_/,$cid);
3735: }
1.620 albertel 3736: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 3737: if (!$chome) {
1.457 raeburn 3738: $chome=&homeserver($cnum,$cdom);
1.297 matthew 3739: }
1.455 albertel 3740: if (!$chome) { return 'unknown_course'; }
1.297 matthew 3741: # Make sure the user exists
1.81 www 3742: my $uhome=&homeserver($uname,$udom);
3743: if (($uhome eq '') || ($uhome eq 'no_host')) {
3744: return 'error: no such user';
3745: }
1.297 matthew 3746: # Get student data if we were not given enough information
3747: if (!defined($first) || $first eq '' ||
3748: !defined($last) || $last eq '' ||
3749: !defined($uid) || $uid eq '' ||
3750: !defined($middle) || $middle eq '' ||
3751: !defined($gene) || $gene eq '') {
1.294 matthew 3752: # They did not supply us with enough data to enroll the student, so
3753: # we need to pick up more information.
1.297 matthew 3754: my %tmp = &get('environment',
1.294 matthew 3755: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 3756: ,$udom,$uname);
3757:
1.455 albertel 3758: #foreach (keys(%tmp)) {
3759: # &logthis("key $_ = ".$tmp{$_});
3760: #}
1.294 matthew 3761: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
3762: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
3763: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 3764: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 3765: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
3766: }
1.556 albertel 3767: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 3768: my $reply=cput('classlist',
3769: {"$uname:$udom" =>
1.515 raeburn 3770: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 3771: $cdom,$cnum);
1.81 www 3772: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
3773: return 'error: '.$reply;
3774: }
1.297 matthew 3775: # Add student role to user
1.83 www 3776: my $uurl='/'.$cid;
1.81 www 3777: $uurl=~s/\_/\//g;
3778: if ($usec) {
3779: $uurl.='/'.$usec;
3780: }
3781: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21 www 3782: }
3783:
1.556 albertel 3784: sub format_name {
3785: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
3786: my $name;
3787: if ($first ne 'lastname') {
3788: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
3789: } else {
3790: if ($lastname=~/\S/) {
3791: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
3792: $name=~s/\s+,/,/;
3793: } else {
3794: $name.= $firstname.' '.$middlename.' '.$generation;
3795: }
3796: }
3797: $name=~s/^\s+//;
3798: $name=~s/\s+$//;
3799: $name=~s/\s+/ /g;
3800: return $name;
3801: }
3802:
1.84 www 3803: # ------------------------------------------------- Write to course preferences
3804:
3805: sub writecoursepref {
3806: my ($courseid,%prefs)=@_;
3807: $courseid=~s/^\///;
3808: $courseid=~s/\_/\//g;
3809: my ($cdomain,$cnum)=split(/\//,$courseid);
3810: my $chome=homeserver($cnum,$cdomain);
3811: if (($chome eq '') || ($chome eq 'no_host')) {
3812: return 'error: no such course';
3813: }
3814: my $cstring='';
1.191 harris41 3815: foreach (keys %prefs) {
1.84 www 3816: $cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191 harris41 3817: }
1.84 www 3818: $cstring=~s/\&$//;
3819: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
3820: }
3821:
3822: # ---------------------------------------------------------- Make/modify course
3823:
3824: sub createcourse {
1.571 raeburn 3825: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner)=@_;
1.84 www 3826: $url=&declutter($url);
3827: my $cid='';
1.264 matthew 3828: unless (&allowed('ccc',$udom)) {
1.84 www 3829: return 'refused';
3830: }
3831: # ------------------------------------------------------------------- Create ID
3832: my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
3833: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
3834: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 3835: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 3836: unless (($uhome eq '') || ($uhome eq 'no_host')) {
3837: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
3838: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 3839: $uhome=&homeserver($uname,$udom,'true');
1.84 www 3840: unless (($uhome eq '') || ($uhome eq 'no_host')) {
3841: return 'error: unable to generate unique course-ID';
3842: }
3843: }
1.264 matthew 3844: # ------------------------------------------------ Check supplied server name
1.620 albertel 3845: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264 matthew 3846: if (! exists($libserv{$course_server})) {
3847: return 'error:bad server name '.$course_server;
3848: }
1.84 www 3849: # ------------------------------------------------------------- Make the course
3850: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 3851: $course_server);
1.84 www 3852: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 3853: $uhome=&homeserver($uname,$udom,'true');
1.84 www 3854: if (($uhome eq '') || ($uhome eq 'no_host')) {
3855: return 'error: no such course';
3856: }
1.271 www 3857: # ----------------------------------------------------------------- Course made
1.516 raeburn 3858: # log existence
3859: &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.571 raeburn 3860: ':'.&escape($inst_code).':'.&escape($course_owner),$uhome);
1.358 www 3861: &flushcourselogs();
3862: # set toplevel url
1.271 www 3863: my $topurl=$url;
3864: unless ($nonstandard) {
3865: # ------------------------------------------ For standard courses, make top url
3866: my $mapurl=&clutter($url);
1.278 www 3867: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 3868: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 3869: <map>
3870: <resource id="1" type="start"></resource>
3871: <resource id="2" src="$mapurl"></resource>
3872: <resource id="3" type="finish"></resource>
3873: <link index="1" from="1" to="2"></link>
3874: <link index="2" from="2" to="3"></link>
3875: </map>
3876: ENDINITMAP
3877: $topurl=&declutter(
3878: &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence')
3879: );
3880: }
3881: # ----------------------------------------------------------- Write preferences
1.84 www 3882: &writecoursepref($udom.'_'.$uname,
3883: ('description' => $description,
1.271 www 3884: 'url' => $topurl));
1.84 www 3885: return '/'.$udom.'/'.$uname;
3886: }
3887:
1.21 www 3888: # ---------------------------------------------------------- Assign Custom Role
3889:
3890: sub assigncustomrole {
1.357 www 3891: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21 www 3892: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357 www 3893: $end,$start,$deleteflag);
1.21 www 3894: }
3895:
3896: # ----------------------------------------------------------------- Revoke Role
3897:
3898: sub revokerole {
1.357 www 3899: my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21 www 3900: my $now=time;
1.357 www 3901: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21 www 3902: }
3903:
3904: # ---------------------------------------------------------- Revoke Custom Role
3905:
3906: sub revokecustomrole {
1.357 www 3907: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21 www 3908: my $now=time;
1.357 www 3909: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
3910: $deleteflag);
1.17 www 3911: }
3912:
1.533 banghart 3913: # ------------------------------------------------------------ Disk usage
1.535 albertel 3914: sub diskusage {
1.533 banghart 3915: my ($udom,$uname,$directoryRoot)=@_;
3916: $directoryRoot =~ s/\/$//;
1.535 albertel 3917: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514 albertel 3918: return $listing;
1.512 banghart 3919: }
3920:
1.566 banghart 3921: sub is_locked {
3922: my ($file_name, $domain, $user) = @_;
3923: my @check;
3924: my $is_locked;
3925: push @check, $file_name;
1.613 albertel 3926: my %locked = &get('file_permissions',\@check,
1.620 albertel 3927: $env{'user.domain'},$env{'user.name'});
1.615 albertel 3928: my ($tmp)=keys(%locked);
3929: if ($tmp=~/^error:/) { undef(%locked); }
1.613 albertel 3930:
1.566 banghart 3931: if (ref($locked{$file_name}) eq 'ARRAY') {
3932: $is_locked = 'true';
3933: } else {
3934: $is_locked = 'false';
3935: }
3936: }
3937:
1.559 banghart 3938: # ------------------------------------------------------------- Mark as Read Only
3939:
3940: sub mark_as_readonly {
3941: my ($domain,$user,$files,$what) = @_;
1.613 albertel 3942: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 3943: my ($tmp)=keys(%current_permissions);
3944: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 3945: foreach my $file (@{$files}) {
1.561 banghart 3946: push(@{$current_permissions{$file}},$what);
1.559 banghart 3947: }
1.613 albertel 3948: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 3949: return;
3950: }
3951:
1.572 banghart 3952: # ------------------------------------------------------------Save Selected Files
3953:
3954: sub save_selected_files {
3955: my ($user, $path, @files) = @_;
3956: my $filename = $user."savedfiles";
1.573 banghart 3957: my @other_files = &files_not_in_path($user, $path);
1.574 banghart 3958: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 3959: foreach my $file (@files) {
1.620 albertel 3960: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 3961: }
3962: foreach my $file (@other_files) {
1.574 banghart 3963: print (OUT $file."\n");
1.572 banghart 3964: }
1.574 banghart 3965: close (OUT);
1.572 banghart 3966: return 'ok';
3967: }
3968:
1.574 banghart 3969: sub clear_selected_files {
3970: my ($user) = @_;
3971: my $filename = $user."savedfiles";
3972: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
3973: print (OUT undef);
3974: close (OUT);
3975: return ("ok");
3976: }
3977:
1.572 banghart 3978: sub files_in_path {
3979: my ($user, $path) = @_;
3980: my $filename = $user."savedfiles";
3981: my %return_files;
1.574 banghart 3982: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 3983: while (my $line_in = <IN>) {
1.574 banghart 3984: chomp ($line_in);
3985: my @paths_and_file = split (m!/!, $line_in);
3986: my $file_part = pop (@paths_and_file);
3987: my $path_part = join ('/', @paths_and_file);
1.573 banghart 3988: $path_part.='/';
3989: my $path_and_file = $path_part.$file_part;
3990: if ($path_part eq $path) {
3991: $return_files{$file_part}= 'selected';
3992: }
3993: }
1.574 banghart 3994: close (IN);
3995: return (\%return_files);
1.572 banghart 3996: }
3997:
3998: # called in portfolio select mode, to show files selected NOT in current directory
3999: sub files_not_in_path {
4000: my ($user, $path) = @_;
4001: my $filename = $user."savedfiles";
4002: my @return_files;
4003: my $path_part;
1.574 banghart 4004: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572 banghart 4005: while (<IN>) {
4006: #ok, I know it's clunky, but I want it to work
4007: my @paths_and_file = split m!/!, $_;
1.574 banghart 4008: my $file_part = pop (@paths_and_file);
4009: chomp ($file_part);
4010: my $path_part = join ('/', @paths_and_file);
1.572 banghart 4011: $path_part .= '/';
4012: my $path_and_file = $path_part.$file_part;
4013: if ($path_part ne $path) {
1.574 banghart 4014: push (@return_files, ($path_and_file));
1.572 banghart 4015: }
4016: }
1.574 banghart 4017: close (OUT);
4018: return (@return_files);
1.572 banghart 4019: }
4020:
1.561 banghart 4021: #--------------------------------------------------------------Get Marked as Read Only
4022:
1.629 banghart 4023:
1.561 banghart 4024: sub get_marked_as_readonly {
4025: my ($domain,$user,$what) = @_;
1.613 albertel 4026: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 4027: my ($tmp)=keys(%current_permissions);
4028: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.563 banghart 4029: my @readonly_files;
1.629 banghart 4030: my $cmp1=$what;
4031: if (ref($what)) { $cmp1=join('',@{$what}) };
1.563 banghart 4032: while (my ($file_name,$value) = each(%current_permissions)) {
1.561 banghart 4033: if (ref($value) eq "ARRAY"){
4034: foreach my $stored_what (@{$value}) {
1.629 banghart 4035: my $cmp2=$stored_what;
4036: if (ref($stored_what)) { $cmp2=join('',@{$stored_what}) };
4037: if ($cmp1 eq $cmp2) {
1.561 banghart 4038: push(@readonly_files, $file_name);
1.563 banghart 4039: } elsif (!defined($what)) {
4040: push(@readonly_files, $file_name);
1.561 banghart 4041: }
4042: }
4043: }
4044: }
4045: return @readonly_files;
4046: }
1.577 banghart 4047: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 4048:
1.577 banghart 4049: sub get_marked_as_readonly_hash {
4050: my ($domain,$user,$what) = @_;
1.613 albertel 4051: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 4052: my ($tmp)=keys(%current_permissions);
4053: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613 albertel 4054:
1.577 banghart 4055: my %readonly_files;
4056: while (my ($file_name,$value) = each(%current_permissions)) {
4057: if (ref($value) eq "ARRAY"){
4058: foreach my $stored_what (@{$value}) {
4059: if ($stored_what eq $what) {
4060: $readonly_files{$file_name} = 'locked';
4061: } elsif (!defined($what)) {
4062: $readonly_files{$file_name} = 'locked';
4063: }
4064: }
4065: }
4066: }
4067: return %readonly_files;
4068: }
1.559 banghart 4069: # ------------------------------------------------------------ Unmark as Read Only
4070:
4071: sub unmark_as_readonly {
1.629 banghart 4072: # unmarks $file_name (if $file_name is defined), or all files locked by $what
4073: # for portfolio submissions, $what contains [$symb,$crsid]
4074: my ($domain,$user,$what,$file_name) = @_;
1.634 albertel 4075: my $symb_crs = $what;
4076: if (ref($what)) { $symb_crs=join('',@$what); }
1.613 albertel 4077: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 4078: my ($tmp)=keys(%current_permissions);
4079: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613 albertel 4080: my @readonly_files = &get_marked_as_readonly($domain,$user,$what);
1.561 banghart 4081: foreach my $file(@readonly_files){
1.563 banghart 4082: my $current_locks = $current_permissions{$file};
4083: my @new_locks;
4084: my @del_keys;
4085: if (ref($current_locks) eq "ARRAY"){
4086: foreach my $locker (@{$current_locks}) {
1.632 albertel 4087: my $compare=$locker;
4088: if (ref($locker)) { $compare=join('',@{$locker}) };
4089: if ($compare eq $symb_crs) {
1.629 banghart 4090: if (defined($file_name) && ($file_name ne $file)) {
4091: push(@new_locks, $what);
4092: }
4093: } else {
1.563 banghart 4094: push(@new_locks, $what);
4095: }
4096: }
4097: if (@new_locks > 0) {
4098: $current_permissions{$file} = \@new_locks;
4099: } else {
4100: push(@del_keys, $file);
1.613 albertel 4101: &del('file_permissions',\@del_keys, $domain, $user);
1.563 banghart 4102: delete $current_permissions{$file};
4103: }
4104: }
1.561 banghart 4105: }
1.613 albertel 4106: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 4107: return;
4108: }
1.512 banghart 4109:
1.17 www 4110: # ------------------------------------------------------------ Directory lister
4111:
4112: sub dirlist {
1.253 stredwic 4113: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
4114:
1.18 www 4115: $uri=~s/^\///;
4116: $uri=~s/\/$//;
1.253 stredwic 4117: my ($udom, $uname);
4118: (undef,$udom,$uname)=split(/\//,$uri);
4119: if(defined($userdomain)) {
4120: $udom = $userdomain;
4121: }
4122: if(defined($username)) {
4123: $uname = $username;
4124: }
4125:
4126: my $dirRoot = $perlvar{'lonDocRoot'};
4127: if(defined($alternateDirectoryRoot)) {
4128: $dirRoot = $alternateDirectoryRoot;
4129: $dirRoot =~ s/\/$//;
4130: }
4131:
4132: if($udom) {
4133: if($uname) {
1.605 matthew 4134: my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253 stredwic 4135: homeserver($uname,$udom));
1.605 matthew 4136: my @listing_results;
4137: if ($listing eq 'unknown_cmd') {
4138: $listing=reply('ls:'.$dirRoot.'/'.$uri,
4139: homeserver($uname,$udom));
4140: @listing_results = split(/:/,$listing);
4141: } else {
4142: @listing_results = map { &unescape($_); } split(/:/,$listing);
4143: }
4144: return @listing_results;
1.253 stredwic 4145: } elsif(!defined($alternateDirectoryRoot)) {
4146: my $tryserver;
4147: my %allusers=();
4148: foreach $tryserver (keys %libserv) {
4149: if($hostdom{$tryserver} eq $udom) {
1.605 matthew 4150: my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253 stredwic 4151: $udom, $tryserver);
1.605 matthew 4152: my @listing_results;
4153: if ($listing eq 'unknown_cmd') {
4154: $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
4155: $udom, $tryserver);
4156: @listing_results = split(/:/,$listing);
4157: } else {
4158: @listing_results =
4159: map { &unescape($_); } split(/:/,$listing);
4160: }
4161: if ($listing_results[0] ne 'no_such_dir' &&
4162: $listing_results[0] ne 'empty' &&
4163: $listing_results[0] ne 'con_lost') {
4164: foreach (@listing_results) {
1.253 stredwic 4165: my ($entry,@stat)=split(/&/,$_);
4166: $allusers{$entry}=1;
4167: }
4168: }
1.191 harris41 4169: }
1.253 stredwic 4170: }
4171: my $alluserstr='';
4172: foreach (sort keys %allusers) {
4173: $alluserstr.=$_.'&user:';
4174: }
4175: $alluserstr=~s/:$//;
4176: return split(/:/,$alluserstr);
4177: } else {
4178: my @emptyResults = ();
4179: push(@emptyResults, 'missing user name');
4180: return split(':',@emptyResults);
4181: }
4182: } elsif(!defined($alternateDirectoryRoot)) {
4183: my $tryserver;
4184: my %alldom=();
4185: foreach $tryserver (keys %libserv) {
4186: $alldom{$hostdom{$tryserver}}=1;
4187: }
4188: my $alldomstr='';
4189: foreach (sort keys %alldom) {
1.397 albertel 4190: $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253 stredwic 4191: }
4192: $alldomstr=~s/:$//;
4193: return split(/:/,$alldomstr);
4194: } else {
4195: my @emptyResults = ();
4196: push(@emptyResults, 'missing domain');
4197: return split(':',@emptyResults);
1.275 stredwic 4198: }
4199: }
4200:
4201: # --------------------------------------------- GetFileTimestamp
4202: # This function utilizes dirlist and returns the date stamp for
4203: # when it was last modified. It will also return an error of -1
4204: # if an error occurs
4205:
1.410 matthew 4206: ##
4207: ## FIXME: This subroutine assumes its caller knows something about the
4208: ## directory structure of the home server for the student ($root).
4209: ## Not a good assumption to make. Since this is for looking up files
4210: ## in user directories, the full path should be constructed by lond, not
4211: ## whatever machine we request data from.
4212: ##
1.275 stredwic 4213: sub GetFileTimestamp {
4214: my ($studentDomain,$studentName,$filename,$root)=@_;
4215: $studentDomain=~s/\W//g;
4216: $studentName=~s/\W//g;
4217: my $subdir=$studentName.'__';
4218: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
4219: my $proname="$studentDomain/$subdir/$studentName";
4220: $proname .= '/'.$filename;
1.375 matthew 4221: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
4222: $studentName, $root);
1.275 stredwic 4223: my @stats = split('&', $fileStat);
4224: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 4225: # @stats contains first the filename, then the stat output
4226: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 4227: } else {
4228: return -1;
1.253 stredwic 4229: }
1.26 www 4230: }
4231:
4232: # -------------------------------------------------------- Value of a Condition
4233:
1.40 www 4234: sub directcondval {
4235: my $number=shift;
1.620 albertel 4236: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 4237: &Apache::lonuserstate::evalstate();
4238: }
1.620 albertel 4239: if ($env{'user.state.'.$env{'request.course.id'}}) {
4240: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 4241: } else {
4242: return 2;
4243: }
4244: }
4245:
1.26 www 4246: sub condval {
4247: my $condidx=shift;
4248: my $result=0;
1.54 www 4249: my $allpathcond='';
1.191 harris41 4250: foreach (split(/\|/,$condidx)) {
1.620 albertel 4251: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$_})) {
1.54 www 4252: $allpathcond.=
1.620 albertel 4253: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$_}.')|';
1.54 www 4254: }
1.191 harris41 4255: }
1.54 www 4256: $allpathcond=~s/\|$//;
1.620 albertel 4257: if ($env{'request.course.id'}) {
1.54 www 4258: if ($allpathcond) {
1.26 www 4259: my $operand='|';
4260: my @stack;
1.191 harris41 4261: foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
1.26 www 4262: if ($_ eq '(') {
4263: push @stack,($operand,$result)
4264: } elsif ($_ eq ')') {
4265: my $before=pop @stack;
4266: if (pop @stack eq '&') {
4267: $result=$result>$before?$before:$result;
4268: } else {
4269: $result=$result>$before?$result:$before;
4270: }
4271: } elsif (($_ eq '&') || ($_ eq '|')) {
4272: $operand=$_;
4273: } else {
1.40 www 4274: my $new=directcondval($_);
1.26 www 4275: if ($operand eq '&') {
4276: $result=$result>$new?$new:$result;
4277: } else {
4278: $result=$result>$new?$result:$new;
1.191 harris41 4279: }
1.26 www 4280: }
1.191 harris41 4281: }
1.26 www 4282: }
4283: }
4284: return $result;
1.421 albertel 4285: }
4286:
4287: # ---------------------------------------------------- Devalidate courseresdata
4288:
4289: sub devalidatecourseresdata {
4290: my ($coursenum,$coursedomain)=@_;
4291: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 4292: &devalidate_cache_new('courseres',$hashid);
1.28 www 4293: }
4294:
1.200 www 4295: # --------------------------------------------------- Course Resourcedata Query
4296:
1.624 albertel 4297: sub get_courseresdata {
4298: my ($coursenum,$coursedomain)=@_;
1.200 www 4299: my $coursehom=&homeserver($coursenum,$coursedomain);
4300: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 4301: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 4302: my %dumpreply;
1.417 albertel 4303: unless (defined($cached)) {
1.624 albertel 4304: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 4305: $result=\%dumpreply;
1.251 albertel 4306: my ($tmp) = keys(%dumpreply);
4307: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 4308: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 4309: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
4310: return $tmp;
1.416 albertel 4311: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 4312: $result=undef;
1.599 albertel 4313: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 4314: }
4315: }
1.624 albertel 4316: return $result;
4317: }
4318:
1.633 albertel 4319: sub devalidateuserresdata {
4320: my ($uname,$udom)=@_;
4321: my $hashid="$udom:$uname";
4322: &devalidate_cache_new('userres',$hashid);
4323: }
4324:
1.624 albertel 4325: sub get_userresdata {
4326: my ($uname,$udom)=@_;
4327: #most student don\'t have any data set, check if there is some data
4328: if (&EXT_cache_status($udom,$uname)) { return undef; }
4329:
4330: my $hashid="$udom:$uname";
4331: my ($result,$cached)=&is_cached_new('userres',$hashid);
4332: if (!defined($cached)) {
4333: my %resourcedata=&dump('resourcedata',$udom,$uname);
4334: $result=\%resourcedata;
4335: &do_cache_new('userres',$hashid,$result,600);
4336: }
4337: my ($tmp)=keys(%$result);
4338: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
4339: return $result;
4340: }
4341: #error 2 occurs when the .db doesn't exist
4342: if ($tmp!~/error: 2 /) {
4343: &logthis("<font color=blue>WARNING:".
4344: " Trying to get resource data for ".
4345: $uname." at ".$udom.": ".
4346: $tmp."</font>");
4347: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 4348: #&EXT_cache_set($udom,$uname);
4349: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 4350: undef($tmp); # not really an error so don't send it back
1.624 albertel 4351: }
4352: return $tmp;
4353: }
4354:
4355: sub resdata {
4356: my ($name,$domain,$type,@which)=@_;
4357: my $result;
4358: if ($type eq 'course') {
4359: $result=&get_courseresdata($name,$domain);
4360: } elsif ($type eq 'user') {
4361: $result=&get_userresdata($name,$domain);
4362: }
4363: if (!ref($result)) { return $result; }
1.251 albertel 4364: foreach my $item (@which) {
1.417 albertel 4365: if (defined($result->{$item})) {
4366: return $result->{$item};
1.251 albertel 4367: }
1.250 albertel 4368: }
1.291 albertel 4369: return undef;
1.200 www 4370: }
4371:
1.379 matthew 4372: #
4373: # EXT resource caching routines
4374: #
4375:
4376: sub clear_EXT_cache_status {
1.383 albertel 4377: &delenv('cache.EXT.');
1.379 matthew 4378: }
4379:
4380: sub EXT_cache_status {
4381: my ($target_domain,$target_user) = @_;
1.383 albertel 4382: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 4383: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 4384: # We know already the user has no data
4385: return 1;
4386: } else {
4387: return 0;
4388: }
4389: }
4390:
4391: sub EXT_cache_set {
4392: my ($target_domain,$target_user) = @_;
1.383 albertel 4393: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633 albertel 4394: #&appenv($cachename => time);
1.379 matthew 4395: }
4396:
1.28 www 4397: # --------------------------------------------------------- Value of a Variable
1.58 www 4398: sub EXT {
1.395 albertel 4399: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.218 albertel 4400:
1.68 www 4401: unless ($varname) { return ''; }
1.218 albertel 4402: #get real user name/domain, courseid and symb
4403: my $courseid;
1.359 albertel 4404: my $publicuser;
1.427 www 4405: if ($symbparm) {
4406: $symbparm=&get_symb_from_alias($symbparm);
4407: }
1.218 albertel 4408: if (!($uname && $udom)) {
1.360 albertel 4409: (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378 matthew 4410: &Apache::lonxml::whichuser($symbparm);
1.218 albertel 4411: if (!$symbparm) { $symbparm=$cursymb; }
4412: } else {
1.620 albertel 4413: $courseid=$env{'request.course.id'};
1.218 albertel 4414: }
1.48 www 4415: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
4416: my $rest;
1.320 albertel 4417: if (defined($therest[0])) {
1.48 www 4418: $rest=join('.',@therest);
4419: } else {
4420: $rest='';
4421: }
1.320 albertel 4422:
1.57 www 4423: my $qualifierrest=$qualifier;
4424: if ($rest) { $qualifierrest.='.'.$rest; }
4425: my $spacequalifierrest=$space;
4426: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 4427: if ($realm eq 'user') {
1.48 www 4428: # --------------------------------------------------------------- user.resource
4429: if ($space eq 'resource') {
1.618 albertel 4430: if (defined($Apache::lonhomework::parsing_a_problem) ||
4431: defined($Apache::lonhomework::parsing_a_task)) {
1.335 albertel 4432: return $Apache::lonhomework::history{$qualifierrest};
4433: } else {
1.359 albertel 4434: my %restored;
1.620 albertel 4435: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 4436: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
4437: } else {
4438: %restored=&restore($symbparm,$courseid,$udom,$uname);
4439: }
1.335 albertel 4440: return $restored{$qualifierrest};
4441: }
1.48 www 4442: # ----------------------------------------------------------------- user.access
4443: } elsif ($space eq 'access') {
1.218 albertel 4444: # FIXME - not supporting calls for a specific user
1.48 www 4445: return &allowed($qualifier,$rest);
4446: # ------------------------------------------ user.preferences, user.environment
4447: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 4448: if (($uname eq $env{'user.name'}) &&
4449: ($udom eq $env{'user.domain'})) {
4450: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 4451: } else {
1.359 albertel 4452: my %returnhash;
4453: if (!$publicuser) {
4454: %returnhash=&userenvironment($udom,$uname,
4455: $qualifierrest);
4456: }
1.218 albertel 4457: return $returnhash{$qualifierrest};
4458: }
1.48 www 4459: # ----------------------------------------------------------------- user.course
4460: } elsif ($space eq 'course') {
1.218 albertel 4461: # FIXME - not supporting calls for a specific user
1.620 albertel 4462: return $env{join('.',('request.course',$qualifier))};
1.48 www 4463: # ------------------------------------------------------------------- user.role
4464: } elsif ($space eq 'role') {
1.218 albertel 4465: # FIXME - not supporting calls for a specific user
1.620 albertel 4466: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 4467: if ($qualifier eq 'value') {
4468: return $role;
4469: } elsif ($qualifier eq 'extent') {
4470: return $where;
4471: }
4472: # ----------------------------------------------------------------- user.domain
4473: } elsif ($space eq 'domain') {
1.218 albertel 4474: return $udom;
1.48 www 4475: # ------------------------------------------------------------------- user.name
4476: } elsif ($space eq 'name') {
1.218 albertel 4477: return $uname;
1.48 www 4478: # ---------------------------------------------------- Any other user namespace
1.29 www 4479: } else {
1.359 albertel 4480: my %reply;
4481: if (!$publicuser) {
4482: %reply=&get($space,[$qualifierrest],$udom,$uname);
4483: }
4484: return $reply{$qualifierrest};
1.48 www 4485: }
1.236 www 4486: } elsif ($realm eq 'query') {
4487: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 4488: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
4489: [$spacequalifierrest]);
1.620 albertel 4490: return $env{'form.'.$spacequalifierrest};
1.236 www 4491: } elsif ($realm eq 'request') {
1.48 www 4492: # ------------------------------------------------------------- request.browser
4493: if ($space eq 'browser') {
1.430 www 4494: if ($qualifier eq 'textremote') {
4495: if (&mt('textual_remote_display') eq 'on') {
4496: return 1;
4497: } else {
4498: return 0;
4499: }
4500: } else {
1.620 albertel 4501: return $env{'browser.'.$qualifier};
1.430 www 4502: }
1.57 www 4503: # ------------------------------------------------------------ request.filename
4504: } else {
1.620 albertel 4505: return $env{'request.'.$spacequalifierrest};
1.29 www 4506: }
1.28 www 4507: } elsif ($realm eq 'course') {
1.48 www 4508: # ---------------------------------------------------------- course.description
1.620 albertel 4509: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 4510: } elsif ($realm eq 'resource') {
1.165 www 4511:
1.395 albertel 4512: my $section;
1.620 albertel 4513: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 4514: if (!$symbparm) { $symbparm=&symbread(); }
4515: }
1.593 albertel 4516: my ($courselevelm,$courselevel);
1.539 albertel 4517: if ($symbparm && defined($courseid) &&
1.620 albertel 4518: $courseid eq $env{'request.course.id'}) {
1.165 www 4519:
1.218 albertel 4520: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 4521:
1.60 www 4522: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 4523: my $symbp=$symbparm;
1.409 www 4524: my $mapp=(&decode_symb($symbp))[0];
1.218 albertel 4525:
4526: my $symbparm=$symbp.'.'.$spacequalifierrest;
4527: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
4528:
1.620 albertel 4529: if (($env{'user.name'} eq $uname) &&
4530: ($env{'user.domain'} eq $udom)) {
4531: $section=$env{'request.course.sec'};
1.218 albertel 4532: } else {
1.539 albertel 4533: if (! defined($usection)) {
1.551 albertel 4534: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 4535: } else {
4536: $section = $usection;
4537: }
1.218 albertel 4538: }
4539:
4540: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
4541: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
4542: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
4543:
1.593 albertel 4544: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 4545: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 4546: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 4547:
1.60 www 4548: # ----------------------------------------------------------- first, check user
1.624 albertel 4549:
4550: my $userreply=&resdata($uname,$udom,'user',
4551: ($courselevelr,$courselevelm,
4552: $courselevel));
4553:
4554: if (defined($userreply)) { return $userreply; }
1.95 www 4555:
1.594 albertel 4556: # ------------------------------------------------ second, check some of course
1.96 www 4557:
1.624 albertel 4558: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
4559: $env{'course.'.$courseid.'.domain'},
4560: 'course',
4561: ($seclevelr,$seclevelm,$seclevel,
4562: $courselevelr));
1.287 albertel 4563: if (defined($coursereply)) { return $coursereply; }
1.200 www 4564:
1.60 www 4565: # ------------------------------------------------------ third, check map parms
1.218 albertel 4566: my %parmhash=();
4567: my $thisparm='';
4568: if (tie(%parmhash,'GDBM_File',
1.620 albertel 4569: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 4570: &GDBM_READER(),0640)) {
1.218 albertel 4571: $thisparm=$parmhash{$symbparm};
4572: untie(%parmhash);
4573: }
4574: if ($thisparm) { return $thisparm; }
4575: }
1.594 albertel 4576: # ------------------------------------------ fourth, look in resource metadata
1.71 www 4577:
1.218 albertel 4578: $spacequalifierrest=~s/\./\_/;
1.282 albertel 4579: my $filename;
4580: if (!$symbparm) { $symbparm=&symbread(); }
4581: if ($symbparm) {
1.409 www 4582: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 4583: } else {
1.620 albertel 4584: $filename=$env{'request.filename'};
1.282 albertel 4585: }
4586: my $metadata=&metadata($filename,$spacequalifierrest);
1.288 albertel 4587: if (defined($metadata)) { return $metadata; }
1.282 albertel 4588: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288 albertel 4589: if (defined($metadata)) { return $metadata; }
1.142 www 4590:
1.594 albertel 4591: # ---------------------------------------------- fourth, look in rest pf course
1.593 albertel 4592: if ($symbparm && defined($courseid) &&
1.620 albertel 4593: $courseid eq $env{'request.course.id'}) {
1.624 albertel 4594: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
4595: $env{'course.'.$courseid.'.domain'},
4596: 'course',
4597: ($courselevelm,$courselevel));
1.593 albertel 4598: if (defined($coursereply)) { return $coursereply; }
4599: }
1.145 www 4600: # ------------------------------------------------------------------ Cascade up
1.218 albertel 4601: unless ($space eq '0') {
1.336 albertel 4602: my @parts=split(/_/,$space);
4603: my $id=pop(@parts);
4604: my $part=join('_',@parts);
4605: if ($part eq '') { $part='0'; }
4606: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 4607: $symbparm,$udom,$uname,$section,1);
1.337 albertel 4608: if (defined($partgeneral)) { return $partgeneral; }
1.218 albertel 4609: }
1.395 albertel 4610: if ($recurse) { return undef; }
4611: my $pack_def=&packages_tab_default($filename,$varname);
4612: if (defined($pack_def)) { return $pack_def; }
1.71 www 4613:
1.48 www 4614: # ---------------------------------------------------- Any other user namespace
4615: } elsif ($realm eq 'environment') {
4616: # ----------------------------------------------------------------- environment
1.620 albertel 4617: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
4618: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 4619: } else {
4620: my %returnhash=&userenvironment($udom,$uname,
4621: $spacequalifierrest);
4622: return $returnhash{$spacequalifierrest};
4623: }
1.28 www 4624: } elsif ($realm eq 'system') {
1.48 www 4625: # ----------------------------------------------------------------- system.time
4626: if ($space eq 'time') {
4627: return time;
4628: }
1.28 www 4629: }
1.48 www 4630: return '';
1.61 www 4631: }
4632:
1.395 albertel 4633: sub packages_tab_default {
4634: my ($uri,$varname)=@_;
4635: my (undef,$part,$name)=split(/\./,$varname);
4636: my $packages=&metadata($uri,'packages');
4637: foreach my $package (split(/,/,$packages)) {
4638: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.468 albertel 4639: if (defined($packagetab{"$pack_type&$name&default"})) {
4640: return $packagetab{"$pack_type&$name&default"};
4641: }
1.585 albertel 4642: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 4643: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
4644: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 4645: }
4646: }
4647: return undef;
4648: }
4649:
1.334 albertel 4650: sub add_prefix_and_part {
4651: my ($prefix,$part)=@_;
4652: my $keyroot;
4653: if (defined($prefix) && $prefix !~ /^__/) {
4654: # prefix that has a part already
4655: $keyroot=$prefix;
4656: } elsif (defined($prefix)) {
4657: # prefix that is missing a part
4658: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
4659: } else {
4660: # no prefix at all
4661: if (defined($part)) { $keyroot='_'.$part; }
4662: }
4663: return $keyroot;
4664: }
4665:
1.71 www 4666: # ---------------------------------------------------------------- Get metadata
4667:
1.599 albertel 4668: my %metaentry;
1.71 www 4669: sub metadata {
1.176 www 4670: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 4671: $uri=&declutter($uri);
1.288 albertel 4672: # if it is a non metadata possible uri return quickly
1.529 albertel 4673: if (($uri eq '') ||
4674: (($uri =~ m|^/*adm/|) &&
4675: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423 albertel 4676: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489 albertel 4677: ($uri =~ m|home/[^/]+/public_html/|)) {
1.468 albertel 4678: return undef;
1.288 albertel 4679: }
1.73 www 4680: my $filename=$uri;
4681: $uri=~s/\.meta$//;
1.172 www 4682: #
4683: # Is the metadata already cached?
1.177 www 4684: # Look at timestamp of caching
1.172 www 4685: # Everything is cached by the main uri, libraries are never directly cached
4686: #
1.428 albertel 4687: if (!defined($liburi)) {
1.599 albertel 4688: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 4689: if (defined($cached)) { return $result->{':'.$what}; }
4690: }
4691: {
1.172 www 4692: #
4693: # Is this a recursive call for a library?
4694: #
1.599 albertel 4695: # if (! exists($metacache{$uri})) {
4696: # $metacache{$uri}={};
4697: # }
1.171 www 4698: if ($liburi) {
4699: $liburi=&declutter($liburi);
4700: $filename=$liburi;
1.401 bowersj2 4701: } else {
1.599 albertel 4702: &devalidate_cache_new('meta',$uri);
4703: undef(%metaentry);
1.401 bowersj2 4704: }
1.140 www 4705: my %metathesekeys=();
1.73 www 4706: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 4707: my $metastring;
1.609 banghart 4708: if ($uri !~ m -^(uploaded|editupload)/-) {
1.543 albertel 4709: my $file=&filelocation('',&clutter($filename));
1.599 albertel 4710: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 4711: $metastring=&getfile($file);
1.489 albertel 4712: }
1.208 albertel 4713: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 4714: my $token;
1.140 www 4715: undef %metathesekeys;
1.71 www 4716: while ($token=$parser->get_token) {
1.339 albertel 4717: if ($token->[0] eq 'S') {
4718: if (defined($token->[2]->{'package'})) {
1.172 www 4719: #
4720: # This is a package - get package info
4721: #
1.339 albertel 4722: my $package=$token->[2]->{'package'};
4723: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
4724: if (defined($token->[2]->{'id'})) {
4725: $keyroot.='_'.$token->[2]->{'id'};
4726: }
1.599 albertel 4727: if ($metaentry{':packages'}) {
4728: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 4729: } else {
1.599 albertel 4730: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 4731: }
1.613 albertel 4732: foreach (sort keys %packagetab) {
1.432 albertel 4733: my $part=$keyroot;
4734: $part=~s/^\_//;
4735: if ($_=~/^\Q$package\E\&/ ||
4736: $_=~/^\Q$package\E_0\&/) {
1.339 albertel 4737: my ($pack,$name,$subp)=split(/\&/,$_);
1.395 albertel 4738: # ignore package.tab specified default values
4739: # here &package_tab_default() will fetch those
4740: if ($subp eq 'default') { next; }
1.339 albertel 4741: my $value=$packagetab{$_};
1.432 albertel 4742: my $unikey;
4743: if ($pack =~ /_0$/) {
4744: $unikey='parameter_0_'.$name;
4745: $part=0;
4746: } else {
4747: $unikey='parameter'.$keyroot.'_'.$name;
4748: }
1.339 albertel 4749: if ($subp eq 'display') {
4750: $value.=' [Part: '.$part.']';
4751: }
1.599 albertel 4752: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 4753: $metathesekeys{$unikey}=1;
1.599 albertel 4754: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
4755: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 4756: }
1.599 albertel 4757: if (defined($metaentry{':'.$unikey.'.default'})) {
4758: $metaentry{':'.$unikey}=
4759: $metaentry{':'.$unikey.'.default'};
1.356 albertel 4760: }
1.339 albertel 4761: }
4762: }
4763: } else {
1.172 www 4764: #
4765: # This is not a package - some other kind of start tag
1.339 albertel 4766: #
4767: my $entry=$token->[1];
4768: my $unikey;
4769: if ($entry eq 'import') {
4770: $unikey='';
4771: } else {
4772: $unikey=$entry;
4773: }
4774: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
4775:
4776: if (defined($token->[2]->{'id'})) {
4777: $unikey.='_'.$token->[2]->{'id'};
4778: }
1.175 www 4779:
1.339 albertel 4780: if ($entry eq 'import') {
1.175 www 4781: #
4782: # Importing a library here
1.339 albertel 4783: #
4784: if ($depthcount<20) {
4785: my $location=$parser->get_text('/import');
4786: my $dir=$filename;
4787: $dir=~s|[^/]*$||;
4788: $location=&filelocation($dir,$location);
4789: foreach (sort(split(/\,/,&metadata($uri,'keys',
4790: $location,$unikey,
4791: $depthcount+1)))) {
1.599 albertel 4792: $metaentry{':'.$_}=$metaentry{':'.$_};
1.339 albertel 4793: $metathesekeys{$_}=1;
4794: }
4795: }
4796: } else {
4797:
4798: if (defined($token->[2]->{'name'})) {
4799: $unikey.='_'.$token->[2]->{'name'};
4800: }
4801: $metathesekeys{$unikey}=1;
4802: foreach (@{$token->[3]}) {
1.599 albertel 4803: $metaentry{':'.$unikey.'.'.$_}=$token->[2]->{$_};
1.339 albertel 4804: }
4805: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 4806: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 4807: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
4808: # only ws inside the tag, and not in default, so use default
4809: # as value
1.599 albertel 4810: $metaentry{':'.$unikey}=$default;
1.339 albertel 4811: } else {
1.321 albertel 4812: # either something interesting inside the tag or default
4813: # uninteresting
1.599 albertel 4814: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 4815: }
1.172 www 4816: # end of not-a-package not-a-library import
1.339 albertel 4817: }
1.172 www 4818: # end of not-a-package start tag
1.339 albertel 4819: }
1.172 www 4820: # the next is the end of "start tag"
1.339 albertel 4821: }
4822: }
1.483 albertel 4823: my ($extension) = ($uri =~ /\.(\w+)$/);
4824: foreach my $key (sort(keys(%packagetab))) {
4825: #no specific packages #how's our extension
4826: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 4827: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 4828: \%metathesekeys);
4829: }
1.599 albertel 4830: if (!exists($metaentry{':packages'})) {
1.483 albertel 4831: foreach my $key (sort(keys(%packagetab))) {
4832: #no specific packages well let's get default then
4833: if ($key!~/^default&/) { next; }
1.488 albertel 4834: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 4835: \%metathesekeys);
4836: }
4837: }
1.338 www 4838: # are there custom rights to evaluate
1.599 albertel 4839: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 4840:
1.338 www 4841: #
4842: # Importing a rights file here
1.339 albertel 4843: #
4844: unless ($depthcount) {
1.599 albertel 4845: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 4846: my $dir=$filename;
4847: $dir=~s|[^/]*$||;
4848: $location=&filelocation($dir,$location);
4849: foreach (sort(split(/\,/,&metadata($uri,'keys',
4850: $location,'_rights',
4851: $depthcount+1)))) {
1.599 albertel 4852: #$metaentry{':'.$_}=$metacache{$uri}->{':'.$_};
1.339 albertel 4853: $metathesekeys{$_}=1;
4854: }
4855: }
4856: }
1.599 albertel 4857: $metaentry{':keys'}=join(',',keys %metathesekeys);
4858: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
4859: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.623 albertel 4860: &do_cache_new('meta',$uri,\%metaentry,60*60*24);
1.177 www 4861: # this is the end of "was not already recently cached
1.71 www 4862: }
1.599 albertel 4863: return $metaentry{':'.$what};
1.261 albertel 4864: }
4865:
1.488 albertel 4866: sub metadata_create_package_def {
1.483 albertel 4867: my ($uri,$key,$package,$metathesekeys)=@_;
4868: my ($pack,$name,$subp)=split(/\&/,$key);
4869: if ($subp eq 'default') { next; }
4870:
1.599 albertel 4871: if (defined($metaentry{':packages'})) {
4872: $metaentry{':packages'}.=','.$package;
1.483 albertel 4873: } else {
1.599 albertel 4874: $metaentry{':packages'}=$package;
1.483 albertel 4875: }
4876: my $value=$packagetab{$key};
4877: my $unikey;
4878: $unikey='parameter_0_'.$name;
1.599 albertel 4879: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 4880: $$metathesekeys{$unikey}=1;
1.599 albertel 4881: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
4882: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 4883: }
1.599 albertel 4884: if (defined($metaentry{':'.$unikey.'.default'})) {
4885: $metaentry{':'.$unikey}=
4886: $metaentry{':'.$unikey.'.default'};
1.483 albertel 4887: }
4888: }
4889:
1.261 albertel 4890: sub metadata_generate_part0 {
4891: my ($metadata,$metacache,$uri) = @_;
4892: my %allnames;
4893: foreach my $metakey (sort keys %$metadata) {
4894: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 4895: my $part=$$metacache{':'.$metakey.'.part'};
4896: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 4897: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 4898: $allnames{$name}=$part;
4899: }
4900: }
4901: }
4902: foreach my $name (keys(%allnames)) {
4903: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 4904: my $key=":parameter_0_$name";
1.261 albertel 4905: $$metacache{"$key.part"}='0';
4906: $$metacache{"$key.name"}=$name;
1.428 albertel 4907: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 4908: $allnames{$name}.'_'.$name.
4909: '.type'};
1.428 albertel 4910: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 4911: '.display'};
4912: my $expr='\\[Part: '.$allnames{$name}.'\\]';
1.479 albertel 4913: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 4914: $$metacache{"$key.display"}=$olddis;
4915: }
1.71 www 4916: }
4917:
1.301 www 4918: # ------------------------------------------------- Get the title of a resource
4919:
4920: sub gettitle {
4921: my $urlsymb=shift;
4922: my $symb=&symbread($urlsymb);
1.534 albertel 4923: if ($symb) {
1.620 albertel 4924: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 4925: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 4926: if (defined($cached)) {
4927: return $result;
4928: }
1.534 albertel 4929: my ($map,$resid,$url)=&decode_symb($symb);
4930: my $title='';
4931: my %bighash;
1.620 albertel 4932: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534 albertel 4933: &GDBM_READER(),0640)) {
4934: my $mapid=$bighash{'map_pc_'.&clutter($map)};
4935: $title=$bighash{'title_'.$mapid.'.'.$resid};
4936: untie %bighash;
4937: }
4938: $title=~s/\&colon\;/\:/gs;
4939: if ($title) {
1.599 albertel 4940: return &do_cache_new('title',$key,$title,600);
1.534 albertel 4941: }
4942: $urlsymb=$url;
4943: }
4944: my $title=&metadata($urlsymb,'title');
4945: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
4946: return $title;
1.301 www 4947: }
1.613 albertel 4948:
1.614 albertel 4949: sub get_slot {
4950: my ($which,$cnum,$cdom)=@_;
4951: if (!$cnum || !$cdom) {
4952: (undef,my $courseid)=&Apache::lonxml::whichuser();
1.620 albertel 4953: $cdom=$env{'course.'.$courseid.'.domain'};
4954: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 4955: }
4956: my %slotinfo=&get('slots',[$which],$cdom,$cnum);
4957: &Apache::lonhomework::showhash(%slotinfo);
4958: my ($tmp)=keys(%slotinfo);
4959: if ($tmp=~/^error:/) { return (); }
1.616 albertel 4960: if (ref($slotinfo{$which}) eq 'HASH') {
4961: return %{$slotinfo{$which}};
4962: }
4963: return $slotinfo{$which};
1.614 albertel 4964: }
1.31 www 4965: # ------------------------------------------------- Update symbolic store links
4966:
4967: sub symblist {
4968: my ($mapname,%newhash)=@_;
1.438 www 4969: $mapname=&deversion(&declutter($mapname));
1.31 www 4970: my %hash;
1.620 albertel 4971: if (($env{'request.course.fn'}) && (%newhash)) {
4972: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 4973: &GDBM_WRCREAT(),0640)) {
1.191 harris41 4974: foreach (keys %newhash) {
1.601 albertel 4975: $hash{declutter($_)}=&encode_symb($mapname,$newhash{$_}->[1],
4976: $newhash{$_}->[0]);
1.191 harris41 4977: }
1.31 www 4978: if (untie(%hash)) {
4979: return 'ok';
4980: }
4981: }
4982: }
4983: return 'error';
1.212 www 4984: }
4985:
4986: # --------------------------------------------------------------- Verify a symb
4987:
4988: sub symbverify {
1.510 www 4989: my ($symb,$thisurl)=@_;
4990: my $thisfn=$thisurl;
4991: # wrapper not part of symbs
4992: $thisfn=~s/^\/adm\/wrapper//;
1.439 www 4993: $thisfn=&declutter($thisfn);
1.215 www 4994: # direct jump to resource in page or to a sequence - will construct own symbs
4995: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
4996: # check URL part
1.409 www 4997: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 4998:
1.431 www 4999: unless ($url eq $thisfn) { return 0; }
1.213 www 5000:
1.216 www 5001: $symb=&symbclean($symb);
1.510 www 5002: $thisurl=&deversion($thisurl);
1.439 www 5003: $thisfn=&deversion($thisfn);
1.213 www 5004:
5005: my %bighash;
5006: my $okay=0;
1.431 www 5007:
1.620 albertel 5008: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 5009: &GDBM_READER(),0640)) {
1.510 www 5010: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 5011: unless ($ids) {
1.510 www 5012: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 5013: }
5014: if ($ids) {
5015: # ------------------------------------------------------------------- Has ID(s)
5016: foreach (split(/\,/,$ids)) {
5017: my ($mapid,$resid)=split(/\./,$_);
5018: if (
5019: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
5020: eq $symb) {
1.620 albertel 5021: if (($env{'request.role.adv'}) ||
5022: $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582 albertel 5023: $okay=1;
5024: }
5025: }
1.216 www 5026: }
5027: }
1.213 www 5028: untie(%bighash);
5029: }
5030: return $okay;
1.31 www 5031: }
5032:
1.210 www 5033: # --------------------------------------------------------------- Clean-up symb
5034:
5035: sub symbclean {
5036: my $symb=shift;
1.568 albertel 5037: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 5038: # remove version from map
5039: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 5040:
1.210 www 5041: # remove version from URL
5042: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 5043:
1.507 www 5044: # remove wrapper
5045:
1.510 www 5046: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.210 www 5047: return $symb;
1.409 www 5048: }
5049:
5050: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 5051:
5052: sub encode_symb {
5053: my ($map,$resid,$url)=@_;
5054: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
5055: }
1.409 www 5056:
5057: sub decode_symb {
1.568 albertel 5058: my $symb=shift;
5059: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
5060: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 5061: return (&fixversion($map),$resid,&fixversion($url));
5062: }
5063:
5064: sub fixversion {
5065: my $fn=shift;
1.609 banghart 5066: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 5067: my %bighash;
5068: my $uri=&clutter($fn);
1.620 albertel 5069: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 5070: # is this cached?
1.599 albertel 5071: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 5072: if (defined($cached)) { return $result; }
5073: # unfortunately not cached, or expired
1.620 albertel 5074: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 5075: &GDBM_READER(),0640)) {
5076: if ($bighash{'version_'.$uri}) {
5077: my $version=$bighash{'version_'.$uri};
1.444 www 5078: unless (($version eq 'mostrecent') ||
5079: ($version==&getversion($uri))) {
1.440 www 5080: $uri=~s/\.(\w+)$/\.$version\.$1/;
5081: }
5082: }
5083: untie %bighash;
1.413 www 5084: }
1.599 albertel 5085: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 5086: }
5087:
5088: sub deversion {
5089: my $url=shift;
5090: $url=~s/\.\d+\.(\w+)$/\.$1/;
5091: return $url;
1.210 www 5092: }
5093:
1.31 www 5094: # ------------------------------------------------------ Return symb list entry
5095:
5096: sub symbread {
1.249 www 5097: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 5098: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 5099: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 5100: # no filename provided? try from environment
1.44 www 5101: unless ($thisfn) {
1.620 albertel 5102: if ($env{'request.symb'}) {
5103: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 5104: }
1.620 albertel 5105: $thisfn=$env{'request.filename'};
1.44 www 5106: }
1.569 albertel 5107: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 5108: # is that filename actually a symb? Verify, clean, and return
5109: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 5110: if (&symbverify($thisfn,$1)) {
1.620 albertel 5111: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 5112: }
1.242 www 5113: }
1.44 www 5114: $thisfn=declutter($thisfn);
1.31 www 5115: my %hash;
1.37 www 5116: my %bighash;
5117: my $syval='';
1.620 albertel 5118: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 5119: my $targetfn = $thisfn;
1.609 banghart 5120: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 5121: $targetfn = 'adm/wrapper/'.$thisfn;
5122: }
1.620 albertel 5123: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 5124: &GDBM_READER(),0640)) {
1.481 raeburn 5125: $syval=$hash{$targetfn};
1.37 www 5126: untie(%hash);
5127: }
5128: # ---------------------------------------------------------- There was an entry
5129: if ($syval) {
1.601 albertel 5130: #unless ($syval=~/\_\d+$/) {
1.620 albertel 5131: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601 albertel 5132: #&appenv('request.ambiguous' => $thisfn);
1.620 albertel 5133: #return $env{$cache_str}='';
1.601 albertel 5134: #}
5135: #$syval.=$1;
5136: #}
1.37 www 5137: } else {
5138: # ------------------------------------------------------- Was not in symb table
1.620 albertel 5139: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 5140: &GDBM_READER(),0640)) {
1.37 www 5141: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 5142: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 5143: unless ($ids) {
5144: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 5145: }
5146: unless ($ids) {
5147: # alias?
5148: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 5149: }
1.37 www 5150: if ($ids) {
5151: # ------------------------------------------------------------------- Has ID(s)
5152: my @possibilities=split(/\,/,$ids);
1.39 www 5153: if ($#possibilities==0) {
5154: # ----------------------------------------------- There is only one possibility
1.37 www 5155: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 5156: $syval=&encode_symb($bighash{'map_id_'.$mapid},
5157: $resid,$thisfn);
1.249 www 5158: } elsif (!$donotrecurse) {
1.39 www 5159: # ------------------------------------------ There is more than one possibility
5160: my $realpossible=0;
1.191 harris41 5161: foreach (@possibilities) {
1.39 www 5162: my $file=$bighash{'src_'.$_};
5163: if (&allowed('bre',$file)) {
5164: my ($mapid,$resid)=split(/\./,$_);
5165: if ($bighash{'map_type_'.$mapid} ne 'page') {
5166: $realpossible++;
1.626 albertel 5167: $syval=&encode_symb($bighash{'map_id_'.$mapid},
5168: $resid,$thisfn);
1.39 www 5169: }
5170: }
1.191 harris41 5171: }
1.39 www 5172: if ($realpossible!=1) { $syval=''; }
1.249 www 5173: } else {
5174: $syval='';
1.37 www 5175: }
5176: }
5177: untie(%bighash)
1.481 raeburn 5178: }
1.31 www 5179: }
1.62 www 5180: if ($syval) {
1.620 albertel 5181: return $env{$cache_str}=$syval;
1.62 www 5182: }
1.31 www 5183: }
1.44 www 5184: &appenv('request.ambiguous' => $thisfn);
1.620 albertel 5185: return $env{$cache_str}='';
1.31 www 5186: }
5187:
5188: # ---------------------------------------------------------- Return random seed
5189:
1.32 www 5190: sub numval {
5191: my $txt=shift;
5192: $txt=~tr/A-J/0-9/;
5193: $txt=~tr/a-j/0-9/;
5194: $txt=~tr/K-T/0-9/;
5195: $txt=~tr/k-t/0-9/;
5196: $txt=~tr/U-Z/0-5/;
5197: $txt=~tr/u-z/0-5/;
5198: $txt=~s/\D//g;
1.564 albertel 5199: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 5200: return int($txt);
1.368 albertel 5201: }
5202:
1.484 albertel 5203: sub numval2 {
5204: my $txt=shift;
5205: $txt=~tr/A-J/0-9/;
5206: $txt=~tr/a-j/0-9/;
5207: $txt=~tr/K-T/0-9/;
5208: $txt=~tr/k-t/0-9/;
5209: $txt=~tr/U-Z/0-5/;
5210: $txt=~tr/u-z/0-5/;
5211: $txt=~s/\D//g;
5212: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
5213: my $total;
5214: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 5215: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 5216: return int($total);
5217: }
5218:
1.575 albertel 5219: sub numval3 {
5220: use integer;
5221: my $txt=shift;
5222: $txt=~tr/A-J/0-9/;
5223: $txt=~tr/a-j/0-9/;
5224: $txt=~tr/K-T/0-9/;
5225: $txt=~tr/k-t/0-9/;
5226: $txt=~tr/U-Z/0-5/;
5227: $txt=~tr/u-z/0-5/;
5228: $txt=~s/\D//g;
5229: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
5230: my $total;
5231: foreach my $val (@txts) { $total+=$val; }
5232: if ($_64bit) { $total=(($total<<32)>>32); }
5233: return $total;
5234: }
5235:
1.368 albertel 5236: sub latest_rnd_algorithm_id {
1.575 albertel 5237: return '64bit4';
1.366 albertel 5238: }
1.32 www 5239:
1.503 albertel 5240: sub get_rand_alg {
5241: my ($courseid)=@_;
5242: if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
5243: if ($courseid) {
1.620 albertel 5244: return $env{"course.$courseid.rndseed"};
1.503 albertel 5245: }
5246: return &latest_rnd_algorithm_id();
5247: }
5248:
1.562 albertel 5249: sub validCODE {
5250: my ($CODE)=@_;
5251: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
5252: return 0;
5253: }
5254:
1.491 albertel 5255: sub getCODE {
1.620 albertel 5256: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 5257: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
5258: defined($Apache::lonhomework::parsing_a_task) ) &&
5259: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 5260: return $Apache::lonhomework::history{'resource.CODE'};
5261: }
5262: return undef;
5263: }
5264:
1.31 www 5265: sub rndseed {
1.155 albertel 5266: my ($symb,$courseid,$domain,$username)=@_;
1.366 albertel 5267:
5268: my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155 albertel 5269: if (!$symb) {
1.366 albertel 5270: unless ($symb=$wsymb) { return time; }
5271: }
5272: if (!$courseid) { $courseid=$wcourseid; }
5273: if (!$domain) { $domain=$wdomain; }
5274: if (!$username) { $username=$wusername }
1.503 albertel 5275: my $which=&get_rand_alg();
1.491 albertel 5276: if (defined(&getCODE())) {
1.575 albertel 5277: if ($which eq '64bit4') {
5278: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
5279: } else {
5280: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
5281: }
5282: } elsif ($which eq '64bit4') {
5283: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 5284: } elsif ($which eq '64bit3') {
5285: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 5286: } elsif ($which eq '64bit2') {
5287: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 5288: } elsif ($which eq '64bit') {
5289: return &rndseed_64bit($symb,$courseid,$domain,$username);
5290: }
5291: return &rndseed_32bit($symb,$courseid,$domain,$username);
5292: }
5293:
5294: sub rndseed_32bit {
5295: my ($symb,$courseid,$domain,$username)=@_;
5296: {
5297: use integer;
5298: my $symbchck=unpack("%32C*",$symb) << 27;
5299: my $symbseed=numval($symb) << 22;
5300: my $namechck=unpack("%32C*",$username) << 17;
5301: my $nameseed=numval($username) << 12;
5302: my $domainseed=unpack("%32C*",$domain) << 7;
5303: my $courseseed=unpack("%32C*",$courseid);
5304: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
5305: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
5306: #&Apache::lonxml::debug("rndseed :$num:$symb");
1.564 albertel 5307: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 5308: return $num;
5309: }
5310: }
5311:
5312: sub rndseed_64bit {
5313: my ($symb,$courseid,$domain,$username)=@_;
5314: {
5315: use integer;
5316: my $symbchck=unpack("%32S*",$symb) << 21;
5317: my $symbseed=numval($symb) << 10;
5318: my $namechck=unpack("%32S*",$username);
5319:
5320: my $nameseed=numval($username) << 21;
5321: my $domainseed=unpack("%32S*",$domain) << 10;
5322: my $courseseed=unpack("%32S*",$courseid);
5323:
5324: my $num1=$symbchck+$symbseed+$namechck;
5325: my $num2=$nameseed+$domainseed+$courseseed;
5326: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
5327: #&Apache::lonxml::debug("rndseed :$num:$symb");
1.564 albertel 5328: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
5329: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 5330: return "$num1,$num2";
1.155 albertel 5331: }
1.366 albertel 5332: }
5333:
1.443 albertel 5334: sub rndseed_64bit2 {
5335: my ($symb,$courseid,$domain,$username)=@_;
5336: {
5337: use integer;
5338: # strings need to be an even # of cahracters long, it it is odd the
5339: # last characters gets thrown away
5340: my $symbchck=unpack("%32S*",$symb.' ') << 21;
5341: my $symbseed=numval($symb) << 10;
5342: my $namechck=unpack("%32S*",$username.' ');
5343:
5344: my $nameseed=numval($username) << 21;
1.501 albertel 5345: my $domainseed=unpack("%32S*",$domain.' ') << 10;
5346: my $courseseed=unpack("%32S*",$courseid.' ');
5347:
5348: my $num1=$symbchck+$symbseed+$namechck;
5349: my $num2=$nameseed+$domainseed+$courseseed;
5350: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
5351: #&Apache::lonxml::debug("rndseed :$num:$symb");
5352: return "$num1,$num2";
5353: }
5354: }
5355:
5356: sub rndseed_64bit3 {
5357: my ($symb,$courseid,$domain,$username)=@_;
5358: {
5359: use integer;
5360: # strings need to be an even # of cahracters long, it it is odd the
5361: # last characters gets thrown away
5362: my $symbchck=unpack("%32S*",$symb.' ') << 21;
5363: my $symbseed=numval2($symb) << 10;
5364: my $namechck=unpack("%32S*",$username.' ');
5365:
5366: my $nameseed=numval2($username) << 21;
1.443 albertel 5367: my $domainseed=unpack("%32S*",$domain.' ') << 10;
5368: my $courseseed=unpack("%32S*",$courseid.' ');
5369:
5370: my $num1=$symbchck+$symbseed+$namechck;
5371: my $num2=$nameseed+$domainseed+$courseseed;
5372: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564 albertel 5373: #&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
5374: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
5375:
1.503 albertel 5376: return "$num1:$num2";
1.443 albertel 5377: }
5378: }
5379:
1.575 albertel 5380: sub rndseed_64bit4 {
5381: my ($symb,$courseid,$domain,$username)=@_;
5382: {
5383: use integer;
5384: # strings need to be an even # of cahracters long, it it is odd the
5385: # last characters gets thrown away
5386: my $symbchck=unpack("%32S*",$symb.' ') << 21;
5387: my $symbseed=numval3($symb) << 10;
5388: my $namechck=unpack("%32S*",$username.' ');
5389:
5390: my $nameseed=numval3($username) << 21;
5391: my $domainseed=unpack("%32S*",$domain.' ') << 10;
5392: my $courseseed=unpack("%32S*",$courseid.' ');
5393:
5394: my $num1=$symbchck+$symbseed+$namechck;
5395: my $num2=$nameseed+$domainseed+$courseseed;
5396: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
5397: #&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
5398: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
5399:
5400: return "$num1:$num2";
5401: }
5402: }
5403:
1.366 albertel 5404: sub rndseed_CODE_64bit {
5405: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 5406: {
1.366 albertel 5407: use integer;
1.443 albertel 5408: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 5409: my $symbseed=numval2($symb);
1.491 albertel 5410: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
5411: my $CODEseed=numval(&getCODE());
1.443 albertel 5412: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 5413: my $num1=$symbseed+$CODEchck;
5414: my $num2=$CODEseed+$courseseed+$symbchck;
5415: #&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366 albertel 5416: #&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564 albertel 5417: if ($_64bit) { $num1=(($num1<<32)>>32); }
5418: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 5419: return "$num1:$num2";
1.366 albertel 5420: }
5421: }
5422:
1.575 albertel 5423: sub rndseed_CODE_64bit4 {
5424: my ($symb,$courseid,$domain,$username)=@_;
5425: {
5426: use integer;
5427: my $symbchck=unpack("%32S*",$symb.' ') << 16;
5428: my $symbseed=numval3($symb);
5429: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
5430: my $CODEseed=numval3(&getCODE());
5431: my $courseseed=unpack("%32S*",$courseid.' ');
5432: my $num1=$symbseed+$CODEchck;
5433: my $num2=$CODEseed+$courseseed+$symbchck;
5434: #&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
5435: #&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
5436: if ($_64bit) { $num1=(($num1<<32)>>32); }
5437: if ($_64bit) { $num2=(($num2<<32)>>32); }
5438: return "$num1:$num2";
5439: }
5440: }
5441:
1.366 albertel 5442: sub setup_random_from_rndseed {
5443: my ($rndseed)=@_;
1.503 albertel 5444: if ($rndseed =~/([,:])/) {
5445: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 5446: &Math::Random::random_set_seed(abs($num1),abs($num2));
5447: } else {
5448: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 5449: }
1.36 albertel 5450: }
5451:
1.474 albertel 5452: sub latest_receipt_algorithm_id {
5453: return 'receipt2';
5454: }
5455:
1.480 www 5456: sub recunique {
5457: my $fucourseid=shift;
5458: my $unique;
1.620 albertel 5459: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
5460: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 5461: } else {
5462: $unique=$perlvar{'lonReceipt'};
5463: }
5464: return unpack("%32C*",$unique);
5465: }
5466:
5467: sub recprefix {
5468: my $fucourseid=shift;
5469: my $prefix;
1.620 albertel 5470: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
5471: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 5472: } else {
5473: $prefix=$perlvar{'lonHostID'};
5474: }
5475: return unpack("%32C*",$prefix);
5476: }
5477:
1.76 www 5478: sub ireceipt {
1.474 albertel 5479: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76 www 5480: my $cuname=unpack("%32C*",$funame);
5481: my $cudom=unpack("%32C*",$fudom);
5482: my $cucourseid=unpack("%32C*",$fucourseid);
5483: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 5484: my $cunique=&recunique($fucourseid);
1.474 albertel 5485: my $cpart=unpack("%32S*",$part);
1.480 www 5486: my $return =&recprefix($fucourseid).'-';
1.620 albertel 5487: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
5488: $env{'request.state'} eq 'construct') {
1.474 albertel 5489: &Apache::lonxml::debug("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname).
5490: " and ".($cpart%$cudom));
5491:
5492: $return.= ($cunique%$cuname+
5493: $cunique%$cudom+
5494: $cusymb%$cuname+
5495: $cusymb%$cudom+
5496: $cucourseid%$cuname+
5497: $cucourseid%$cudom+
5498: $cpart%$cuname+
5499: $cpart%$cudom);
5500: } else {
5501: $return.= ($cunique%$cuname+
5502: $cunique%$cudom+
5503: $cusymb%$cuname+
5504: $cusymb%$cudom+
5505: $cucourseid%$cuname+
5506: $cucourseid%$cudom);
5507: }
5508: return $return;
1.76 www 5509: }
5510:
5511: sub receipt {
1.474 albertel 5512: my ($part)=@_;
5513: my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
5514: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 5515: }
1.260 ng 5516:
1.36 albertel 5517: # ------------------------------------------------------------ Serves up a file
1.472 albertel 5518: # returns either the contents of the file or
5519: # -1 if the file doesn't exist
1.481 raeburn 5520: #
5521: # if the target is a file that was uploaded via DOCS,
5522: # a check will be made to see if a current copy exists on the local server,
5523: # if it does this will be served, otherwise a copy will be retrieved from
5524: # the home server for the course and stored in /home/httpd/html/userfiles on
5525: # the local server.
1.472 albertel 5526:
1.36 albertel 5527: sub getfile {
1.538 albertel 5528: my ($file) = @_;
1.609 banghart 5529: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 5530: &repcopy($file);
5531: return &readfile($file);
5532: }
5533:
5534: sub repcopy_userfile {
5535: my ($file)=@_;
1.609 banghart 5536: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 5537: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 5538: my ($cdom,$cnum,$filename) =
5539: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
5540: my ($info,$rtncode);
5541: my $uri="/uploaded/$cdom/$cnum/$filename";
5542: if (-e "$file") {
5543: my @fileinfo = stat($file);
5544: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 5545: if ($lwpresp ne 'ok') {
5546: if ($rtncode eq '404') {
1.538 albertel 5547: unlink($file);
1.482 albertel 5548: }
1.517 albertel 5549: #my $ua=new LWP::UserAgent;
1.538 albertel 5550: #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517 albertel 5551: #my $response=$ua->request($request);
5552: #if ($response->is_success()) {
5553: # return $response->content;
5554: # } else {
5555: # return -1;
5556: # }
1.482 albertel 5557: return -1;
5558: }
5559: if ($info < $fileinfo[9]) {
1.607 raeburn 5560: return 'ok';
1.482 albertel 5561: }
5562: $info = '';
1.538 albertel 5563: $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 5564: if ($lwpresp ne 'ok') {
5565: return -1;
5566: }
5567: } else {
1.538 albertel 5568: my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 5569: if ($lwpresp ne 'ok') {
1.517 albertel 5570: my $ua=new LWP::UserAgent;
1.538 albertel 5571: my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517 albertel 5572: my $response=$ua->request($request);
5573: if ($response->is_success()) {
1.538 albertel 5574: $info=$response->content;
1.517 albertel 5575: } else {
5576: return -1;
5577: }
1.482 albertel 5578: }
5579: my @parts = ($cdom,$cnum);
5580: if ($filename =~ m|^(.+)/[^/]+$|) {
5581: push @parts, split(/\//,$1);
1.518 albertel 5582: }
1.538 albertel 5583: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482 albertel 5584: foreach my $part (@parts) {
5585: $path .= '/'.$part;
5586: if (!-e $path) {
5587: mkdir($path,0770);
5588: }
5589: }
5590: }
1.538 albertel 5591: open(FILE,">$file");
1.482 albertel 5592: print FILE $info;
5593: close(FILE);
1.607 raeburn 5594: return 'ok';
1.481 raeburn 5595: }
5596:
1.517 albertel 5597: sub tokenwrapper {
5598: my $uri=shift;
1.552 albertel 5599: $uri=~s|^http\://([^/]+)||;
5600: $uri=~s|^/||;
1.620 albertel 5601: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 5602: my $token=$1;
1.552 albertel 5603: my (undef,$udom,$uname,$file)=split('/',$uri,4);
5604: if ($udom && $uname && $file) {
5605: $file=~s|(\?\.*)*$||;
1.620 albertel 5606: &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552 albertel 5607: return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517 albertel 5608: (($uri=~/\?/)?'&':'?').'token='.$token.
5609: '&tokenissued='.$perlvar{'lonHostID'};
5610: } else {
5611: return '/adm/notfound.html';
5612: }
5613: }
5614:
1.481 raeburn 5615: sub getuploaded {
5616: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
5617: $uri=~s/^\///;
5618: $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
5619: my $ua=new LWP::UserAgent;
5620: my $request=new HTTP::Request($reqtype,$uri);
5621: my $response=$ua->request($request);
5622: $$rtncode = $response->code;
1.482 albertel 5623: if (! $response->is_success()) {
5624: return 'failed';
5625: }
5626: if ($reqtype eq 'HEAD') {
1.486 www 5627: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 5628: } elsif ($reqtype eq 'GET') {
5629: $$info = $response->content;
1.472 albertel 5630: }
1.482 albertel 5631: return 'ok';
1.36 albertel 5632: }
5633:
1.481 raeburn 5634: sub readfile {
5635: my $file = shift;
5636: if ( (! -e $file ) || ($file eq '') ) { return -1; };
5637: my $fh;
5638: open($fh,"<$file");
5639: my $a='';
5640: while (<$fh>) { $a .=$_; }
5641: return $a;
5642: }
5643:
1.36 albertel 5644: sub filelocation {
1.590 banghart 5645: my ($dir,$file) = @_;
5646: my $location;
5647: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
5648: if ($file=~m:^/~:) { # is a contruction space reference
5649: $location = $file;
5650: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.609 banghart 5651: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 5652: my ($udom,$uname,$filename)=
1.609 banghart 5653: ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590 banghart 5654: my $home=&homeserver($uname,$udom);
5655: my $is_me=0;
5656: my @ids=¤t_machine_ids();
5657: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
5658: if ($is_me) {
5659: $location=&Apache::loncommon::propath($udom,$uname).
5660: '/userfiles/'.$filename;
5661: } else {
5662: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
5663: $udom.'/'.$uname.'/'.$filename;
5664: }
5665: } else {
5666: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
5667: $file=~s:^/res/:/:;
5668: if ( !( $file =~ m:^/:) ) {
5669: $location = $dir. '/'.$file;
5670: } else {
5671: $location = '/home/httpd/html/res'.$file;
5672: }
1.59 albertel 5673: }
1.590 banghart 5674: $location=~s://+:/:g; # remove duplicate /
5675: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
5676: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
5677: return $location;
1.46 www 5678: }
1.36 albertel 5679:
1.46 www 5680: sub hreflocation {
5681: my ($dir,$file)=@_;
1.460 albertel 5682: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
5683: my $finalpath=filelocation($dir,$file);
5684: $finalpath=~s-^/home/httpd/html--;
1.462 albertel 5685: $finalpath=~s-^/home/(\w+)/public_html/-/~$1/-;
1.460 albertel 5686: return $finalpath;
5687: } elsif ($file=~m-^/home-) {
5688: $file=~s-^/home/httpd/html--;
1.462 albertel 5689: $file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.460 albertel 5690: return $file;
1.46 www 5691: }
1.462 albertel 5692: return $file;
1.465 albertel 5693: }
5694:
5695: sub current_machine_domains {
5696: my $hostname=$hostname{$perlvar{'lonHostID'}};
5697: my @domains;
5698: while( my($id, $name) = each(%hostname)) {
1.467 matthew 5699: # &logthis("-$id-$name-$hostname-");
1.465 albertel 5700: if ($hostname eq $name) {
5701: push(@domains,$hostdom{$id});
5702: }
5703: }
5704: return @domains;
5705: }
5706:
5707: sub current_machine_ids {
5708: my $hostname=$hostname{$perlvar{'lonHostID'}};
5709: my @ids;
5710: while( my($id, $name) = each(%hostname)) {
1.467 matthew 5711: # &logthis("-$id-$name-$hostname-");
1.465 albertel 5712: if ($hostname eq $name) {
5713: push(@ids,$id);
5714: }
5715: }
5716: return @ids;
1.31 www 5717: }
5718:
5719: # ------------------------------------------------------------- Declutters URLs
5720:
5721: sub declutter {
5722: my $thisfn=shift;
1.569 albertel 5723: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 5724: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 5725: $thisfn=~s/^\///;
5726: $thisfn=~s/^res\///;
1.235 www 5727: $thisfn=~s/\?.+$//;
1.268 www 5728: return $thisfn;
5729: }
5730:
5731: # ------------------------------------------------------------- Clutter up URLs
5732:
5733: sub clutter {
5734: my $thisfn='/'.&declutter(shift);
1.609 banghart 5735: unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) {
1.270 www 5736: $thisfn='/res'.$thisfn;
5737: }
1.31 www 5738: return $thisfn;
1.12 www 5739: }
5740:
1.557 albertel 5741: sub freeze_escape {
5742: my ($value)=@_;
5743: if (ref($value)) {
5744: $value=&nfreeze($value);
5745: return '__FROZEN__'.&escape($value);
5746: }
5747: return &escape($value);
5748: }
5749:
1.12 www 5750: # -------------------------------------------------------- Escape Special Chars
5751:
5752: sub escape {
5753: my $str=shift;
5754: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
5755: return $str;
5756: }
5757:
5758: # ----------------------------------------------------- Un-Escape Special Chars
5759:
5760: sub unescape {
5761: my $str=shift;
5762: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
5763: return $str;
5764: }
1.11 www 5765:
1.557 albertel 5766: sub thaw_unescape {
5767: my ($value)=@_;
5768: if ($value =~ /^__FROZEN__/) {
5769: substr($value,0,10,undef);
5770: $value=&unescape($value);
5771: return &thaw($value);
5772: }
5773: return &unescape($value);
5774: }
5775:
1.415 albertel 5776: sub mod_perl_version {
1.580 albertel 5777: return 1;
1.415 albertel 5778: if (defined($perlvar{'MODPERL2'})) {
5779: return 2;
5780: }
1.436 albertel 5781: }
5782:
5783: sub correct_line_ends {
5784: my ($result)=@_;
5785: $$result =~s/\r\n/\n/mg;
5786: $$result =~s/\r/\n/mg;
1.415 albertel 5787: }
1.1 albertel 5788: # ================================================================ Main Program
5789:
1.184 www 5790: sub goodbye {
1.204 albertel 5791: &logthis("Starting Shut down");
1.443 albertel 5792: #not converted to using infrastruture and probably shouldn't be
1.599 albertel 5793: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443 albertel 5794: #converted
1.599 albertel 5795: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
5796: &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
5797: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
5798: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425 albertel 5799: #1.1 only
1.599 albertel 5800: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
5801: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
5802: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
5803: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
5804: &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
5805: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
5806: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 5807: &flushcourselogs();
5808: &logthis("Shutting down");
1.362 albertel 5809: return DONE;
1.184 www 5810: }
5811:
1.179 www 5812: BEGIN {
1.228 harris41 5813: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195 www 5814: unless ($readit) {
1.217 harris41 5815: {
1.581 matthew 5816: # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
1.448 albertel 5817: open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217 harris41 5818:
5819: while (my $configline=<$config>) {
1.484 albertel 5820: if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
1.1 albertel 5821: my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8 www 5822: chomp($varvalue);
1.1 albertel 5823: $perlvar{$varname}=$varvalue;
5824: }
5825: }
1.448 albertel 5826: close($config);
1.1 albertel 5827: }
1.227 harris41 5828: {
1.448 albertel 5829: open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227 harris41 5830:
5831: while (my $configline=<$config>) {
5832: if ($configline =~ /^[^\#]*PerlSetVar/) {
5833: my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
5834: chomp($varvalue);
5835: $perlvar{$varname}=$varvalue;
5836: }
5837: }
1.448 albertel 5838: close($config);
1.227 harris41 5839: }
1.1 albertel 5840:
1.327 albertel 5841: # ------------------------------------------------------------ Read domain file
5842: {
5843: %domaindescription = ();
5844: %domain_auth_def = ();
5845: %domain_auth_arg_def = ();
1.448 albertel 5846: my $fh;
5847: if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327 albertel 5848: while (<$fh>) {
1.390 matthew 5849: next if (/^(\#|\s*$)/);
5850: # next if /^\#/;
1.327 albertel 5851: chomp;
1.403 www 5852: my ($domain, $domain_description, $def_auth, $def_auth_arg,
5853: $def_lang, $city, $longi, $lati) = split(/:/,$_);
5854: $domain_auth_def{$domain}=$def_auth;
1.327 albertel 5855: $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403 www 5856: $domaindescription{$domain}=$domain_description;
5857: $domain_lang_def{$domain}=$def_lang;
5858: $domain_city{$domain}=$city;
5859: $domain_longi{$domain}=$longi;
5860: $domain_lati{$domain}=$lati;
5861:
1.448 albertel 5862: # &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327 albertel 5863: # &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448 albertel 5864: }
1.327 albertel 5865: }
1.448 albertel 5866: close ($fh);
1.327 albertel 5867: }
5868:
5869:
1.1 albertel 5870: # ------------------------------------------------------------- Read hosts file
5871: {
1.448 albertel 5872: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1 albertel 5873:
5874: while (my $configline=<$config>) {
1.303 matthew 5875: next if ($configline =~ /^(\#|\s*$)/);
1.154 www 5876: chomp($configline);
1.595 albertel 5877: my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597 albertel 5878: $name=~s/\s//g;
1.595 albertel 5879: if ($id && $domain && $role && $name) {
1.252 albertel 5880: $hostname{$id}=$name;
5881: $hostdom{$id}=$domain;
5882: if ($role eq 'library') { $libserv{$id}=$name; }
1.245 www 5883: }
1.1 albertel 5884: }
1.448 albertel 5885: close($config);
1.619 albertel 5886: # FIXME: dev server don't want this, production servers _do_ want this
5887: #&get_iphost();
1.1 albertel 5888: }
5889:
1.598 albertel 5890: sub get_iphost {
5891: if (%iphost) { return %iphost; }
5892: foreach my $id (keys(%hostname)) {
5893: my $name=$hostname{$id};
5894: my $ip = gethostbyname($name);
5895: if (!$ip || length($ip) ne 4) {
5896: &logthis("Skipping host $id name $name no IP found\n");
5897: next;
5898: }
5899: $ip=inet_ntoa($ip);
5900: push(@{$iphost{$ip}},$id);
5901: }
5902: return %iphost;
5903: }
5904:
1.1 albertel 5905: # ------------------------------------------------------ Read spare server file
5906: {
1.448 albertel 5907: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 5908:
5909: while (my $configline=<$config>) {
5910: chomp($configline);
1.284 matthew 5911: if ($configline) {
1.1 albertel 5912: $spareid{$configline}=1;
5913: }
5914: }
1.448 albertel 5915: close($config);
1.1 albertel 5916: }
1.11 www 5917: # ------------------------------------------------------------ Read permissions
5918: {
1.448 albertel 5919: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 5920:
5921: while (my $configline=<$config>) {
1.448 albertel 5922: chomp($configline);
5923: if ($configline) {
5924: my ($role,$perm)=split(/ /,$configline);
5925: if ($perm ne '') { $pr{$role}=$perm; }
5926: }
1.11 www 5927: }
1.448 albertel 5928: close($config);
1.11 www 5929: }
5930:
5931: # -------------------------------------------- Read plain texts for permissions
5932: {
1.448 albertel 5933: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 5934:
5935: while (my $configline=<$config>) {
1.448 albertel 5936: chomp($configline);
5937: if ($configline) {
5938: my ($short,$plain)=split(/:/,$configline);
5939: if ($plain ne '') { $prp{$short}=$plain; }
5940: }
1.135 www 5941: }
1.448 albertel 5942: close($config);
1.135 www 5943: }
5944:
5945: # ---------------------------------------------------------- Read package table
5946: {
1.448 albertel 5947: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 5948:
5949: while (my $configline=<$config>) {
1.483 albertel 5950: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 5951: chomp($configline);
5952: my ($short,$plain)=split(/:/,$configline);
5953: my ($pack,$name)=split(/\&/,$short);
5954: if ($plain ne '') {
5955: $packagetab{$pack.'&'.$name.'&name'}=$name;
5956: $packagetab{$short}=$plain;
5957: }
1.11 www 5958: }
1.448 albertel 5959: close($config);
1.329 matthew 5960: }
5961:
5962: # ------------- set up temporary directory
5963: {
5964: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
5965:
1.11 www 5966: }
5967:
1.599 albertel 5968: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185 www 5969:
1.281 www 5970: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 5971: $dumpcount=0;
1.22 www 5972:
1.163 harris41 5973: &logtouch();
1.12 www 5974: &logthis('<font color=yellow>INFO: Read configuration</font>');
1.195 www 5975: $readit=1;
1.564 albertel 5976: {
5977: use integer;
5978: my $test=(2**32)+1;
1.568 albertel 5979: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 5980: &logthis(" Detected 64bit platform ($_64bit)");
5981: }
1.195 www 5982: }
1.1 albertel 5983: }
1.179 www 5984:
1.1 albertel 5985: 1;
1.191 harris41 5986: __END__
5987:
1.243 albertel 5988: =pod
5989:
1.191 harris41 5990: =head1 NAME
5991:
1.243 albertel 5992: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 5993:
5994: =head1 SYNOPSIS
5995:
1.243 albertel 5996: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 5997:
5998: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
5999:
1.243 albertel 6000: Common parameters:
6001:
6002: =over 4
6003:
6004: =item *
6005:
6006: $uname : an internal username (if $cname expecting a course Id specifically)
6007:
6008: =item *
6009:
6010: $udom : a domain (if $cdom expecting a course's domain specifically)
6011:
6012: =item *
6013:
6014: $symb : a resource instance identifier
6015:
6016: =item *
6017:
6018: $namespace : the name of a .db file that contains the data needed or
6019: being set.
6020:
6021: =back
6022:
1.394 bowersj2 6023: =head1 OVERVIEW
1.191 harris41 6024:
1.394 bowersj2 6025: lonnet provides subroutines which interact with the
6026: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
6027: about classes, users, and resources.
1.243 albertel 6028:
6029: For many of these objects you can also use this to store data about
6030: them or modify them in various ways.
1.191 harris41 6031:
1.394 bowersj2 6032: =head2 Symbs
1.191 harris41 6033:
1.394 bowersj2 6034: To identify a specific instance of a resource, LON-CAPA uses symbols
6035: or "symbs"X<symb>. These identifiers are built from the URL of the
6036: map, the resource number of the resource in the map, and the URL of
6037: the resource itself. The latter is somewhat redundant, but might help
6038: if maps change.
6039:
6040: An example is
6041:
6042: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
6043:
6044: The respective map entry is
6045:
6046: <resource id="19" src="/res/msu/korte/tests/part12.problem"
6047: title="Problem 2">
6048: </resource>
6049:
6050: Symbs are used by the random number generator, as well as to store and
6051: restore data specific to a certain instance of for example a problem.
6052:
6053: =head2 Storing And Retrieving Data
6054:
6055: X<store()>X<cstore()>X<restore()>Three of the most important functions
6056: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
6057: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
6058: is is the non-critical message twin of cstore. These functions are for
6059: handlers to store a perl hash to a user's permanent data space in an
6060: easy manner, and to retrieve it again on another call. It is expected
6061: that a handler would use this once at the beginning to retrieve data,
6062: and then again once at the end to send only the new data back.
6063:
6064: The data is stored in the user's data directory on the user's
6065: homeserver under the ID of the course.
6066:
6067: The hash that is returned by restore will have all of the previous
6068: value for all of the elements of the hash.
6069:
6070: Example:
6071:
6072: #creating a hash
6073: my %hash;
6074: $hash{'foo'}='bar';
6075:
6076: #storing it
6077: &Apache::lonnet::cstore(\%hash);
6078:
6079: #changing a value
6080: $hash{'foo'}='notbar';
6081:
6082: #adding a new value
6083: $hash{'bar'}='foo';
6084: &Apache::lonnet::cstore(\%hash);
6085:
6086: #retrieving the hash
6087: my %history=&Apache::lonnet::restore();
6088:
6089: #print the hash
6090: foreach my $key (sort(keys(%history))) {
6091: print("\%history{$key} = $history{$key}");
6092: }
6093:
6094: Will print out:
1.191 harris41 6095:
1.394 bowersj2 6096: %history{1:foo} = bar
6097: %history{1:keys} = foo:timestamp
6098: %history{1:timestamp} = 990455579
6099: %history{2:bar} = foo
6100: %history{2:foo} = notbar
6101: %history{2:keys} = foo:bar:timestamp
6102: %history{2:timestamp} = 990455580
6103: %history{bar} = foo
6104: %history{foo} = notbar
6105: %history{timestamp} = 990455580
6106: %history{version} = 2
6107:
6108: Note that the special hash entries C<keys>, C<version> and
6109: C<timestamp> were added to the hash. C<version> will be equal to the
6110: total number of versions of the data that have been stored. The
6111: C<timestamp> attribute will be the UNIX time the hash was
6112: stored. C<keys> is available in every historical section to list which
6113: keys were added or changed at a specific historical revision of a
6114: hash.
6115:
6116: B<Warning>: do not store the hash that restore returns directly. This
6117: will cause a mess since it will restore the historical keys as if the
6118: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 6119:
1.394 bowersj2 6120: Calling convention:
1.191 harris41 6121:
1.394 bowersj2 6122: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
6123: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 6124:
1.394 bowersj2 6125: For more detailed information, see lonnet specific documentation.
1.191 harris41 6126:
1.394 bowersj2 6127: =head1 RETURN MESSAGES
1.191 harris41 6128:
1.394 bowersj2 6129: =over 4
1.191 harris41 6130:
1.394 bowersj2 6131: =item * B<con_lost>: unable to contact remote host
1.191 harris41 6132:
1.394 bowersj2 6133: =item * B<con_delayed>: unable to contact remote host, message will be delivered
6134: when the connection is brought back up
1.191 harris41 6135:
1.394 bowersj2 6136: =item * B<con_failed>: unable to contact remote host and unable to save message
6137: for later delivery
1.191 harris41 6138:
1.394 bowersj2 6139: =item * B<error:>: an error a occured, a description of the error follows the :
1.191 harris41 6140:
1.394 bowersj2 6141: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 6142: that was requested
1.191 harris41 6143:
1.243 albertel 6144: =back
1.191 harris41 6145:
1.243 albertel 6146: =head1 PUBLIC SUBROUTINES
1.191 harris41 6147:
1.243 albertel 6148: =head2 Session Environment Functions
1.191 harris41 6149:
1.243 albertel 6150: =over 4
1.191 harris41 6151:
1.394 bowersj2 6152: =item *
6153: X<appenv()>
6154: B<appenv(%hash)>: the value of %hash is written to
6155: the user envirnoment file, and will be restored for each access this
1.620 albertel 6156: user makes during this session, also modifies the %env for the current
1.394 bowersj2 6157: process
1.191 harris41 6158:
6159: =item *
1.394 bowersj2 6160: X<delenv()>
6161: B<delenv($regexp)>: removes all items from the session
6162: environment file that matches the regular expression in $regexp. The
1.620 albertel 6163: values are also delted from the current processes %env.
1.191 harris41 6164:
1.243 albertel 6165: =back
6166:
6167: =head2 User Information
1.191 harris41 6168:
1.243 albertel 6169: =over 4
1.191 harris41 6170:
6171: =item *
1.394 bowersj2 6172: X<queryauthenticate()>
6173: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 6174: authentication scheme
6175:
6176: =item *
1.394 bowersj2 6177: X<authenticate()>
6178: B<authenticate($uname,$upass,$udom)>: try to
6179: authenticate user from domain's lib servers (first use the current
6180: one). C<$upass> should be the users password.
1.191 harris41 6181:
6182: =item *
1.394 bowersj2 6183: X<homeserver()>
6184: B<homeserver($uname,$udom)>: find the server which has
6185: the user's directory and files (there must be only one), this caches
6186: the answer, and also caches if there is a borken connection.
1.191 harris41 6187:
6188: =item *
1.394 bowersj2 6189: X<idget()>
6190: B<idget($udom,@ids)>: find the usernames behind a list of IDs
6191: (IDs are a unique resource in a domain, there must be only 1 ID per
6192: username, and only 1 username per ID in a specific domain) (returns
6193: hash: id=>name,id=>name)
1.191 harris41 6194:
6195: =item *
1.394 bowersj2 6196: X<idrget()>
6197: B<idrget($udom,@unames)>: find the IDs behind a list of
6198: usernames (returns hash: name=>id,name=>id)
1.191 harris41 6199:
6200: =item *
1.394 bowersj2 6201: X<idput()>
6202: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 6203:
6204: =item *
1.394 bowersj2 6205: X<rolesinit()>
6206: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 6207:
6208: =item *
1.551 albertel 6209: X<getsection()>
6210: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 6211: course $cname, return section name/number or '' for "not in course"
6212: and '-1' for "no section"
6213:
6214: =item *
1.394 bowersj2 6215: X<userenvironment()>
6216: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 6217: passed in @what from the requested user's environment, returns a hash
6218:
6219: =back
6220:
6221: =head2 User Roles
6222:
6223: =over 4
6224:
6225: =item *
6226:
6227: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
6228: actions
6229: F: full access
6230: U,I,K: authentication modes (cxx only)
6231: '': forbidden
6232: 1: user needs to choose course
6233: 2: browse allowed
6234:
6235: =item *
6236:
6237: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
6238: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
6239: and course level
6240:
6241: =item *
6242:
6243: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
6244: explanation of a user role term
6245:
6246: =back
6247:
6248: =head2 User Modification
6249:
6250: =over 4
6251:
6252: =item *
6253:
6254: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
6255: user for the level given by URL. Optional start and end dates (leave empty
6256: string or zero for "no date")
1.191 harris41 6257:
6258: =item *
6259:
1.243 albertel 6260: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
6261: change a users, password, possible return values are: ok,
6262: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
6263: refused
1.191 harris41 6264:
6265: =item *
6266:
1.243 albertel 6267: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 6268:
6269: =item *
6270:
1.243 albertel 6271: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
6272: modify user
1.191 harris41 6273:
6274: =item *
6275:
1.286 matthew 6276: modifystudent
6277:
6278: modify a students enrollment and identification information.
6279: The course id is resolved based on the current users environment.
6280: This means the envoking user must be a course coordinator or otherwise
6281: associated with a course.
6282:
1.297 matthew 6283: This call is essentially a wrapper for lonnet::modifyuser and
6284: lonnet::modify_student_enrollment
1.286 matthew 6285:
6286: Inputs:
6287:
6288: =over 4
6289:
6290: =item B<$udom> Students loncapa domain
6291:
6292: =item B<$uname> Students loncapa login name
6293:
6294: =item B<$uid> Students id/student number
6295:
6296: =item B<$umode> Students authentication mode
6297:
6298: =item B<$upass> Students password
6299:
6300: =item B<$first> Students first name
6301:
6302: =item B<$middle> Students middle name
6303:
6304: =item B<$last> Students last name
6305:
6306: =item B<$gene> Students generation
6307:
6308: =item B<$usec> Students section in course
6309:
6310: =item B<$end> Unix time of the roles expiration
6311:
6312: =item B<$start> Unix time of the roles start date
6313:
6314: =item B<$forceid> If defined, allow $uid to be changed
6315:
6316: =item B<$desiredhome> server to use as home server for student
6317:
6318: =back
1.297 matthew 6319:
6320: =item *
6321:
6322: modify_student_enrollment
6323:
6324: Change a students enrollment status in a class. The environment variable
6325: 'role.request.course' must be defined for this function to proceed.
6326:
6327: Inputs:
6328:
6329: =over 4
6330:
6331: =item $udom, students domain
6332:
6333: =item $uname, students name
6334:
6335: =item $uid, students user id
6336:
6337: =item $first, students first name
6338:
6339: =item $middle
6340:
6341: =item $last
6342:
6343: =item $gene
6344:
6345: =item $usec
6346:
6347: =item $end
6348:
6349: =item $start
6350:
6351: =back
6352:
1.191 harris41 6353:
6354: =item *
6355:
1.243 albertel 6356: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
6357: custom role; give a custom role to a user for the level given by URL. Specify
6358: name and domain of role author, and role name
1.191 harris41 6359:
6360: =item *
6361:
1.243 albertel 6362: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 6363:
6364: =item *
6365:
1.243 albertel 6366: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
6367:
6368: =back
6369:
6370: =head2 Course Infomation
6371:
6372: =over 4
1.191 harris41 6373:
6374: =item *
6375:
1.631 albertel 6376: coursedescription($courseid) : returns a hash of information about the
6377: specified course id, including all environment settings for the
6378: course, the description of the course will be in the hash under the
6379: key 'description'
1.191 harris41 6380:
6381: =item *
6382:
1.624 albertel 6383: resdata($name,$domain,$type,@which) : request for current parameter
6384: setting for a specific $type, where $type is either 'course' or 'user',
6385: @what should be a list of parameters to ask about. This routine caches
6386: answers for 5 minutes.
1.243 albertel 6387:
6388: =back
6389:
6390: =head2 Course Modification
6391:
6392: =over 4
1.191 harris41 6393:
6394: =item *
6395:
1.243 albertel 6396: writecoursepref($courseid,%prefs) : write preferences (environment
6397: database) for a course
1.191 harris41 6398:
6399: =item *
6400:
1.243 albertel 6401: createcourse($udom,$description,$url) : make/modify course
6402:
6403: =back
6404:
6405: =head2 Resource Subroutines
6406:
6407: =over 4
1.191 harris41 6408:
6409: =item *
6410:
1.243 albertel 6411: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 6412:
6413: =item *
6414:
1.243 albertel 6415: repcopy($filename) : subscribes to the requested file, and attempts to
6416: replicate from the owning library server, Might return
1.607 raeburn 6417: 'unavailable', 'not_found', 'forbidden', 'ok', or
6418: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 6419: resource. Expects the local filesystem pathname
6420: (/home/httpd/html/res/....)
6421:
6422: =back
6423:
6424: =head2 Resource Information
6425:
6426: =over 4
1.191 harris41 6427:
6428: =item *
6429:
1.243 albertel 6430: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
6431: a vairety of different possible values, $varname should be a request
6432: string, and the other parameters can be used to specify who and what
6433: one is asking about.
6434:
6435: Possible values for $varname are environment.lastname (or other item
6436: from the envirnment hash), user.name (or someother aspect about the
6437: user), resource.0.maxtries (or some other part and parameter of a
6438: resource)
1.204 albertel 6439:
6440: =item *
6441:
1.243 albertel 6442: directcondval($number) : get current value of a condition; reads from a state
6443: string
1.204 albertel 6444:
6445: =item *
6446:
1.243 albertel 6447: condval($condidx) : value of condition index based on state
1.204 albertel 6448:
6449: =item *
6450:
1.243 albertel 6451: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
6452: resource's metadata, $what should be either a specific key, or either
6453: 'keys' (to get a list of possible keys) or 'packages' to get a list of
6454: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
6455:
6456: this function automatically caches all requests
1.191 harris41 6457:
6458: =item *
6459:
1.243 albertel 6460: metadata_query($query,$custom,$customshow) : make a metadata query against the
6461: network of library servers; returns file handle of where SQL and regex results
6462: will be stored for query
1.191 harris41 6463:
6464: =item *
6465:
1.243 albertel 6466: symbread($filename) : return symbolic list entry (filename argument optional);
6467: returns the data handle
1.191 harris41 6468:
6469: =item *
6470:
1.243 albertel 6471: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 6472: a possible symb for the URL in $thisfn, and if is an encryypted
6473: resource that the user accessed using /enc/ returns a 1 on success, 0
6474: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 6475: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 6476:
1.191 harris41 6477:
6478: =item *
6479:
1.243 albertel 6480: symbclean($symb) : removes versions numbers from a symb, returns the
6481: cleaned symb
1.191 harris41 6482:
6483: =item *
6484:
1.243 albertel 6485: is_on_map($uri) : checks if the $uri is somewhere on the current
6486: course map, user must be in a course for it to work.
1.191 harris41 6487:
6488: =item *
6489:
1.243 albertel 6490: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 6491:
6492: =item *
6493:
1.243 albertel 6494: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
6495: a random seed, all arguments are optional, if they aren't sent it uses the
6496: environment to derive them. Note: if symb isn't sent and it can't get one
6497: from &symbread it will use the current time as its return value
1.191 harris41 6498:
6499: =item *
6500:
1.243 albertel 6501: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
6502: unfakeable, receipt
1.191 harris41 6503:
6504: =item *
6505:
1.620 albertel 6506: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 6507:
6508: =item *
6509:
1.243 albertel 6510: countacc($url) : count the number of accesses to a given URL
1.191 harris41 6511:
6512: =item *
6513:
1.243 albertel 6514: 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 6515:
6516: =item *
6517:
1.243 albertel 6518: 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 6519:
6520: =item *
6521:
1.243 albertel 6522: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 6523:
6524: =item *
6525:
1.243 albertel 6526: devalidate($symb) : devalidate temporary spreadsheet calculations,
6527: forcing spreadsheet to reevaluate the resource scores next time.
6528:
6529: =back
6530:
6531: =head2 Storing/Retreiving Data
6532:
6533: =over 4
1.191 harris41 6534:
6535: =item *
6536:
1.243 albertel 6537: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
6538: for this url; hashref needs to be given and should be a \%hashname; the
6539: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 6540: be derived from the env
1.191 harris41 6541:
6542: =item *
6543:
1.243 albertel 6544: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
6545: uses critical subroutine
1.191 harris41 6546:
6547: =item *
6548:
1.243 albertel 6549: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
6550: all args are optional
1.191 harris41 6551:
6552: =item *
6553:
1.243 albertel 6554: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
6555: works very similar to store/cstore, but all data is stored in a
6556: temporary location and can be reset using tmpreset, $storehash should
6557: be a hash reference, returns nothing on success
1.191 harris41 6558:
6559: =item *
6560:
1.243 albertel 6561: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
6562: similar to restore, but all data is stored in a temporary location and
6563: can be reset using tmpreset. Returns a hash of values on success,
6564: error string otherwise.
1.191 harris41 6565:
6566: =item *
6567:
1.243 albertel 6568: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
6569: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 6570:
6571: =item *
6572:
1.243 albertel 6573: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
6574: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 6575:
6576: =item *
6577:
1.243 albertel 6578: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
6579: namesp ($udom and $uname are optional)
1.191 harris41 6580:
6581: =item *
6582:
1.243 albertel 6583: dump($namespace,$udom,$uname,$regexp) :
6584: dumps the complete (or key matching regexp) namespace into a hash
6585: ($udom, $uname and $regexp are optional)
1.449 matthew 6586:
6587: =item *
6588:
6589: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
6590: $store can be a scalar, an array reference, or if the amount to be
6591: incremented is > 1, a hash reference.
6592:
6593: ($udom and $uname are optional)
1.191 harris41 6594:
6595: =item *
6596:
1.243 albertel 6597: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
6598: ($udom and $uname are optional)
1.191 harris41 6599:
6600: =item *
6601:
1.524 raeburn 6602: putstore($namespace,$storehash,$udomain,$uname) : stores hash in namesp
6603: keys used in storehash include version information (e.g., 1:$symb:message etc.) as
6604: used in records written by &store and retrieved by &restore. This function
6605: was created for use in editing discussion posts, without incrementing the
6606: version number included in the key for a particular post. The colon
6607: separated list of attribute names (e.g., the value associated with the key
6608: 1:keys:$symb) is also generated and passed in the ampersand separated
6609: items sent to lonnet::reply().
6610:
6611: =item *
6612:
1.243 albertel 6613: cput($namespace,$storehash,$udom,$uname) : critical put
6614: ($udom and $uname are optional)
1.191 harris41 6615:
6616: =item *
6617:
1.243 albertel 6618: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
6619: reference filled in from namesp (encrypts the return communication)
6620: ($udom and $uname are optional)
1.191 harris41 6621:
6622: =item *
6623:
1.243 albertel 6624: log($udom,$name,$home,$message) : write to permanent log for user; use
6625: critical subroutine
6626:
6627: =back
6628:
6629: =head2 Network Status Functions
6630:
6631: =over 4
1.191 harris41 6632:
6633: =item *
6634:
6635: dirlist($uri) : return directory list based on URI
6636:
6637: =item *
6638:
1.243 albertel 6639: spareserver() : find server with least workload from spare.tab
6640:
6641: =back
6642:
6643: =head2 Apache Request
6644:
6645: =over 4
1.191 harris41 6646:
6647: =item *
6648:
1.243 albertel 6649: ssi($url,%hash) : server side include, does a complete request cycle on url to
6650: localhost, posts hash
6651:
6652: =back
6653:
6654: =head2 Data to String to Data
6655:
6656: =over 4
1.191 harris41 6657:
6658: =item *
6659:
1.243 albertel 6660: hash2str(%hash) : convert a hash into a string complete with escaping and '='
6661: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 6662:
6663: =item *
6664:
1.243 albertel 6665: hashref2str($hashref) : convert a hashref into a string complete with
6666: escaping and '=' and '&' separators, supports elements that are
6667: arrayrefs and hashrefs
1.191 harris41 6668:
6669: =item *
6670:
1.243 albertel 6671: arrayref2str($arrayref) : convert an arrayref into a string complete
6672: with escaping and '&' separators, supports elements that are arrayrefs
6673: and hashrefs
1.191 harris41 6674:
6675: =item *
6676:
1.243 albertel 6677: str2hash($string) : convert string to hash using unescaping and
6678: splitting on '=' and '&', supports elements that are arrayrefs and
6679: hashrefs
1.191 harris41 6680:
6681: =item *
6682:
1.243 albertel 6683: str2array($string) : convert string to hash using unescaping and
6684: splitting on '&', supports elements that are arrayrefs and hashrefs
6685:
6686: =back
6687:
6688: =head2 Logging Routines
6689:
6690: =over 4
6691:
6692: These routines allow one to make log messages in the lonnet.log and
6693: lonnet.perm logfiles.
1.191 harris41 6694:
6695: =item *
6696:
1.243 albertel 6697: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 6698:
6699: =item *
6700:
1.243 albertel 6701: logthis() : append message to the normal lonnet.log file, it gets
6702: preiodically rolled over and deleted.
1.191 harris41 6703:
6704: =item *
6705:
1.243 albertel 6706: logperm() : append a permanent message to lonnet.perm.log, this log
6707: file never gets deleted by any automated portion of the system, only
6708: messages of critical importance should go in here.
6709:
6710: =back
6711:
6712: =head2 General File Helper Routines
6713:
6714: =over 4
1.191 harris41 6715:
6716: =item *
6717:
1.481 raeburn 6718: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
6719: (a) files in /uploaded
6720: (i) If a local copy of the file exists -
6721: compares modification date of local copy with last-modified date for
6722: definitive version stored on home server for course. If local copy is
6723: stale, requests a new version from the home server and stores it.
6724: If the original has been removed from the home server, then local copy
6725: is unlinked.
6726: (ii) If local copy does not exist -
6727: requests the file from the home server and stores it.
6728:
6729: If $caller is 'uploadrep':
6730: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
6731: for request for files originally uploaded via DOCS.
6732: - returns 'ok' if fresh local copy now available, -1 otherwise.
6733:
6734: Otherwise:
6735: This indicates a call from the content generation phase of the request.
6736: - returns the entire contents of the file or -1.
6737:
6738: (b) files in /res
6739: - returns the entire contents of a file or -1;
6740: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 6741:
6742: =item *
6743:
1.243 albertel 6744: filelocation($dir,$file) : returns file system location of a file
6745: based on URI; meant to be "fairly clean" absolute reference, $dir is a
6746: directory that relative $file lookups are to looked in ($dir of /a/dir
6747: and a file of ../bob will become /a/bob)
1.191 harris41 6748:
6749: =item *
6750:
6751: hreflocation($dir,$file) : returns file system location or a URL; same as
6752: filelocation except for hrefs
6753:
6754: =item *
6755:
6756: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
6757:
1.243 albertel 6758: =back
6759:
1.608 albertel 6760: =head2 Usererfile file routines (/uploaded*)
6761:
6762: =over 4
6763:
6764: =item *
6765:
6766: userfileupload(): main rotine for putting a file in a user or course's
6767: filespace, arguments are,
6768:
1.620 albertel 6769: formname - required - this is the name of the element in $env where the
1.608 albertel 6770: filename, and the contents of the file to create/modifed exist
1.620 albertel 6771: the filename is in $env{'form.'.$formname.'.filename'} and the
6772: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 6773: coursedoc - if true, store the file in the course of the active role
6774: of the current user
6775: subdir - required - subdirectory to put the file in under ../userfiles/
6776: if undefined, it will be placed in "unknown"
6777:
6778: (This routine calls clean_filename() to remove any dangerous
6779: characters from the filename, and then calls finuserfileupload() to
6780: complete the transaction)
6781:
6782: returns either the url of the uploaded file (/uploaded/....) if successful
6783: and /adm/notfound.html if unsuccessful
6784:
6785: =item *
6786:
6787: clean_filename(): routine for cleaing a filename up for storage in
6788: userfile space, argument is:
6789:
6790: filename - proposed filename
6791:
6792: returns: the new clean filename
6793:
6794: =item *
6795:
6796: finishuserfileupload(): routine that creaes and sends the file to
6797: userspace, probably shouldn't be called directly
6798:
6799: docuname: username or courseid of destination for the file
6800: docudom: domain of user/course of destination for the file
6801: docuhome: loncapa id of the library server that is getting the file
6802: formname: same as for userfileupload()
6803: fname: filename (inculding subdirectories) for the file
6804:
6805: returns either the url of the uploaded file (/uploaded/....) if successful
6806: and /adm/notfound.html if unsuccessful
6807:
6808: =item *
6809:
6810: renameuserfile(): renames an existing userfile to a new name
6811:
6812: Args:
6813: docuname: username or courseid of destination for the file
6814: docudom: domain of user/course of destination for the file
6815: old: current file name (including any subdirs under userfiles)
6816: new: desired file name (including any subdirs under userfiles)
6817:
6818: =item *
6819:
6820: mkdiruserfile(): creates a directory is a userfiles dir
6821:
6822: Args:
6823: docuname: username or courseid of destination for the file
6824: docudom: domain of user/course of destination for the file
6825: dir: dir to create (including any subdirs under userfiles)
6826:
6827: =item *
6828:
6829: removeuserfile(): removes a file that exists in userfiles
6830:
6831: Args:
6832: docuname: username or courseid of destination for the file
6833: docudom: domain of user/course of destination for the file
6834: fname: filname to delete (including any subdirs under userfiles)
6835:
6836: =item *
6837:
6838: removeuploadedurl(): convience function for removeuserfile()
6839:
6840: Args:
6841: url: a full /uploaded/... url to delete
6842:
6843: =back
6844:
1.243 albertel 6845: =head2 HTTP Helper Routines
6846:
6847: =over 4
6848:
1.191 harris41 6849: =item *
6850:
6851: escape() : unpack non-word characters into CGI-compatible hex codes
6852:
6853: =item *
6854:
6855: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
6856:
1.243 albertel 6857: =back
6858:
6859: =head1 PRIVATE SUBROUTINES
6860:
6861: =head2 Underlying communication routines (Shouldn't call)
6862:
6863: =over 4
6864:
6865: =item *
6866:
6867: subreply() : tries to pass a message to lonc, returns con_lost if incapable
6868:
6869: =item *
6870:
6871: reply() : uses subreply to send a message to remote machine, logs all failures
6872:
6873: =item *
6874:
6875: critical() : passes a critical message to another server; if cannot
6876: get through then place message in connection buffer directory and
6877: returns con_delayed, if incapable of saving message, returns
6878: con_failed
6879:
6880: =item *
6881:
6882: reconlonc() : tries to reconnect lonc client processes.
6883:
6884: =back
6885:
6886: =head2 Resource Access Logging
6887:
6888: =over 4
6889:
6890: =item *
6891:
6892: flushcourselogs() : flush (save) buffer logs and access logs
6893:
6894: =item *
6895:
6896: courselog($what) : save message for course in hash
6897:
6898: =item *
6899:
6900: courseacclog($what) : save message for course using &courselog(). Perform
6901: special processing for specific resource types (problems, exams, quizzes, etc).
6902:
1.191 harris41 6903: =item *
6904:
6905: goodbye() : flush course logs and log shutting down; it is called in srm.conf
6906: as a PerlChildExitHandler
1.243 albertel 6907:
6908: =back
6909:
6910: =head2 Other
6911:
6912: =over 4
6913:
6914: =item *
6915:
6916: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 6917:
6918: =back
6919:
6920: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>