Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.932
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.932 ! raeburn 4: # $Id: lonnet.pm,v 1.931 2007/12/08 00:28:27 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.486 www 34: use HTTP::Date;
35: # use Date::Parse;
1.871 albertel 36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
37: $_64bit %env);
38:
39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
40: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
41: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
42: %courseownerbuf, %coursetypebuf);
1.403 www 43:
1.1 albertel 44: use IO::Socket;
1.31 www 45: use GDBM_File;
1.208 albertel 46: use HTML::LCParser;
1.88 www 47: use Fcntl qw(:flock);
1.870 albertel 48: use Storable qw(thaw nfreeze);
1.539 albertel 49: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 50: use Cache::Memcached;
1.676 albertel 51: use Digest::MD5;
1.790 albertel 52: use Math::Random;
1.807 albertel 53: use LONCAPA qw(:DEFAULT :match);
1.740 www 54: use LONCAPA::Configuration;
1.676 albertel 55:
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
1.729 www 88: {
89: my $logid;
90: sub instructor_log {
91: my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
92: $logid++;
93: my $id=time().'00000'.$$.'00000'.$logid;
94: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 95: { $id => {
96: 'exe_uname' => $env{'user.name'},
97: 'exe_udom' => $env{'user.domain'},
98: 'exe_time' => time(),
99: 'exe_ip' => $ENV{'REMOTE_ADDR'},
100: 'delflag' => $delflag,
101: 'logentry' => $storehash,
102: 'uname' => $uname,
103: 'udom' => $udom,
104: }
105: },
1.729 www 106: $env{'course.'.$env{'request.course.id'}.'.domain'},
107: $env{'course.'.$env{'request.course.id'}.'.num'}
108: );
109: }
110: }
1.1 albertel 111:
1.163 harris41 112: sub logtouch {
113: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 114: unless (-e "$execdir/logs/lonnet.log") {
115: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 116: close $fh;
117: }
118: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
119: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
120: }
121:
1.1 albertel 122: sub logthis {
123: my $message=shift;
124: my $execdir=$perlvar{'lonDaemons'};
125: my $now=time;
126: my $local=localtime($now);
1.448 albertel 127: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
128: print $fh "$local ($$): $message\n";
129: close($fh);
130: }
1.1 albertel 131: return 1;
132: }
133:
134: sub logperm {
135: my $message=shift;
136: my $execdir=$perlvar{'lonDaemons'};
137: my $now=time;
138: my $local=localtime($now);
1.448 albertel 139: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
140: print $fh "$now:$message:$local\n";
141: close($fh);
142: }
1.1 albertel 143: return 1;
144: }
145:
1.850 albertel 146: sub create_connection {
1.853 albertel 147: my ($hostname,$lonid) = @_;
1.851 albertel 148: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 149: Type => SOCK_STREAM,
150: Timeout => 10);
151: return 0 if (!$client);
1.890 albertel 152: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 153: my $result = <$client>;
154: chomp($result);
155: return 1 if ($result eq 'done');
156: return 0;
157: }
158:
159:
1.1 albertel 160: # -------------------------------------------------- Non-critical communication
161: sub subreply {
162: my ($cmd,$server)=@_;
1.838 albertel 163: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 164: #
165: # With loncnew process trimming, there's a timing hole between lonc server
166: # process exit and the master server picking up the listen on the AF_UNIX
167: # socket. In that time interval, a lock file will exist:
168:
169: my $lockfile=$peerfile.".lock";
170: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
171: sleep(1);
172: }
173: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 174: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 175: #
1.550 foxr 176: # We'll give the connection a few tries before abandoning it. If
177: # connection is not possible, we'll con_lost back to the client.
178: #
179: my $client;
180: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
181: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
182: Type => SOCK_STREAM,
183: Timeout => 10);
1.869 albertel 184: if ($client) {
1.550 foxr 185: last; # Connected!
1.850 albertel 186: } else {
1.853 albertel 187: &create_connection(&hostname($server),$server);
1.550 foxr 188: }
1.850 albertel 189: sleep(1); # Try again later if failed connection.
1.550 foxr 190: }
191: my $answer;
192: if ($client) {
1.704 albertel 193: print $client "sethost:$server:$cmd\n";
1.550 foxr 194: $answer=<$client>;
195: if (!$answer) { $answer="con_lost"; }
196: chomp($answer);
197: } else {
198: $answer = 'con_lost'; # Failed connection.
199: }
1.1 albertel 200: return $answer;
201: }
202:
203: sub reply {
204: my ($cmd,$server)=@_;
1.838 albertel 205: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 206: my $answer=subreply($cmd,$server);
1.65 www 207: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 208: &logthis("<font color=\"blue\">WARNING:".
1.12 www 209: " $cmd to $server returned $answer</font>");
210: }
1.1 albertel 211: return $answer;
212: }
213:
214: # ----------------------------------------------------------- Send USR1 to lonc
215:
216: sub reconlonc {
1.891 albertel 217: my ($lonid) = @_;
218: my $hostname = &hostname($lonid);
219: if ($lonid) {
220: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
221: if ($hostname && -e $peerfile) {
222: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
223: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
224: Type => SOCK_STREAM,
225: Timeout => 10);
226: if ($client) {
227: print $client ("reset_retries\n");
228: my $answer=<$client>;
229: #reset just this one.
230: }
231: }
232: return;
233: }
234:
1.836 www 235: &logthis("Trying to reconnect lonc");
1.1 albertel 236: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 237: if (open(my $fh,"<$loncfile")) {
1.1 albertel 238: my $loncpid=<$fh>;
239: chomp($loncpid);
240: if (kill 0 => $loncpid) {
241: &logthis("lonc at pid $loncpid responding, sending USR1");
242: kill USR1 => $loncpid;
243: sleep 1;
1.836 www 244: } else {
1.12 www 245: &logthis(
1.672 albertel 246: "<font color=\"blue\">WARNING:".
1.12 www 247: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 248: }
249: } else {
1.836 www 250: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 251: }
252: }
253:
254: # ------------------------------------------------------ Critical communication
1.12 www 255:
1.1 albertel 256: sub critical {
257: my ($cmd,$server)=@_;
1.838 albertel 258: unless (&hostname($server)) {
1.672 albertel 259: &logthis("<font color=\"blue\">WARNING:".
1.89 www 260: " Critical message to unknown server ($server)</font>");
261: return 'no_such_host';
262: }
1.1 albertel 263: my $answer=reply($cmd,$server);
264: if ($answer eq 'con_lost') {
265: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 266: my $answer=reply($cmd,$server);
1.1 albertel 267: if ($answer eq 'con_lost') {
268: my $now=time;
269: my $middlename=$cmd;
1.5 www 270: $middlename=substr($middlename,0,16);
1.1 albertel 271: $middlename=~s/\W//g;
272: my $dfilename=
1.305 www 273: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
274: $dumpcount++;
1.1 albertel 275: {
1.448 albertel 276: my $dfh;
277: if (open($dfh,">$dfilename")) {
278: print $dfh "$cmd\n";
279: close($dfh);
280: }
1.1 albertel 281: }
282: sleep 2;
283: my $wcmd='';
284: {
1.448 albertel 285: my $dfh;
286: if (open($dfh,"<$dfilename")) {
287: $wcmd=<$dfh>;
288: close($dfh);
289: }
1.1 albertel 290: }
291: chomp($wcmd);
1.7 www 292: if ($wcmd eq $cmd) {
1.672 albertel 293: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 294: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 295: &logperm("D:$server:$cmd");
296: return 'con_delayed';
297: } else {
1.672 albertel 298: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 299: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 300: &logperm("F:$server:$cmd");
301: return 'con_failed';
302: }
303: }
304: }
305: return $answer;
1.405 albertel 306: }
307:
1.755 albertel 308: # ------------------------------------------- check if return value is an error
309:
310: sub error {
311: my ($result) = @_;
1.756 albertel 312: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 313: if ($2 == 2) { return undef; }
314: return $1;
315: }
316: return undef;
317: }
318:
1.783 albertel 319: sub convert_and_load_session_env {
320: my ($lonidsdir,$handle)=@_;
321: my @profile;
322: {
1.917 albertel 323: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
324: if (!$opened) {
1.915 albertel 325: return 0;
326: }
1.783 albertel 327: flock($idf,LOCK_SH);
328: @profile=<$idf>;
329: close($idf);
330: }
331: my %temp_env;
332: foreach my $line (@profile) {
1.786 albertel 333: if ($line !~ m/=/) {
334: return 0;
335: }
1.783 albertel 336: chomp($line);
337: my ($envname,$envvalue)=split(/=/,$line,2);
338: $temp_env{&unescape($envname)} = &unescape($envvalue);
339: }
340: unlink("$lonidsdir/$handle.id");
341: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
342: 0640)) {
343: %disk_env = %temp_env;
344: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
345: untie(%disk_env);
346: }
1.786 albertel 347: return 1;
1.783 albertel 348: }
349:
1.374 www 350: # ------------------------------------------- Transfer profile into environment
1.780 albertel 351: my $env_loaded;
352: sub transfer_profile_to_env {
1.788 albertel 353: my ($lonidsdir,$handle,$force_transfer) = @_;
354: if (!$force_transfer && $env_loaded) { return; }
1.374 www 355:
1.720 albertel 356: if (!defined($lonidsdir)) {
357: $lonidsdir = $perlvar{'lonIDsDir'};
358: }
359: if (!defined($handle)) {
360: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
361: }
362:
1.786 albertel 363: my $convert;
364: {
1.917 albertel 365: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
366: if (!$opened) {
1.915 albertel 367: return;
368: }
1.786 albertel 369: flock($idf,LOCK_SH);
370: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
371: &GDBM_READER(),0640)) {
372: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
373: untie(%disk_env);
374: } else {
375: $convert = 1;
376: }
377: }
378: if ($convert) {
379: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
380: &logthis("Failed to load session, or convert session.");
381: }
1.374 www 382: }
1.783 albertel 383:
1.786 albertel 384: my %remove;
1.783 albertel 385: while ( my $envname = each(%env) ) {
1.433 matthew 386: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
387: if ($time < time-300) {
1.783 albertel 388: $remove{$key}++;
1.433 matthew 389: }
390: }
391: }
1.783 albertel 392:
1.619 albertel 393: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 394: $env_loaded=1;
1.783 albertel 395: foreach my $expired_key (keys(%remove)) {
1.433 matthew 396: &delenv($expired_key);
1.374 www 397: }
1.1 albertel 398: }
399:
1.916 albertel 400: # ---------------------------------------------------- Check for valid session
401: sub check_for_valid_session {
402: my ($r) = @_;
403: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
404: my $lonid=$cookies{'lonID'};
405: return undef if (!$lonid);
406:
407: my $handle=&LONCAPA::clean_handle($lonid->value);
408: my $lonidsdir=$r->dir_config('lonIDsDir');
409: return undef if (!-e "$lonidsdir/$handle.id");
410:
1.917 albertel 411: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
412: return undef if (!$opened);
1.916 albertel 413:
414: flock($idf,LOCK_SH);
415: my %disk_env;
416: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
417: &GDBM_READER(),0640)) {
418: return undef;
419: }
420:
421: if (!defined($disk_env{'user.name'})
422: || !defined($disk_env{'user.domain'})) {
423: return undef;
424: }
425: return $handle;
426: }
427:
1.830 albertel 428: sub timed_flock {
429: my ($file,$lock_type) = @_;
430: my $failed=0;
431: eval {
432: local $SIG{__DIE__}='DEFAULT';
433: local $SIG{ALRM}=sub {
434: $failed=1;
435: die("failed lock");
436: };
437: alarm(13);
438: flock($file,$lock_type);
439: alarm(0);
440: };
441: if ($failed) {
442: return undef;
443: } else {
444: return 1;
445: }
446: }
447:
1.5 www 448: # ---------------------------------------------------------- Append Environment
449:
450: sub appenv {
1.6 www 451: my %newenv=@_;
1.692 albertel 452: foreach my $key (keys(%newenv)) {
453: if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672 albertel 454: &logthis("<font color=\"blue\">WARNING: ".
1.692 albertel 455: "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151 www 456: .'</font>');
1.692 albertel 457: delete($newenv{$key});
1.35 www 458: } else {
1.692 albertel 459: $env{$key}=$newenv{$key};
1.35 www 460: }
1.191 harris41 461: }
1.917 albertel 462: my $opened = open(my $env_file,'+<',$env{'user.environment'});
463: if ($opened
1.915 albertel 464: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 465: &&
466: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
467: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 468: while (my ($key,$value) = each(%newenv)) {
469: $disk_env{$key} = $value;
1.448 albertel 470: }
1.783 albertel 471: untie(%disk_env);
1.56 www 472: }
473: return 'ok';
474: }
475: # ----------------------------------------------------- Delete from Environment
476:
477: sub delenv {
478: my $delthis=shift;
479: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 480: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 481: "Attempt to delete from environment ".$delthis);
482: return 'error';
483: }
1.917 albertel 484: my $opened = open(my $env_file,'+<',$env{'user.environment'});
485: if ($opened
1.915 albertel 486: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 487: &&
488: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
489: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 490: foreach my $key (keys(%disk_env)) {
491: if ($key=~/^$delthis/) {
1.915 albertel 492: delete($env{$key});
493: delete($disk_env{$key});
494: }
1.448 albertel 495: }
1.783 albertel 496: untie(%disk_env);
1.5 www 497: }
498: return 'ok';
1.369 albertel 499: }
500:
1.790 albertel 501: sub get_env_multiple {
502: my ($name) = @_;
503: my @values;
504: if (defined($env{$name})) {
505: # exists is it an array
506: if (ref($env{$name})) {
507: @values=@{ $env{$name} };
508: } else {
509: $values[0]=$env{$name};
510: }
511: }
512: return(@values);
513: }
514:
1.369 albertel 515: # ------------------------------------------ Find out current server userload
516: sub userload {
517: my $numusers=0;
518: {
519: opendir(LONIDS,$perlvar{'lonIDsDir'});
520: my $filename;
521: my $curtime=time;
522: while ($filename=readdir(LONIDS)) {
1.925 albertel 523: next if ($filename eq '.' || $filename eq '..');
524: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 525: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 526: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 527: }
528: closedir(LONIDS);
529: }
530: my $userloadpercent=0;
531: my $maxuserload=$perlvar{'lonUserLoadLim'};
532: if ($maxuserload) {
1.371 albertel 533: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 534: }
1.372 albertel 535: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 536: return $userloadpercent;
1.283 www 537: }
538:
539: # ------------------------------------------ Fight off request when overloaded
540:
541: sub overloaderror {
542: my ($r,$checkserver)=@_;
543: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
544: my $loadavg;
545: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 546: open(my $loadfile,'/proc/loadavg');
1.283 www 547: $loadavg=<$loadfile>;
548: $loadavg =~ s/\s.*//g;
1.285 matthew 549: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 550: close($loadfile);
1.283 www 551: } else {
552: $loadavg=&reply('load',$checkserver);
553: }
1.285 matthew 554: my $overload=$loadavg-100;
1.283 www 555: if ($overload>0) {
1.285 matthew 556: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 557: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 558: return 413;
1.283 www 559: }
560: return '';
1.5 www 561: }
1.1 albertel 562:
563: # ------------------------------ Find server with least workload from spare.tab
1.11 www 564:
1.1 albertel 565: sub spareserver {
1.670 albertel 566: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 567: my $spare_server;
1.370 albertel 568: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 569: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
570: : $userloadpercent;
571:
572: foreach my $try_server (@{ $spareid{'primary'} }) {
573: ($spare_server, $lowest_load) =
574: &compare_server_load($try_server, $spare_server, $lowest_load);
575: }
576:
577: my $found_server = ($spare_server ne '' && $lowest_load < 100);
578:
579: if (!$found_server) {
580: foreach my $try_server (@{ $spareid{'default'} }) {
581: ($spare_server, $lowest_load) =
582: &compare_server_load($try_server, $spare_server, $lowest_load);
583: }
584: }
585:
586: if (!$want_server_name) {
1.838 albertel 587: $spare_server="http://".&hostname($spare_server);
1.784 albertel 588: }
589: return $spare_server;
590: }
591:
592: sub compare_server_load {
593: my ($try_server, $spare_server, $lowest_load) = @_;
594:
595: my $loadans = &reply('load', $try_server);
596: my $userloadans = &reply('userload',$try_server);
597:
598: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
599: next; #didn't get a number from the server
600: }
601:
602: my $load;
603: if ($loadans =~ /\d/) {
604: if ($userloadans =~ /\d/) {
605: #both are numbers, pick the bigger one
606: $load = ($loadans > $userloadans) ? $loadans
607: : $userloadans;
1.411 albertel 608: } else {
1.784 albertel 609: $load = $loadans;
1.411 albertel 610: }
1.784 albertel 611: } else {
612: $load = $userloadans;
613: }
614:
615: if (($load =~ /\d/) && ($load < $lowest_load)) {
616: $spare_server = $try_server;
617: $lowest_load = $load;
1.370 albertel 618: }
1.784 albertel 619: return ($spare_server,$lowest_load);
1.202 matthew 620: }
1.914 albertel 621:
622: # --------------------------- ask offload servers if user already has a session
623: sub find_existing_session {
624: my ($udom,$uname) = @_;
625: foreach my $try_server (@{ $spareid{'primary'} },
626: @{ $spareid{'default'} }) {
627: return $try_server if (&has_user_session($try_server, $udom, $uname));
628: }
629: return;
630: }
631:
632: # -------------------------------- ask if server already has a session for user
633: sub has_user_session {
634: my ($lonid,$udom,$uname) = @_;
635: my $result = &reply(join(':','userhassession',
636: map {&escape($_)} ($udom,$uname)),$lonid);
637: return 1 if ($result eq 'ok');
638:
639: return 0;
640: }
641:
1.202 matthew 642: # --------------------------------------------- Try to change a user's password
643:
644: sub changepass {
1.799 raeburn 645: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 646: $currentpass = &escape($currentpass);
647: $newpass = &escape($newpass);
1.799 raeburn 648: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202 matthew 649: $server);
650: if (! $answer) {
651: &logthis("No reply on password change request to $server ".
652: "by $uname in domain $udom.");
653: } elsif ($answer =~ "^ok") {
654: &logthis("$uname in $udom successfully changed their password ".
655: "on $server.");
656: } elsif ($answer =~ "^pwchange_failure") {
657: &logthis("$uname in $udom was unable to change their password ".
658: "on $server. The action was blocked by either lcpasswd ".
659: "or pwchange");
660: } elsif ($answer =~ "^non_authorized") {
661: &logthis("$uname in $udom did not get their password correct when ".
662: "attempting to change it on $server.");
663: } elsif ($answer =~ "^auth_mode_error") {
664: &logthis("$uname in $udom attempted to change their password despite ".
665: "not being locally or internally authenticated on $server.");
666: } elsif ($answer =~ "^unknown_user") {
667: &logthis("$uname in $udom attempted to change their password ".
668: "on $server but were unable to because $server is not ".
669: "their home server.");
670: } elsif ($answer =~ "^refused") {
671: &logthis("$server refused to change $uname in $udom password because ".
672: "it was sent an unencrypted request to change the password.");
673: }
674: return $answer;
1.1 albertel 675: }
676:
1.169 harris41 677: # ----------------------- Try to determine user's current authentication scheme
678:
679: sub queryauthenticate {
680: my ($uname,$udom)=@_;
1.456 albertel 681: my $uhome=&homeserver($uname,$udom);
682: if (!$uhome) {
683: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
684: return 'no_host';
685: }
686: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
687: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
688: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 689: }
1.456 albertel 690: return $answer;
1.169 harris41 691: }
692:
1.1 albertel 693: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 694:
1.1 albertel 695: sub authenticate {
696: my ($uname,$upass,$udom)=@_;
1.807 albertel 697: $upass=&escape($upass);
698: $uname= &LONCAPA::clean_username($uname);
1.836 www 699: my $uhome=&homeserver($uname,$udom,1);
700: if ((!$uhome) || ($uhome eq 'no_host')) {
701: # Maybe the machine was offline and only re-appeared again recently?
702: &reconlonc();
703: # One more
704: my $uhome=&homeserver($uname,$udom,1);
705: if ((!$uhome) || ($uhome eq 'no_host')) {
706: &logthis("User $uname at $udom is unknown in authenticate");
707: }
1.471 albertel 708: return 'no_host';
1.1 albertel 709: }
1.471 albertel 710: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
711: if ($answer eq 'authorized') {
712: &logthis("User $uname at $udom authorized by $uhome");
713: return $uhome;
714: }
715: if ($answer eq 'non_authorized') {
716: &logthis("User $uname at $udom rejected by $uhome");
717: return 'no_host';
1.9 www 718: }
1.471 albertel 719: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 720: return 'no_host';
721: }
722:
723: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 724:
1.599 albertel 725: my %homecache;
1.1 albertel 726: sub homeserver {
1.230 stredwic 727: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 728: my $index="$uname:$udom";
1.426 albertel 729:
1.599 albertel 730: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 731:
732: my %servers = &get_servers($udom,'library');
733: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 734: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 735: exists($badServerCache{$tryserver}));
1.841 albertel 736:
737: my $answer=reply("home:$udom:$uname",$tryserver);
738: if ($answer eq 'found') {
739: delete($badServerCache{$tryserver});
740: return $homecache{$index}=$tryserver;
741: } elsif ($answer eq 'no_host') {
742: $badServerCache{$tryserver}=1;
743: }
1.1 albertel 744: }
745: return 'no_host';
1.70 www 746: }
747:
748: # ------------------------------------- Find the usernames behind a list of IDs
749:
750: sub idget {
751: my ($udom,@ids)=@_;
752: my %returnhash=();
753:
1.841 albertel 754: my %servers = &get_servers($udom,'library');
755: foreach my $tryserver (keys(%servers)) {
756: my $idlist=join('&',@ids);
757: $idlist=~tr/A-Z/a-z/;
758: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
759: my @answer=();
760: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
761: @answer=split(/\&/,$reply);
762: } ;
763: my $i;
764: for ($i=0;$i<=$#ids;$i++) {
765: if ($answer[$i]) {
766: $returnhash{$ids[$i]}=$answer[$i];
767: }
768: }
769: }
1.70 www 770: return %returnhash;
771: }
772:
773: # ------------------------------------- Find the IDs behind a list of usernames
774:
775: sub idrget {
776: my ($udom,@unames)=@_;
777: my %returnhash=();
1.800 albertel 778: foreach my $uname (@unames) {
779: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 780: }
1.70 www 781: return %returnhash;
782: }
783:
784: # ------------------------------- Store away a list of names and associated IDs
785:
786: sub idput {
787: my ($udom,%ids)=@_;
788: my %servers=();
1.800 albertel 789: foreach my $uname (keys(%ids)) {
790: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
791: my $uhom=&homeserver($uname,$udom);
1.70 www 792: if ($uhom ne 'no_host') {
1.800 albertel 793: my $id=&escape($ids{$uname});
1.70 www 794: $id=~tr/A-Z/a-z/;
1.800 albertel 795: my $esc_unam=&escape($uname);
1.70 www 796: if ($servers{$uhom}) {
1.800 albertel 797: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 798: } else {
1.800 albertel 799: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 800: }
801: }
1.191 harris41 802: }
1.800 albertel 803: foreach my $server (keys(%servers)) {
804: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 805: }
1.344 www 806: }
807:
1.806 raeburn 808: # ------------------------------------------- get items from domain db files
809:
810: sub get_dom {
1.860 raeburn 811: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 812: my $items='';
813: foreach my $item (@$storearr) {
814: $items.=&escape($item).'&';
815: }
816: $items=~s/\&$//;
1.860 raeburn 817: if (!$udom) {
818: $udom=$env{'user.domain'};
819: if (defined(&domain($udom,'primary'))) {
820: $uhome=&domain($udom,'primary');
821: } else {
1.874 albertel 822: undef($uhome);
1.860 raeburn 823: }
824: } else {
825: if (!$uhome) {
826: if (defined(&domain($udom,'primary'))) {
827: $uhome=&domain($udom,'primary');
828: }
829: }
830: }
831: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 832: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 833: my %returnhash;
1.875 albertel 834: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 835: return %returnhash;
836: }
1.806 raeburn 837: my @pairs=split(/\&/,$rep);
838: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
839: return @pairs;
840: }
841: my $i=0;
842: foreach my $item (@$storearr) {
843: $returnhash{$item}=&thaw_unescape($pairs[$i]);
844: $i++;
845: }
846: return %returnhash;
847: } else {
1.880 banghart 848: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 849: }
850: }
851:
852: # -------------------------------------------- put items in domain db files
853:
854: sub put_dom {
1.860 raeburn 855: my ($namespace,$storehash,$udom,$uhome)=@_;
856: if (!$udom) {
857: $udom=$env{'user.domain'};
858: if (defined(&domain($udom,'primary'))) {
859: $uhome=&domain($udom,'primary');
860: } else {
1.874 albertel 861: undef($uhome);
1.860 raeburn 862: }
863: } else {
864: if (!$uhome) {
865: if (defined(&domain($udom,'primary'))) {
866: $uhome=&domain($udom,'primary');
867: }
868: }
869: }
870: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 871: my $items='';
872: foreach my $item (keys(%$storehash)) {
873: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
874: }
875: $items=~s/\&$//;
876: return &reply("putdom:$udom:$namespace:$items",$uhome);
877: } else {
1.860 raeburn 878: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 879: }
880: }
881:
1.837 raeburn 882: sub retrieve_inst_usertypes {
883: my ($udom) = @_;
884: my (%returnhash,@order);
1.846 albertel 885: if (defined(&domain($udom,'primary'))) {
886: my $uhome=&domain($udom,'primary');
1.837 raeburn 887: my $rep=&reply("inst_usertypes:$udom",$uhome);
888: my ($hashitems,$orderitems) = split(/:/,$rep);
889: my @pairs=split(/\&/,$hashitems);
890: foreach my $item (@pairs) {
891: my ($key,$value)=split(/=/,$item,2);
892: $key = &unescape($key);
893: next if ($key =~ /^error: 2 /);
894: $returnhash{$key}=&thaw_unescape($value);
895: }
896: my @esc_order = split(/\&/,$orderitems);
897: foreach my $item (@esc_order) {
898: push(@order,&unescape($item));
899: }
900: } else {
901: &logthis("get_dom failed - no primary domain server for $udom");
902: }
903: return (\%returnhash,\@order);
904: }
905:
1.868 raeburn 906: sub is_domainimage {
907: my ($url) = @_;
908: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
909: if (&domain($1) ne '') {
910: return '1';
911: }
912: }
913: return;
914: }
915:
1.899 raeburn 916: sub inst_directory_query {
917: my ($srch) = @_;
918: my $udom = $srch->{'srchdomain'};
919: my %results;
920: my $homeserver = &domain($udom,'primary');
1.909 raeburn 921: my $outcome;
1.899 raeburn 922: if ($homeserver ne '') {
1.904 albertel 923: my $queryid=&reply("querysend:instdirsearch:".
924: &escape($srch->{'srchby'}).':'.
925: &escape($srch->{'srchterm'}).':'.
926: &escape($srch->{'srchtype'}),$homeserver);
927: my $host=&hostname($homeserver);
928: if ($queryid !~/^\Q$host\E\_/) {
929: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
930: return;
931: }
932: my $response = &get_query_reply($queryid);
933: my $maxtries = 5;
934: my $tries = 1;
935: while (($response=~/^timeout/) && ($tries < $maxtries)) {
936: $response = &get_query_reply($queryid);
937: $tries ++;
938: }
939:
940: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 941: if ($response eq 'unavailable') {
942: $outcome = $response;
943: } else {
944: $outcome = 'ok';
945: my @matches = split(/\n/,$response);
946: foreach my $match (@matches) {
947: my ($key,$value) = split(/=/,$match);
948: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
949: }
1.899 raeburn 950: }
951: }
952: }
1.909 raeburn 953: return ($outcome,%results);
1.899 raeburn 954: }
955:
956: sub usersearch {
957: my ($srch) = @_;
958: my $dom = $srch->{'srchdomain'};
959: my %results;
960: my %libserv = &all_library();
961: my $query = 'usersearch';
962: foreach my $tryserver (keys(%libserv)) {
963: if (&host_domain($tryserver) eq $dom) {
964: my $host=&hostname($tryserver);
965: my $queryid=
1.911 raeburn 966: &reply("querysend:".&escape($query).':'.
967: &escape($srch->{'srchby'}).':'.
1.899 raeburn 968: &escape($srch->{'srchtype'}).':'.
969: &escape($srch->{'srchterm'}),$tryserver);
970: if ($queryid !~/^\Q$host\E\_/) {
971: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 972: next;
1.899 raeburn 973: }
974: my $reply = &get_query_reply($queryid);
975: my $maxtries = 1;
976: my $tries = 1;
977: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
978: $reply = &get_query_reply($queryid);
979: $tries ++;
980: }
981: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
982: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
983: } else {
1.911 raeburn 984: my @matches;
985: if ($reply =~ /\n/) {
986: @matches = split(/\n/,$reply);
987: } else {
988: @matches = split(/\&/,$reply);
989: }
1.899 raeburn 990: foreach my $match (@matches) {
991: my ($uname,$udom,%userhash);
1.911 raeburn 992: foreach my $entry (split(/:/,$match)) {
993: my ($key,$value) =
994: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 995: $userhash{$key} = $value;
996: if ($key eq 'username') {
997: $uname = $value;
998: } elsif ($key eq 'domain') {
999: $udom = $value;
1.911 raeburn 1000: }
1.899 raeburn 1001: }
1002: $results{$uname.':'.$udom} = \%userhash;
1003: }
1004: }
1005: }
1006: }
1007: return %results;
1008: }
1009:
1.912 raeburn 1010: sub get_instuser {
1011: my ($udom,$uname,$id) = @_;
1012: my $homeserver = &domain($udom,'primary');
1013: my ($outcome,%results);
1014: if ($homeserver ne '') {
1015: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1016: &escape($id).':'.&escape($udom),$homeserver);
1017: my $host=&hostname($homeserver);
1018: if ($queryid !~/^\Q$host\E\_/) {
1019: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1020: return;
1021: }
1022: my $response = &get_query_reply($queryid);
1023: my $maxtries = 5;
1024: my $tries = 1;
1025: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1026: $response = &get_query_reply($queryid);
1027: $tries ++;
1028: }
1029: if (!&error($response) && $response ne 'refused') {
1030: if ($response eq 'unavailable') {
1031: $outcome = $response;
1032: } else {
1033: $outcome = 'ok';
1034: my @matches = split(/\n/,$response);
1035: foreach my $match (@matches) {
1036: my ($key,$value) = split(/=/,$match);
1037: $results{&unescape($key)} = &thaw_unescape($value);
1038: }
1039: }
1040: }
1041: }
1042: my %userinfo;
1043: if (ref($results{$uname}) eq 'HASH') {
1044: %userinfo = %{$results{$uname}};
1045: }
1046: return ($outcome,%userinfo);
1047: }
1048:
1049: sub inst_rulecheck {
1.923 raeburn 1050: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1051: my %returnhash;
1052: if ($udom ne '') {
1053: if (ref($rules) eq 'ARRAY') {
1054: @{$rules} = map {&escape($_);} (@{$rules});
1055: my $rulestr = join(':',@{$rules});
1056: my $homeserver=&domain($udom,'primary');
1057: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1058: my $response;
1059: if ($item eq 'username') {
1060: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1061: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1062: $homeserver));
1.923 raeburn 1063: } elsif ($item eq 'id') {
1064: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1065: ':'.&escape($id).':'.$rulestr,
1066: $homeserver));
1067: }
1.912 raeburn 1068: if ($response ne 'refused') {
1069: my @pairs=split(/\&/,$response);
1070: foreach my $item (@pairs) {
1071: my ($key,$value)=split(/=/,$item,2);
1072: $key = &unescape($key);
1073: next if ($key =~ /^error: 2 /);
1074: $returnhash{$key}=&thaw_unescape($value);
1075: }
1076: }
1077: }
1078: }
1079: }
1080: return %returnhash;
1081: }
1082:
1083: sub inst_userrules {
1.923 raeburn 1084: my ($udom,$check) = @_;
1.912 raeburn 1085: my (%ruleshash,@ruleorder);
1086: if ($udom ne '') {
1087: my $homeserver=&domain($udom,'primary');
1088: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1089: my $response;
1090: if ($check eq 'id') {
1091: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1092: $homeserver);
1.923 raeburn 1093: } else {
1094: $response=&reply('instuserrules:'.&escape($udom),
1095: $homeserver);
1096: }
1.912 raeburn 1097: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1098: ($response ne 'unknown_cmd') &&
1.912 raeburn 1099: ($response ne 'no_such_host')) {
1100: my ($hashitems,$orderitems) = split(/:/,$response);
1101: my @pairs=split(/\&/,$hashitems);
1102: foreach my $item (@pairs) {
1103: my ($key,$value)=split(/=/,$item,2);
1104: $key = &unescape($key);
1105: next if ($key =~ /^error: 2 /);
1106: $ruleshash{$key}=&thaw_unescape($value);
1107: }
1108: my @esc_order = split(/\&/,$orderitems);
1109: foreach my $item (@esc_order) {
1110: push(@ruleorder,&unescape($item));
1111: }
1112: }
1113: }
1114: }
1115: return (\%ruleshash,\@ruleorder);
1116: }
1117:
1.344 www 1118: # --------------------------------------------------- Assign a key to a student
1119:
1120: sub assign_access_key {
1.364 www 1121: #
1122: # a valid key looks like uname:udom#comments
1123: # comments are being appended
1124: #
1.498 www 1125: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1126: $kdom=
1.620 albertel 1127: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1128: $knum=
1.620 albertel 1129: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1130: $cdom=
1.620 albertel 1131: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1132: $cnum=
1.620 albertel 1133: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1134: $udom=$env{'user.name'} unless (defined($udom));
1135: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1136: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1137: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1138: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1139: # assigned to this person
1140: # - this should not happen,
1.345 www 1141: # unless something went wrong
1142: # the first time around
1143: # ready to assign
1.364 www 1144: $logentry=$1.'; '.$logentry;
1.496 www 1145: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1146: $kdom,$knum) eq 'ok') {
1.345 www 1147: # key now belongs to user
1.346 www 1148: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1149: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1150: &appenv('environment.'.$envkey => $ckey);
1151: return 'ok';
1152: } else {
1153: return
1154: 'error: Count not permanently assign key, will need to be re-entered later.';
1155: }
1156: } else {
1157: return 'error: Could not assign key, try again later.';
1158: }
1.364 www 1159: } elsif (!$existing{$ckey}) {
1.345 www 1160: # the key does not exist
1161: return 'error: The key does not exist';
1162: } else {
1163: # the key is somebody else's
1164: return 'error: The key is already in use';
1165: }
1.344 www 1166: }
1167:
1.364 www 1168: # ------------------------------------------ put an additional comment on a key
1169:
1170: sub comment_access_key {
1171: #
1172: # a valid key looks like uname:udom#comments
1173: # comments are being appended
1174: #
1175: my ($ckey,$cdom,$cnum,$logentry)=@_;
1176: $cdom=
1.620 albertel 1177: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1178: $cnum=
1.620 albertel 1179: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1180: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1181: if ($existing{$ckey}) {
1182: $existing{$ckey}.='; '.$logentry;
1183: # ready to assign
1.367 www 1184: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1185: $cdom,$cnum) eq 'ok') {
1186: return 'ok';
1187: } else {
1188: return 'error: Count not store comment.';
1189: }
1190: } else {
1191: # the key does not exist
1192: return 'error: The key does not exist';
1193: }
1194: }
1195:
1.344 www 1196: # ------------------------------------------------------ Generate a set of keys
1197:
1198: sub generate_access_keys {
1.364 www 1199: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1200: $cdom=
1.620 albertel 1201: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1202: $cnum=
1.620 albertel 1203: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1204: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1205: unless (($cdom) && ($cnum)) { return 0; }
1206: if ($number>10000) { return 0; }
1207: sleep(2); # make sure don't get same seed twice
1208: srand(time()^($$+($$<<15))); # from "Programming Perl"
1209: my $total=0;
1210: for (my $i=1;$i<=$number;$i++) {
1211: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1212: sprintf("%lx",int(100000*rand)).'-'.
1213: sprintf("%lx",int(100000*rand));
1214: $newkey=~s/1/g/g; # folks mix up 1 and l
1215: $newkey=~s/0/h/g; # and also 0 and O
1216: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1217: if ($existing{$newkey}) {
1218: $i--;
1219: } else {
1.364 www 1220: if (&put('accesskeys',
1221: { $newkey => '# generated '.localtime().
1.620 albertel 1222: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1223: '; '.$logentry },
1224: $cdom,$cnum) eq 'ok') {
1.344 www 1225: $total++;
1226: }
1227: }
1228: }
1.620 albertel 1229: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1230: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1231: return $total;
1232: }
1233:
1234: # ------------------------------------------------------- Validate an accesskey
1235:
1236: sub validate_access_key {
1237: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1238: $cdom=
1.620 albertel 1239: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1240: $cnum=
1.620 albertel 1241: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1242: $udom=$env{'user.domain'} unless (defined($udom));
1243: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1244: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1245: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1246: }
1247:
1248: # ------------------------------------- Find the section of student in a course
1.652 albertel 1249: sub devalidate_getsection_cache {
1250: my ($udom,$unam,$courseid)=@_;
1251: my $hashid="$udom:$unam:$courseid";
1252: &devalidate_cache_new('getsection',$hashid);
1253: }
1.298 matthew 1254:
1.815 albertel 1255: sub courseid_to_courseurl {
1256: my ($courseid) = @_;
1257: #already url style courseid
1258: return $courseid if ($courseid =~ m{^/});
1259:
1260: if (exists($env{'course.'.$courseid.'.num'})) {
1261: my $cnum = $env{'course.'.$courseid.'.num'};
1262: my $cdom = $env{'course.'.$courseid.'.domain'};
1263: return "/$cdom/$cnum";
1264: }
1265:
1266: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1267: if (exists($courseinfo{'num'})) {
1268: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1269: }
1270:
1271: return undef;
1272: }
1273:
1.298 matthew 1274: sub getsection {
1275: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1276: my $cachetime=1800;
1.551 albertel 1277:
1278: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1279: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1280: if (defined($cached)) { return $result; }
1281:
1.298 matthew 1282: my %Pending;
1283: my %Expired;
1284: #
1285: # Each role can either have not started yet (pending), be active,
1286: # or have expired.
1287: #
1288: # If there is an active role, we are done.
1289: #
1290: # If there is more than one role which has not started yet,
1291: # choose the one which will start sooner
1292: # If there is one role which has not started yet, return it.
1293: #
1294: # If there is more than one expired role, choose the one which ended last.
1295: # If there is a role which has expired, return it.
1296: #
1.815 albertel 1297: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1298: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1299: foreach my $key (keys(%roleshash)) {
1.479 albertel 1300: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1301: my $section=$1;
1302: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1303: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1304: my $now=time;
1.548 albertel 1305: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1306: $Expired{$end}=$section;
1307: next;
1308: }
1.548 albertel 1309: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1310: $Pending{$start}=$section;
1311: next;
1312: }
1.599 albertel 1313: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1314: }
1315: #
1316: # Presumedly there will be few matching roles from the above
1317: # loop and the sorting time will be negligible.
1318: if (scalar(keys(%Pending))) {
1319: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1320: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1321: }
1322: if (scalar(keys(%Expired))) {
1323: my @sorted = sort {$a <=> $b} keys(%Expired);
1324: my $time = pop(@sorted);
1.599 albertel 1325: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1326: }
1.599 albertel 1327: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1328: }
1.70 www 1329:
1.599 albertel 1330: sub save_cache {
1331: &purge_remembered();
1.722 albertel 1332: #&Apache::loncommon::validate_page();
1.620 albertel 1333: undef(%env);
1.780 albertel 1334: undef($env_loaded);
1.599 albertel 1335: }
1.452 albertel 1336:
1.599 albertel 1337: my $to_remember=-1;
1338: my %remembered;
1339: my %accessed;
1340: my $kicks=0;
1341: my $hits=0;
1.849 albertel 1342: sub make_key {
1343: my ($name,$id) = @_;
1.872 albertel 1344: if (length($id) > 65
1345: && length(&escape($id)) > 200) {
1346: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1347: }
1.849 albertel 1348: return &escape($name.':'.$id);
1349: }
1350:
1.599 albertel 1351: sub devalidate_cache_new {
1352: my ($name,$id,$debug) = @_;
1353: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1354: $id=&make_key($name,$id);
1.599 albertel 1355: $memcache->delete($id);
1356: delete($remembered{$id});
1357: delete($accessed{$id});
1358: }
1359:
1360: sub is_cached_new {
1361: my ($name,$id,$debug) = @_;
1.849 albertel 1362: $id=&make_key($name,$id);
1.599 albertel 1363: if (exists($remembered{$id})) {
1364: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1365: $accessed{$id}=[&gettimeofday()];
1366: $hits++;
1367: return ($remembered{$id},1);
1368: }
1369: my $value = $memcache->get($id);
1370: if (!(defined($value))) {
1371: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1372: return (undef,undef);
1.416 albertel 1373: }
1.599 albertel 1374: if ($value eq '__undef__') {
1375: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1376: $value=undef;
1377: }
1378: &make_room($id,$value,$debug);
1379: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1380: return ($value,1);
1381: }
1382:
1383: sub do_cache_new {
1384: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1385: $id=&make_key($name,$id);
1.599 albertel 1386: my $setvalue=$value;
1387: if (!defined($setvalue)) {
1388: $setvalue='__undef__';
1389: }
1.623 albertel 1390: if (!defined($time) ) {
1391: $time=600;
1392: }
1.599 albertel 1393: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1394: my $result = $memcache->set($id,$setvalue,$time);
1395: if (! $result) {
1.872 albertel 1396: &logthis("caching of id -> $id failed");
1.910 albertel 1397: $memcache->disconnect_all();
1.872 albertel 1398: }
1.600 albertel 1399: # need to make a copy of $value
1.919 albertel 1400: &make_room($id,$value,$debug);
1.599 albertel 1401: return $value;
1402: }
1403:
1404: sub make_room {
1405: my ($id,$value,$debug)=@_;
1.919 albertel 1406:
1407: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1408: : $value;
1.599 albertel 1409: if ($to_remember<0) { return; }
1410: $accessed{$id}=[&gettimeofday()];
1411: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1412: my $to_kick;
1413: my $max_time=0;
1414: foreach my $other (keys(%accessed)) {
1415: if (&tv_interval($accessed{$other}) > $max_time) {
1416: $to_kick=$other;
1417: $max_time=&tv_interval($accessed{$other});
1418: }
1419: }
1420: delete($remembered{$to_kick});
1421: delete($accessed{$to_kick});
1422: $kicks++;
1423: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1424: return;
1425: }
1426:
1.599 albertel 1427: sub purge_remembered {
1.604 albertel 1428: #&logthis("Tossing ".scalar(keys(%remembered)));
1429: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1430: undef(%remembered);
1431: undef(%accessed);
1.428 albertel 1432: }
1.70 www 1433: # ------------------------------------- Read an entry from a user's environment
1434:
1435: sub userenvironment {
1436: my ($udom,$unam,@what)=@_;
1437: my %returnhash=();
1438: my @answer=split(/\&/,
1439: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
1440: &homeserver($unam,$udom)));
1441: my $i;
1442: for ($i=0;$i<=$#what;$i++) {
1443: $returnhash{$what[$i]}=&unescape($answer[$i]);
1444: }
1445: return %returnhash;
1.1 albertel 1446: }
1447:
1.617 albertel 1448: # ---------------------------------------------------------- Get a studentphoto
1449: sub studentphoto {
1450: my ($udom,$unam,$ext) = @_;
1451: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1452: if (defined($env{'request.course.id'})) {
1.708 raeburn 1453: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1454: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1455: return(&retrievestudentphoto($udom,$unam,$ext));
1456: } else {
1457: my ($result,$perm_reqd)=
1.707 albertel 1458: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1459: if ($result eq 'ok') {
1460: if (!($perm_reqd eq 'yes')) {
1461: return(&retrievestudentphoto($udom,$unam,$ext));
1462: }
1463: }
1464: }
1465: }
1466: } else {
1467: my ($result,$perm_reqd) =
1.707 albertel 1468: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1469: if ($result eq 'ok') {
1470: if (!($perm_reqd eq 'yes')) {
1471: return(&retrievestudentphoto($udom,$unam,$ext));
1472: }
1473: }
1474: }
1475: return '/adm/lonKaputt/lonlogo_broken.gif';
1476: }
1477:
1478: sub retrievestudentphoto {
1479: my ($udom,$unam,$ext,$type) = @_;
1480: my $home=&Apache::lonnet::homeserver($unam,$udom);
1481: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1482: if ($ret eq 'ok') {
1483: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1484: if ($type eq 'thumbnail') {
1485: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1486: }
1487: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1488: return $tokenurl;
1489: } else {
1490: if ($type eq 'thumbnail') {
1491: return '/adm/lonKaputt/genericstudent_tn.gif';
1492: } else {
1493: return '/adm/lonKaputt/lonlogo_broken.gif';
1494: }
1.617 albertel 1495: }
1496: }
1497:
1.263 www 1498: # -------------------------------------------------------------------- New chat
1499:
1500: sub chatsend {
1.724 raeburn 1501: my ($newentry,$anon,$group)=@_;
1.620 albertel 1502: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1503: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1504: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1505: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1506: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1507: &escape($newentry)).':'.$group,$chome);
1.292 www 1508: }
1509:
1510: # ------------------------------------------ Find current version of a resource
1511:
1512: sub getversion {
1513: my $fname=&clutter(shift);
1514: unless ($fname=~/^\/res\//) { return -1; }
1515: return ¤tversion(&filelocation('',$fname));
1516: }
1517:
1518: sub currentversion {
1519: my $fname=shift;
1.599 albertel 1520: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1521: if (defined($cached)) { return $result; }
1.292 www 1522: my $author=$fname;
1523: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1524: my ($udom,$uname)=split(/\//,$author);
1525: my $home=homeserver($uname,$udom);
1526: if ($home eq 'no_host') {
1527: return -1;
1528: }
1529: my $answer=reply("currentversion:$fname",$home);
1530: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1531: return -1;
1532: }
1.599 albertel 1533: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1534: }
1535:
1.1 albertel 1536: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1537:
1.1 albertel 1538: sub subscribe {
1539: my $fname=shift;
1.761 raeburn 1540: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1541: $fname=~s/[\n\r]//g;
1.1 albertel 1542: my $author=$fname;
1543: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1544: my ($udom,$uname)=split(/\//,$author);
1545: my $home=homeserver($uname,$udom);
1.335 albertel 1546: if ($home eq 'no_host') {
1547: return 'not_found';
1.1 albertel 1548: }
1549: my $answer=reply("sub:$fname",$home);
1.64 www 1550: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1551: $answer.=' by '.$home;
1552: }
1.1 albertel 1553: return $answer;
1554: }
1555:
1.8 www 1556: # -------------------------------------------------------------- Replicate file
1557:
1558: sub repcopy {
1559: my $filename=shift;
1.23 www 1560: $filename=~s/\/+/\//g;
1.607 raeburn 1561: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1562: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1563: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1564: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1565: return &repcopy_userfile($filename);
1566: }
1.532 albertel 1567: $filename=~s/[\n\r]//g;
1.8 www 1568: my $transname="$filename.in.transfer";
1.828 www 1569: # FIXME: this should flock
1.607 raeburn 1570: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1571: my $remoteurl=subscribe($filename);
1.64 www 1572: if ($remoteurl =~ /^con_lost by/) {
1573: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1574: return 'unavailable';
1.8 www 1575: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1576: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1577: return 'not_found';
1.64 www 1578: } elsif ($remoteurl =~ /^rejected by/) {
1579: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1580: return 'forbidden';
1.20 www 1581: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1582: return 'ok';
1.8 www 1583: } else {
1.290 www 1584: my $author=$filename;
1585: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1586: my ($udom,$uname)=split(/\//,$author);
1587: my $home=homeserver($uname,$udom);
1588: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1589: my @parts=split(/\//,$filename);
1590: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1591: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1592: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1593: return 'bad_request';
1.8 www 1594: }
1595: my $count;
1596: for ($count=5;$count<$#parts;$count++) {
1597: $path.="/$parts[$count]";
1598: if ((-e $path)!=1) {
1599: mkdir($path,0777);
1600: }
1601: }
1602: my $ua=new LWP::UserAgent;
1603: my $request=new HTTP::Request('GET',"$remoteurl");
1604: my $response=$ua->request($request,$transname);
1605: if ($response->is_error()) {
1606: unlink($transname);
1607: my $message=$response->status_line;
1.672 albertel 1608: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1609: ." LWP get: $message: $filename</font>");
1.607 raeburn 1610: return 'unavailable';
1.8 www 1611: } else {
1.16 www 1612: if ($remoteurl!~/\.meta$/) {
1613: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1614: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1615: if ($mresponse->is_error()) {
1616: unlink($filename.'.meta');
1617: &logthis(
1.672 albertel 1618: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1619: }
1620: }
1.8 www 1621: rename($transname,$filename);
1.607 raeburn 1622: return 'ok';
1.8 www 1623: }
1.290 www 1624: }
1.8 www 1625: }
1.330 www 1626: }
1627:
1628: # ------------------------------------------------ Get server side include body
1629: sub ssi_body {
1.381 albertel 1630: my ($filelink,%form)=@_;
1.606 matthew 1631: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1632: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1633: }
1.330 www 1634: my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381 albertel 1635: &ssi($filelink,%form));
1.778 albertel 1636: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1637: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 1638: $output=~s/\<\/body\s*\>.*?$//si;
1.330 www 1639: return $output;
1.8 www 1640: }
1641:
1.15 www 1642: # --------------------------------------------------------- Server Side Include
1643:
1.782 albertel 1644: sub absolute_url {
1645: my ($host_name) = @_;
1646: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1647: if ($host_name eq '') {
1648: $host_name = $ENV{'SERVER_NAME'};
1649: }
1650: return $protocol.$host_name;
1651: }
1652:
1.15 www 1653: sub ssi {
1654:
1.23 www 1655: my ($fn,%form)=@_;
1.15 www 1656:
1657: my $ua=new LWP::UserAgent;
1.23 www 1658:
1659: my $request;
1.711 albertel 1660:
1661: $form{'no_update_last_known'}=1;
1.895 albertel 1662: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 1663: if (%form) {
1.782 albertel 1664: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201 albertel 1665: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23 www 1666: } else {
1.782 albertel 1667: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1668: }
1669:
1.15 www 1670: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1671: my $response=$ua->request($request);
1672:
1.324 www 1673: return $response->content;
1674: }
1675:
1676: sub externalssi {
1677: my ($url)=@_;
1678: my $ua=new LWP::UserAgent;
1679: my $request=new HTTP::Request('GET',$url);
1680: my $response=$ua->request($request);
1.15 www 1681: return $response->content;
1682: }
1.254 www 1683:
1.492 albertel 1684: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1685:
1686: sub allowuploaded {
1687: my ($srcurl,$url)=@_;
1688: $url=&clutter(&declutter($url));
1689: my $dir=$url;
1690: $dir=~s/\/[^\/]+$//;
1691: my %httpref=();
1692: my $httpurl=&hreflocation('',$url);
1693: $httpref{'httpref.'.$httpurl}=$srcurl;
1694: &Apache::lonnet::appenv(%httpref);
1.254 www 1695: }
1.477 raeburn 1696:
1.478 albertel 1697: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1698: # input: action, courseID, current domain, intended
1.637 raeburn 1699: # path to file, source of file, instruction to parse file for objects,
1700: # ref to hash for embedded objects,
1701: # ref to hash for codebase of java objects.
1702: #
1.485 raeburn 1703: # output: url to file (if action was uploaddoc),
1704: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 1705: #
1.478 albertel 1706: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1707: # course.
1.477 raeburn 1708: #
1.478 albertel 1709: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1710: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1711: # course's home server.
1.477 raeburn 1712: #
1.478 albertel 1713: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1714: # be copied from $source (current location) to
1715: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1716: # and will then be copied to
1717: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1718: # course's home server.
1.485 raeburn 1719: #
1.481 raeburn 1720: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 1721: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 1722: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1723: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1724: # in course's home server.
1.637 raeburn 1725: #
1.477 raeburn 1726:
1727: sub process_coursefile {
1.638 albertel 1728: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 1729: my $fetchresult;
1.638 albertel 1730: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 1731: if ($action eq 'propagate') {
1.638 albertel 1732: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1733: $home);
1.481 raeburn 1734: } else {
1.477 raeburn 1735: my $fpath = '';
1736: my $fname = $file;
1.478 albertel 1737: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 1738: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 1739: my $filepath = &build_filepath($fpath);
1.481 raeburn 1740: if ($action eq 'copy') {
1741: if ($source eq '') {
1742: $fetchresult = 'no source file';
1743: return $fetchresult;
1744: } else {
1745: my $destination = $filepath.'/'.$fname;
1746: rename($source,$destination);
1747: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1748: $home);
1.481 raeburn 1749: }
1750: } elsif ($action eq 'uploaddoc') {
1751: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 1752: print $fh $env{'form.'.$source};
1.481 raeburn 1753: close($fh);
1.637 raeburn 1754: if ($parser eq 'parse') {
1755: my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
1756: unless ($parse_result eq 'ok') {
1757: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1758: }
1759: }
1.477 raeburn 1760: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1761: $home);
1.481 raeburn 1762: if ($fetchresult eq 'ok') {
1763: return '/uploaded/'.$fpath.'/'.$fname;
1764: } else {
1765: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1766: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 1767: return '/adm/notfound.html';
1768: }
1.477 raeburn 1769: }
1770: }
1.485 raeburn 1771: unless ( $fetchresult eq 'ok') {
1.477 raeburn 1772: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1773: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 1774: }
1775: return $fetchresult;
1776: }
1777:
1.637 raeburn 1778: sub build_filepath {
1779: my ($fpath) = @_;
1780: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1781: unless ($fpath eq '') {
1782: my @parts=split('/',$fpath);
1783: foreach my $part (@parts) {
1784: $filepath.= '/'.$part;
1785: if ((-e $filepath)!=1) {
1786: mkdir($filepath,0777);
1787: }
1788: }
1789: }
1790: return $filepath;
1791: }
1792:
1793: sub store_edited_file {
1.638 albertel 1794: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 1795: my $file = $primary_url;
1796: $file =~ s#^/uploaded/$docudom/$docuname/##;
1797: my $fpath = '';
1798: my $fname = $file;
1799: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1800: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1801: my $filepath = &build_filepath($fpath);
1802: open(my $fh,'>'.$filepath.'/'.$fname);
1803: print $fh $content;
1804: close($fh);
1.638 albertel 1805: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 1806: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1807: $home);
1.637 raeburn 1808: if ($$fetchresult eq 'ok') {
1809: return '/uploaded/'.$fpath.'/'.$fname;
1810: } else {
1.638 albertel 1811: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1812: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 1813: return '/adm/notfound.html';
1814: }
1815: }
1816:
1.531 albertel 1817: sub clean_filename {
1.831 albertel 1818: my ($fname,$args)=@_;
1.315 www 1819: # Replace Windows backslashes by forward slashes
1.257 www 1820: $fname=~s/\\/\//g;
1.831 albertel 1821: if (!$args->{'keep_path'}) {
1822: # Get rid of everything but the actual filename
1823: $fname=~s/^.*\/([^\/]+)$/$1/;
1824: }
1.315 www 1825: # Replace spaces by underscores
1826: $fname=~s/\s+/\_/g;
1827: # Replace all other weird characters by nothing
1.831 albertel 1828: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 1829: # Replace all .\d. sequences with _\d. so they no longer look like version
1830: # numbers
1831: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 1832: return $fname;
1833: }
1834:
1.608 albertel 1835: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 1836: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 1837: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 1838: # $coursedoc - if true up to the current course
1839: # if false
1840: # $subdir - directory in userfile to store the file into
1.858 raeburn 1841: # $parser - instruction to parse file for objects ($parser = parse)
1842: # $allfiles - reference to hash for embedded objects
1843: # $codebase - reference to hash for codebase of java objects
1844: # $desuname - username for permanent storage of uploaded file
1845: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 1846: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
1847: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858 raeburn 1848: #
1.686 albertel 1849: # output: url of file in userspace, or error: <message>
1850: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 1851:
1852:
1.531 albertel 1853: sub userfileupload {
1.860 raeburn 1854: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1855: $destudom,$thumbwidth,$thumbheight)=@_;
1.531 albertel 1856: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 1857: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 1858: $fname=&clean_filename($fname);
1.315 www 1859: # See if there is anything left
1.257 www 1860: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 1861: chop($env{'form.'.$formname});
1.523 raeburn 1862: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
1863: my $now = time;
1864: my $filepath = 'tmp/helprequests/'.$now;
1865: my @parts=split(/\//,$filepath);
1866: my $fullpath = $perlvar{'lonDaemons'};
1867: for (my $i=0;$i<@parts;$i++) {
1868: $fullpath .= '/'.$parts[$i];
1869: if ((-e $fullpath)!=1) {
1870: mkdir($fullpath,0777);
1871: }
1872: }
1873: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 1874: print $fh $env{'form.'.$formname};
1.523 raeburn 1875: close($fh);
1.741 raeburn 1876: return $fullpath.'/'.$fname;
1877: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
1878: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
1879: '_'.$env{'user.domain'}.'/pending';
1880: my @parts=split(/\//,$filepath);
1881: my $fullpath = $perlvar{'lonDaemons'};
1882: for (my $i=0;$i<@parts;$i++) {
1883: $fullpath .= '/'.$parts[$i];
1884: if ((-e $fullpath)!=1) {
1885: mkdir($fullpath,0777);
1886: }
1887: }
1888: open(my $fh,'>'.$fullpath.'/'.$fname);
1889: print $fh $env{'form.'.$formname};
1890: close($fh);
1891: return $fullpath.'/'.$fname;
1.523 raeburn 1892: }
1.719 banghart 1893:
1.258 www 1894: # Create the directory if not present
1.493 albertel 1895: $fname="$subdir/$fname";
1.259 www 1896: if ($coursedoc) {
1.638 albertel 1897: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1898: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 1899: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 1900: return &finishuserfileupload($docuname,$docudom,
1901: $formname,$fname,$parser,$allfiles,
1.860 raeburn 1902: $codebase,$thumbwidth,$thumbheight);
1.481 raeburn 1903: } else {
1.620 albertel 1904: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 1905: return &process_coursefile('uploaddoc',$docuname,$docudom,
1906: $fname,$formname,$parser,
1907: $allfiles,$codebase);
1.481 raeburn 1908: }
1.719 banghart 1909: } elsif (defined($destuname)) {
1910: my $docuname=$destuname;
1911: my $docudom=$destudom;
1.860 raeburn 1912: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
1913: $parser,$allfiles,$codebase,
1914: $thumbwidth,$thumbheight);
1.719 banghart 1915:
1.259 www 1916: } else {
1.638 albertel 1917: my $docuname=$env{'user.name'};
1918: my $docudom=$env{'user.domain'};
1.714 raeburn 1919: if (exists($env{'form.group'})) {
1920: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1921: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1922: }
1.860 raeburn 1923: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
1924: $parser,$allfiles,$codebase,
1925: $thumbwidth,$thumbheight);
1.259 www 1926: }
1.271 www 1927: }
1928:
1929: sub finishuserfileupload {
1.860 raeburn 1930: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1931: $thumbwidth,$thumbheight) = @_;
1.477 raeburn 1932: my $path=$docudom.'/'.$docuname.'/';
1.258 www 1933: my $filepath=$perlvar{'lonDocRoot'};
1.860 raeburn 1934: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 1935: $file=$fname;
1936: if ($fname=~m|/|) {
1937: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
1938: $path.=$fnamepath.'/';
1939: }
1.259 www 1940: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 1941: my $count;
1942: for ($count=4;$count<=$#parts;$count++) {
1943: $filepath.="/$parts[$count]";
1944: if ((-e $filepath)!=1) {
1945: mkdir($filepath,0777);
1946: }
1947: }
1948: # Save the file
1949: {
1.701 albertel 1950: if (!open(FH,'>'.$filepath.'/'.$file)) {
1951: &logthis('Failed to create '.$filepath.'/'.$file);
1952: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
1953: return '/adm/notfound.html';
1954: }
1955: if (!print FH ($env{'form.'.$formname})) {
1956: &logthis('Failed to write to '.$filepath.'/'.$file);
1957: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
1958: return '/adm/notfound.html';
1959: }
1.570 albertel 1960: close(FH);
1.258 www 1961: }
1.637 raeburn 1962: if ($parser eq 'parse') {
1.638 albertel 1963: my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
1964: $codebase);
1.637 raeburn 1965: unless ($parse_result eq 'ok') {
1.638 albertel 1966: &logthis('Failed to parse '.$filepath.$file.
1967: ' for embedded media: '.$parse_result);
1.637 raeburn 1968: }
1969: }
1.860 raeburn 1970: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
1971: my $input = $filepath.'/'.$file;
1972: my $output = $filepath.'/'.'tn-'.$file;
1973: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1974: system("convert -sample $thumbsize $input $output");
1975: if (-e $filepath.'/'.'tn-'.$file) {
1976: $fetchthumb = 1;
1977: }
1978: }
1.858 raeburn 1979:
1.259 www 1980: # Notify homeserver to grep it
1981: #
1.638 albertel 1982: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 1983: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 1984: if ($fetchresult eq 'ok') {
1.860 raeburn 1985: if ($fetchthumb) {
1986: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
1987: if ($thumbresult ne 'ok') {
1988: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
1989: $docuhome.': '.$thumbresult);
1990: }
1991: }
1.259 www 1992: #
1.258 www 1993: # Return the URL to it
1.494 albertel 1994: return '/uploaded/'.$path.$file;
1.263 www 1995: } else {
1.494 albertel 1996: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
1997: ': '.$fetchresult);
1.263 www 1998: return '/adm/notfound.html';
1.858 raeburn 1999: }
1.493 albertel 2000: }
2001:
1.637 raeburn 2002: sub extract_embedded_items {
1.648 raeburn 2003: my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2004: my @state = ();
2005: my %javafiles = (
2006: codebase => '',
2007: code => '',
2008: archive => ''
2009: );
2010: my %mediafiles = (
2011: src => '',
2012: movie => '',
2013: );
1.648 raeburn 2014: my $p;
2015: if ($content) {
2016: $p = HTML::LCParser->new($content);
2017: } else {
2018: $p = HTML::LCParser->new($filepath.'/'.$file);
2019: }
1.641 albertel 2020: while (my $t=$p->get_token()) {
1.640 albertel 2021: if ($t->[0] eq 'S') {
2022: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2023: push(@state, $tagname);
1.648 raeburn 2024: if (lc($tagname) eq 'allow') {
2025: &add_filetype($allfiles,$attr->{'src'},'src');
2026: }
1.640 albertel 2027: if (lc($tagname) eq 'img') {
2028: &add_filetype($allfiles,$attr->{'src'},'src');
2029: }
1.886 albertel 2030: if (lc($tagname) eq 'a') {
2031: &add_filetype($allfiles,$attr->{'href'},'href');
2032: }
1.645 raeburn 2033: if (lc($tagname) eq 'script') {
2034: if ($attr->{'archive'} =~ /\.jar$/i) {
2035: &add_filetype($allfiles,$attr->{'archive'},'archive');
2036: } else {
2037: &add_filetype($allfiles,$attr->{'src'},'src');
2038: }
2039: }
2040: if (lc($tagname) eq 'link') {
2041: if (lc($attr->{'rel'}) eq 'stylesheet') {
2042: &add_filetype($allfiles,$attr->{'href'},'href');
2043: }
2044: }
1.640 albertel 2045: if (lc($tagname) eq 'object' ||
2046: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2047: foreach my $item (keys(%javafiles)) {
2048: $javafiles{$item} = '';
2049: }
2050: }
2051: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2052: my $name = lc($attr->{'name'});
2053: foreach my $item (keys(%javafiles)) {
2054: if ($name eq $item) {
2055: $javafiles{$item} = $attr->{'value'};
2056: last;
2057: }
2058: }
2059: foreach my $item (keys(%mediafiles)) {
2060: if ($name eq $item) {
2061: &add_filetype($allfiles, $attr->{'value'}, 'value');
2062: last;
2063: }
2064: }
2065: }
2066: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2067: foreach my $item (keys(%javafiles)) {
2068: if ($attr->{$item}) {
2069: $javafiles{$item} = $attr->{$item};
2070: last;
2071: }
2072: }
2073: foreach my $item (keys(%mediafiles)) {
2074: if ($attr->{$item}) {
2075: &add_filetype($allfiles,$attr->{$item},$item);
2076: last;
2077: }
2078: }
2079: }
2080: } elsif ($t->[0] eq 'E') {
2081: my ($tagname) = ($t->[1]);
2082: if ($javafiles{'codebase'} ne '') {
2083: $javafiles{'codebase'} .= '/';
2084: }
2085: if (lc($tagname) eq 'applet' ||
2086: lc($tagname) eq 'object' ||
2087: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2088: ) {
2089: foreach my $item (keys(%javafiles)) {
2090: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2091: my $file=$javafiles{'codebase'}.$javafiles{$item};
2092: &add_filetype($allfiles,$file,$item);
2093: }
2094: }
2095: }
2096: pop @state;
2097: }
2098: }
1.637 raeburn 2099: return 'ok';
2100: }
2101:
1.639 albertel 2102: sub add_filetype {
2103: my ($allfiles,$file,$type)=@_;
2104: if (exists($allfiles->{$file})) {
2105: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2106: push(@{$allfiles->{$file}}, &escape($type));
2107: }
2108: } else {
2109: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2110: }
2111: }
2112:
1.493 albertel 2113: sub removeuploadedurl {
2114: my ($url)=@_;
2115: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2116: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2117: }
2118:
2119: sub removeuserfile {
2120: my ($docuname,$docudom,$fname)=@_;
2121: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2122: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
2123: if ($result eq 'ok') {
2124: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2125: my $metafile = $fname.'.meta';
2126: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2127: my $url = "/uploaded/$docudom/$docuname/$fname";
2128: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2129: my $sqlresult =
1.823 albertel 2130: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2131: 'portfolio_metadata',$group,
2132: 'delete');
1.798 raeburn 2133: }
2134: }
2135: return $result;
1.257 www 2136: }
1.15 www 2137:
1.530 albertel 2138: sub mkdiruserfile {
2139: my ($docuname,$docudom,$dir)=@_;
2140: my $home=&homeserver($docuname,$docudom);
2141: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2142: }
2143:
1.531 albertel 2144: sub renameuserfile {
2145: my ($docuname,$docudom,$old,$new)=@_;
2146: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2147: my $result = &reply("renameuserfile:$docudom:$docuname:".
2148: &escape("$old").':'.&escape("$new"),$home);
2149: if ($result eq 'ok') {
2150: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2151: my $oldmeta = $old.'.meta';
2152: my $newmeta = $new.'.meta';
2153: my $metaresult =
2154: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2155: my $url = "/uploaded/$docudom/$docuname/$old";
2156: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2157: my $sqlresult =
1.823 albertel 2158: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2159: 'portfolio_metadata',$group,
2160: 'delete');
1.798 raeburn 2161: }
2162: }
2163: return $result;
1.531 albertel 2164: }
2165:
1.14 www 2166: # ------------------------------------------------------------------------- Log
2167:
2168: sub log {
2169: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2170: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2171: }
2172:
2173: # ------------------------------------------------------------------ Course Log
1.352 www 2174: #
2175: # This routine flushes several buffers of non-mission-critical nature
2176: #
1.157 www 2177:
2178: sub flushcourselogs {
1.352 www 2179: &logthis('Flushing log buffers');
2180: #
2181: # course logs
2182: # This is a log of all transactions in a course, which can be used
2183: # for data mining purposes
2184: #
2185: # It also collects the courseid database, which lists last transaction
2186: # times and course titles for all courseids
2187: #
2188: my %courseidbuffer=();
1.921 raeburn 2189: foreach my $crsid (keys(%courselogs)) {
1.352 www 2190: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2191: &escape($courselogs{$crsid}),
2192: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2193: delete $courselogs{$crsid};
2194: } else {
2195: &logthis('Failed to flush log buffer for '.$crsid);
2196: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2197: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2198: " exceeded maximum size, deleting.</font>");
2199: delete $courselogs{$crsid};
2200: }
1.352 www 2201: }
1.920 raeburn 2202: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.918 raeburn 2203: 'description' => &escape($coursedescrbuf{$crsid}),
1.921 raeburn 2204: 'inst_code' => &escape($courseinstcodebuf{$crsid}),
1.918 raeburn 2205: 'type' => &escape($coursetypebuf{$crsid}),
2206: 'owner' => &escape($courseownerbuf{$crsid}),
1.920 raeburn 2207: };
1.191 harris41 2208: }
1.352 www 2209: #
2210: # Write course id database (reverse lookup) to homeserver of courses
2211: # Is used in pickcourse
2212: #
1.840 albertel 2213: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2214: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2215: $courseidbuffer{$crs_home},
2216: $crs_home,'timeonly');
1.352 www 2217: }
2218: #
2219: # File accesses
2220: # Writes to the dynamic metadata of resources to get hit counts, etc.
2221: #
1.449 matthew 2222: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2223: if ($entry =~ /___count$/) {
2224: my ($dom,$name);
1.807 albertel 2225: ($dom,$name,undef)=
1.811 albertel 2226: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2227: if (! defined($dom) || $dom eq '' ||
2228: ! defined($name) || $name eq '') {
1.620 albertel 2229: my $cid = $env{'request.course.id'};
2230: $dom = $env{'request.'.$cid.'.domain'};
2231: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2232: }
1.450 matthew 2233: my $value = $accesshash{$entry};
2234: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2235: my %temphash=($url => $value);
1.449 matthew 2236: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2237: if ($result eq 'ok') {
2238: delete $accesshash{$entry};
2239: } elsif ($result eq 'unknown_cmd') {
2240: # Target server has old code running on it.
1.450 matthew 2241: my %temphash=($entry => $value);
1.449 matthew 2242: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2243: delete $accesshash{$entry};
2244: }
2245: }
2246: } else {
1.811 albertel 2247: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2248: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2249: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2250: delete $accesshash{$entry};
2251: }
1.185 www 2252: }
1.191 harris41 2253: }
1.352 www 2254: #
2255: # Roles
2256: # Reverse lookup of user roles for course faculty/staff and co-authorship
2257: #
1.800 albertel 2258: foreach my $entry (keys(%userrolehash)) {
1.351 www 2259: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2260: split(/\:/,$entry);
2261: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2262: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2263: $rudom,$runame) eq 'ok') {
2264: delete $userrolehash{$entry};
2265: }
2266: }
1.662 raeburn 2267: #
2268: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2269: #
2270: my %domrolebuffer = ();
2271: foreach my $entry (keys %domainrolehash) {
1.901 albertel 2272: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2273: if ($domrolebuffer{$rudom}) {
2274: $domrolebuffer{$rudom}.='&'.&escape($entry).
2275: '='.&escape($domainrolehash{$entry});
2276: } else {
2277: $domrolebuffer{$rudom}.=&escape($entry).
2278: '='.&escape($domainrolehash{$entry});
2279: }
2280: delete $domainrolehash{$entry};
2281: }
2282: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2283: my %servers = &get_servers($dom,'library');
2284: foreach my $tryserver (keys(%servers)) {
2285: unless (&reply('domroleput:'.$dom.':'.
2286: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2287: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2288: }
1.662 raeburn 2289: }
2290: }
1.186 www 2291: $dumpcount++;
1.157 www 2292: }
2293:
2294: sub courselog {
2295: my $what=shift;
1.158 www 2296: $what=time.':'.$what;
1.620 albertel 2297: unless ($env{'request.course.id'}) { return ''; }
2298: $coursedombuf{$env{'request.course.id'}}=
2299: $env{'course.'.$env{'request.course.id'}.'.domain'};
2300: $coursenumbuf{$env{'request.course.id'}}=
2301: $env{'course.'.$env{'request.course.id'}.'.num'};
2302: $coursehombuf{$env{'request.course.id'}}=
2303: $env{'course.'.$env{'request.course.id'}.'.home'};
2304: $coursedescrbuf{$env{'request.course.id'}}=
2305: $env{'course.'.$env{'request.course.id'}.'.description'};
2306: $courseinstcodebuf{$env{'request.course.id'}}=
2307: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2308: $courseownerbuf{$env{'request.course.id'}}=
2309: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2310: $coursetypebuf{$env{'request.course.id'}}=
2311: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2312: if (defined $courselogs{$env{'request.course.id'}}) {
2313: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2314: } else {
1.620 albertel 2315: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2316: }
1.620 albertel 2317: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2318: &flushcourselogs();
2319: }
1.158 www 2320: }
2321:
2322: sub courseacclog {
2323: my $fnsymb=shift;
1.620 albertel 2324: unless ($env{'request.course.id'}) { return ''; }
2325: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2326: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2327: $what.=':POST';
1.583 matthew 2328: # FIXME: Probably ought to escape things....
1.800 albertel 2329: foreach my $key (keys(%env)) {
2330: if ($key=~/^form\.(.*)/) {
2331: $what.=':'.$1.'='.$env{$key};
1.158 www 2332: }
1.191 harris41 2333: }
1.583 matthew 2334: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2335: # FIXME: We should not be depending on a form parameter that someone
2336: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2337: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2338: $what.= ':POST';
2339: # FIXME: Probably ought to escape things....
2340: foreach my $element ('courseexp','crsfulltext','crsrelated',
2341: 'crsdiscuss') {
1.620 albertel 2342: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2343: }
2344: }
1.158 www 2345: }
2346: &courselog($what);
1.149 www 2347: }
2348:
1.185 www 2349: sub countacc {
2350: my $url=&declutter(shift);
1.458 matthew 2351: return if (! defined($url) || $url eq '');
1.620 albertel 2352: unless ($env{'request.course.id'}) { return ''; }
2353: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2354: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2355: $accesshash{$key}++;
1.185 www 2356: }
1.349 www 2357:
1.361 www 2358: sub linklog {
2359: my ($from,$to)=@_;
2360: $from=&declutter($from);
2361: $to=&declutter($to);
2362: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2363: $accesshash{$to.'___'.$from.'___goto'}=1;
2364: }
2365:
1.349 www 2366: sub userrolelog {
2367: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2368: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2369: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2370: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2371: ($trole=~/^ta/)) {
1.350 www 2372: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2373: $userrolehash
2374: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2375: =$tend.':'.$tstart;
1.662 raeburn 2376: }
1.898 albertel 2377: if (($env{'request.role'} =~ /dc\./) &&
2378: (($trole=~/^au/) || ($trole=~/^in/) ||
2379: ($trole=~/^cc/) || ($trole=~/^ep/) ||
2380: ($trole=~/^cr/) || ($trole=~/^ta/))) {
2381: $userrolehash
2382: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2383: =$tend.':'.$tstart;
2384: }
1.662 raeburn 2385: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2386: ($trole=~/^li/) || ($trole=~/^li/) ||
2387: ($trole=~/^au/) || ($trole=~/^dg/) ||
2388: ($trole=~/^sc/)) {
2389: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2390: $domainrolehash
2391: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2392: = $tend.':'.$tstart;
2393: }
1.351 www 2394: }
2395:
2396: sub get_course_adv_roles {
2397: my $cid=shift;
1.620 albertel 2398: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2399: my %coursehash=&coursedescription($cid);
1.470 www 2400: my %nothide=();
1.800 albertel 2401: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2402: $nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470 www 2403: }
1.351 www 2404: my %returnhash=();
2405: my %dumphash=
2406: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2407: my $now=time;
1.800 albertel 2408: foreach my $entry (keys %dumphash) {
2409: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2410: if (($tstart) && ($tstart<0)) { next; }
2411: if (($tend) && ($tend<$now)) { next; }
2412: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2413: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2414: if ($username eq '' || $domain eq '') { next; }
1.470 www 2415: if ((&privileged($username,$domain)) &&
2416: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2417: if ($role eq 'cr') { next; }
1.351 www 2418: my $key=&plaintext($role);
2419: if ($section) { $key.=' (Sec/Grp '.$section.')'; }
2420: if ($returnhash{$key}) {
2421: $returnhash{$key}.=','.$username.':'.$domain;
2422: } else {
2423: $returnhash{$key}=$username.':'.$domain;
2424: }
1.400 www 2425: }
2426: return %returnhash;
2427: }
2428:
2429: sub get_my_roles {
1.858 raeburn 2430: my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620 albertel 2431: unless (defined($uname)) { $uname=$env{'user.name'}; }
2432: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858 raeburn 2433: my %dumphash;
2434: if ($context eq 'userroles') {
2435: %dumphash = &dump('roles',$udom,$uname);
2436: } else {
2437: %dumphash=
1.400 www 2438: &dump('nohist_userroles',$udom,$uname);
1.858 raeburn 2439: }
1.400 www 2440: my %returnhash=();
2441: my $now=time;
1.800 albertel 2442: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2443: my ($role,$tend,$tstart);
2444: if ($context eq 'userroles') {
2445: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2446: } else {
2447: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2448: }
1.400 www 2449: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2450: my $status = 'active';
2451: if (($tend) && ($tend<$now)) {
2452: $status = 'previous';
2453: }
2454: if (($tstart) && ($now<$tstart)) {
2455: $status = 'future';
2456: }
2457: if (ref($types) eq 'ARRAY') {
2458: if (!grep(/^\Q$status\E$/,@{$types})) {
2459: next;
2460: }
2461: } else {
2462: if ($status ne 'active') {
2463: next;
2464: }
2465: }
1.867 raeburn 2466: my ($rolecode,$username,$domain,$section,$area);
2467: if ($context eq 'userroles') {
2468: ($area,$rolecode) = split(/_/,$entry);
2469: (undef,$domain,$username,$section) = split(/\//,$area);
2470: } else {
2471: ($role,$username,$domain,$section) = split(/\:/,$entry);
2472: }
1.832 raeburn 2473: if (ref($roledoms) eq 'ARRAY') {
2474: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2475: next;
2476: }
2477: }
2478: if (ref($roles) eq 'ARRAY') {
2479: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 2480: if ($role =~ /^cr\//) {
2481: if (!grep(/^cr$/,@{$roles})) {
2482: next;
2483: }
2484: } else {
2485: next;
2486: }
1.832 raeburn 2487: }
1.867 raeburn 2488: }
1.400 www 2489: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832 raeburn 2490: }
1.373 www 2491: return %returnhash;
1.399 www 2492: }
2493:
2494: # ----------------------------------------------------- Frontpage Announcements
2495: #
2496: #
2497:
2498: sub postannounce {
2499: my ($server,$text)=@_;
1.844 albertel 2500: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2501: unless ($text=~/\w/) { $text=''; }
2502: return &reply('setannounce:'.&escape($text),$server);
2503: }
2504:
2505: sub getannounce {
1.448 albertel 2506:
2507: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 2508: my $announcement='';
1.800 albertel 2509: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 2510: close($fh);
1.399 www 2511: if ($announcement=~/\w/) {
2512: return
2513: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 2514: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 2515: } else {
2516: return '';
2517: }
2518: } else {
2519: return '';
2520: }
1.351 www 2521: }
1.353 www 2522:
2523: # ---------------------------------------------------------- Course ID routines
2524: # Deal with domain's nohist_courseid.db files
2525: #
2526:
2527: sub courseidput {
1.921 raeburn 2528: my ($domain,$storehash,$coursehome,$caller) = @_;
2529: my $outcome;
2530: if ($caller eq 'timeonly') {
2531: my $cids = '';
2532: foreach my $item (keys(%$storehash)) {
2533: $cids.=&escape($item).'&';
2534: }
2535: $cids=~s/\&$//;
2536: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
2537: $coursehome);
2538: } else {
2539: my $items = '';
2540: foreach my $item (keys(%$storehash)) {
2541: $items.= &escape($item).'='.
2542: &freeze_escape($$storehash{$item}).'&';
2543: }
2544: $items=~s/\&$//;
2545: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
2546: $coursehome);
1.918 raeburn 2547: }
2548: if ($outcome eq 'unknown_cmd') {
2549: my $what;
2550: foreach my $cid (keys(%$storehash)) {
2551: $what .= &escape($cid).'=';
1.921 raeburn 2552: foreach my $item ('description','inst_code','owner','type') {
2553: $what .= &escape($storehash->{$item}).':';
1.918 raeburn 2554: }
2555: $what =~ s/\:$/&/;
2556: }
2557: $what =~ s/\&$//;
2558: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2559: } else {
2560: return $outcome;
2561: }
1.353 www 2562: }
2563:
2564: sub courseiddump {
1.921 raeburn 2565: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
2566: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.918 raeburn 2567: my $as_hash = 1;
2568: my %returnhash;
2569: if (!$domfilter) { $domfilter=''; }
1.845 albertel 2570: my %libserv = &all_library();
2571: foreach my $tryserver (keys(%libserv)) {
2572: if ( ( $hostidflag == 1
2573: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
2574: || (!defined($hostidflag)) ) {
2575:
1.918 raeburn 2576: if (($domfilter eq '') ||
2577: (&host_domain($tryserver) eq $domfilter)) {
2578: my $rep =
2579: &reply('courseiddump:'.&host_domain($tryserver).':'.
2580: $sincefilter.':'.&escape($descfilter).':'.
2581: &escape($instcodefilter).':'.&escape($ownerfilter).
2582: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.921 raeburn 2583: ':'.&escape($regexp_ok).':'.$as_hash,$tryserver);
1.918 raeburn 2584: my @pairs=split(/\&/,$rep);
2585: foreach my $item (@pairs) {
2586: my ($key,$value)=split(/\=/,$item,2);
2587: $key = &unescape($key);
2588: next if ($key =~ /^error: 2 /);
2589: my $result = &thaw_unescape($value);
2590: if (ref($result) eq 'HASH') {
2591: $returnhash{$key}=$result;
2592: } else {
1.921 raeburn 2593: my @responses = split(/:/,$value);
2594: my @items = ('description','inst_code','owner','type');
1.918 raeburn 2595: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 2596: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 2597: }
2598: }
1.353 www 2599: }
2600: }
2601: }
2602: }
2603: return %returnhash;
2604: }
2605:
1.658 raeburn 2606: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 2607:
2608: sub dcmailput {
1.685 raeburn 2609: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 2610: my $status = &Apache::lonnet::critical(
1.740 www 2611: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2612: &escape($message),$server);
1.662 raeburn 2613: return $status;
2614: }
2615:
1.658 raeburn 2616: sub dcmaildump {
2617: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 2618: my %returnhash=();
1.846 albertel 2619:
2620: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 2621: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2622: &escape($enddate).':';
2623: my @esc_senders=map { &escape($_)} @$senders;
2624: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 2625: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 2626: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 2627: if (($key) && ($value)) {
2628: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 2629: }
2630: }
2631: }
2632: return %returnhash;
2633: }
1.662 raeburn 2634: # ---------------------------------------------------------- Domain roles
2635:
2636: sub get_domain_roles {
2637: my ($dom,$roles,$startdate,$enddate)=@_;
2638: if (undef($startdate) || $startdate eq '') {
2639: $startdate = '.';
2640: }
2641: if (undef($enddate) || $enddate eq '') {
2642: $enddate = '.';
2643: }
1.922 raeburn 2644: my $rolelist;
2645: if (ref($roles) eq 'ARRAY') {
2646: $rolelist = join(':',@{$roles});
2647: }
1.662 raeburn 2648: my %personnel = ();
1.841 albertel 2649:
2650: my %servers = &get_servers($dom,'library');
2651: foreach my $tryserver (keys(%servers)) {
2652: %{$personnel{$tryserver}}=();
2653: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
2654: &escape($startdate).':'.
2655: &escape($enddate).':'.
2656: &escape($rolelist), $tryserver))) {
2657: my ($key,$value) = split(/\=/,$line,2);
2658: if (($key) && ($value)) {
2659: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2660: }
2661: }
1.662 raeburn 2662: }
2663: return %personnel;
2664: }
1.658 raeburn 2665:
1.149 www 2666: # ----------------------------------------------------------- Check out an item
2667:
1.504 albertel 2668: sub get_first_access {
2669: my ($type,$argsymb)=@_;
1.790 albertel 2670: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2671: if ($argsymb) { $symb=$argsymb; }
2672: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 2673: if ($type eq 'course') {
2674: $res='course';
2675: } elsif ($type eq 'map') {
1.588 albertel 2676: $res=&symbread($map);
2677: } else {
2678: $res=$symb;
2679: }
2680: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2681: return $times{"$courseid\0$res"};
1.504 albertel 2682: }
2683:
2684: sub set_first_access {
2685: my ($type)=@_;
1.790 albertel 2686: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2687: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 2688: if ($type eq 'course') {
2689: $res='course';
2690: } elsif ($type eq 'map') {
1.588 albertel 2691: $res=&symbread($map);
2692: } else {
2693: $res=$symb;
2694: }
2695: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 2696: if (!$firstaccess) {
1.588 albertel 2697: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 2698: }
2699: return 'already_set';
1.504 albertel 2700: }
2701:
1.149 www 2702: sub checkout {
2703: my ($symb,$tuname,$tudom,$tcrsid)=@_;
2704: my $now=time;
2705: my $lonhost=$perlvar{'lonHostID'};
2706: my $infostr=&escape(
1.234 www 2707: 'CHECKOUTTOKEN&'.
1.149 www 2708: $tuname.'&'.
2709: $tudom.'&'.
2710: $tcrsid.'&'.
2711: $symb.'&'.
2712: $now.'&'.$ENV{'REMOTE_ADDR'});
2713: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 2714: if ($token=~/^error\:/) {
1.672 albertel 2715: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2716: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
2717: "</font>");
2718: return '';
2719: }
2720:
1.149 www 2721: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
2722: $token=~tr/a-z/A-Z/;
2723:
1.153 www 2724: my %infohash=('resource.0.outtoken' => $token,
2725: 'resource.0.checkouttime' => $now,
2726: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 2727:
2728: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2729: return '';
1.151 www 2730: } else {
1.672 albertel 2731: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2732: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
2733: "</font>");
1.149 www 2734: }
2735:
2736: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2737: &escape('Checkout '.$infostr.' - '.
2738: $token)) ne 'ok') {
2739: return '';
1.151 www 2740: } else {
1.672 albertel 2741: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2742: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
2743: "</font>");
1.149 www 2744: }
1.151 www 2745: return $token;
1.149 www 2746: }
2747:
2748: # ------------------------------------------------------------ Check in an item
2749:
2750: sub checkin {
2751: my $token=shift;
1.150 www 2752: my $now=time;
2753: my ($ta,$tb,$lonhost)=split(/\*/,$token);
2754: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 2755: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 2756: $dtoken=~s/\W/\_/g;
1.234 www 2757: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 2758: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
2759:
1.154 www 2760: unless (($tuname) && ($tudom)) {
2761: &logthis('Check in '.$token.' ('.$dtoken.') failed');
2762: return '';
2763: }
2764:
2765: unless (&allowed('mgr',$tcrsid)) {
2766: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 2767: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 2768: return '';
2769: }
2770:
1.153 www 2771: my %infohash=('resource.0.intoken' => $token,
2772: 'resource.0.checkintime' => $now,
2773: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 2774:
2775: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2776: return '';
2777: }
2778:
2779: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2780: &escape('Checkin - '.$token)) ne 'ok') {
2781: return '';
2782: }
2783:
2784: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 2785: }
2786:
2787: # --------------------------------------------- Set Expire Date for Spreadsheet
2788:
2789: sub expirespread {
2790: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 2791: my $cid=$env{'request.course.id'};
1.110 www 2792: if ($cid) {
2793: my $now=time;
2794: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 2795: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
2796: $env{'course.'.$cid.'.num'}.
1.110 www 2797: ':nohist_expirationdates:'.
2798: &escape($key).'='.$now,
1.620 albertel 2799: $env{'course.'.$cid.'.home'})
1.110 www 2800: }
2801: return 'ok';
1.14 www 2802: }
2803:
1.109 www 2804: # ----------------------------------------------------- Devalidate Spreadsheets
2805:
2806: sub devalidate {
1.325 www 2807: my ($symb,$uname,$udom)=@_;
1.620 albertel 2808: my $cid=$env{'request.course.id'};
1.109 www 2809: if ($cid) {
1.391 matthew 2810: # delete the stored spreadsheets for
2811: # - the student level sheet of this user in course's homespace
2812: # - the assessment level sheet for this resource
2813: # for this user in user's homespace
1.553 albertel 2814: # - current conditional state info
1.325 www 2815: my $key=$uname.':'.$udom.':';
1.109 www 2816: my $status=
1.299 matthew 2817: &del('nohist_calculatedsheets',
1.391 matthew 2818: [$key.'studentcalc:'],
1.620 albertel 2819: $env{'course.'.$cid.'.domain'},
2820: $env{'course.'.$cid.'.num'})
1.133 albertel 2821: .' '.
2822: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 2823: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 2824: unless ($status eq 'ok ok') {
2825: &logthis('Could not devalidate spreadsheet '.
1.325 www 2826: $uname.' at '.$udom.' for '.
1.109 www 2827: $symb.': '.$status);
1.133 albertel 2828: }
1.553 albertel 2829: &delenv('user.state.'.$cid);
1.109 www 2830: }
2831: }
2832:
1.265 albertel 2833: sub get_scalar {
2834: my ($string,$end) = @_;
2835: my $value;
2836: if ($$string =~ s/^([^&]*?)($end)/$2/) {
2837: $value = $1;
2838: } elsif ($$string =~ s/^([^&]*?)&//) {
2839: $value = $1;
2840: }
2841: return &unescape($value);
2842: }
2843:
2844: sub array2str {
2845: my (@array) = @_;
2846: my $result=&arrayref2str(\@array);
2847: $result=~s/^__ARRAY_REF__//;
2848: $result=~s/__END_ARRAY_REF__$//;
2849: return $result;
2850: }
2851:
1.204 albertel 2852: sub arrayref2str {
2853: my ($arrayref) = @_;
1.265 albertel 2854: my $result='__ARRAY_REF__';
1.204 albertel 2855: foreach my $elem (@$arrayref) {
1.265 albertel 2856: if(ref($elem) eq 'ARRAY') {
2857: $result.=&arrayref2str($elem).'&';
2858: } elsif(ref($elem) eq 'HASH') {
2859: $result.=&hashref2str($elem).'&';
2860: } elsif(ref($elem)) {
2861: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 2862: } else {
2863: $result.=&escape($elem).'&';
2864: }
2865: }
2866: $result=~s/\&$//;
1.265 albertel 2867: $result .= '__END_ARRAY_REF__';
1.204 albertel 2868: return $result;
2869: }
2870:
1.168 albertel 2871: sub hash2str {
1.204 albertel 2872: my (%hash) = @_;
2873: my $result=&hashref2str(\%hash);
1.265 albertel 2874: $result=~s/^__HASH_REF__//;
2875: $result=~s/__END_HASH_REF__$//;
1.204 albertel 2876: return $result;
2877: }
2878:
2879: sub hashref2str {
2880: my ($hashref)=@_;
1.265 albertel 2881: my $result='__HASH_REF__';
1.800 albertel 2882: foreach my $key (sort(keys(%$hashref))) {
2883: if (ref($key) eq 'ARRAY') {
2884: $result.=&arrayref2str($key).'=';
2885: } elsif (ref($key) eq 'HASH') {
2886: $result.=&hashref2str($key).'=';
2887: } elsif (ref($key)) {
1.265 albertel 2888: $result.='=';
1.800 albertel 2889: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 2890: } else {
1.800 albertel 2891: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 2892: }
2893:
1.800 albertel 2894: if(ref($hashref->{$key}) eq 'ARRAY') {
2895: $result.=&arrayref2str($hashref->{$key}).'&';
2896: } elsif(ref($hashref->{$key}) eq 'HASH') {
2897: $result.=&hashref2str($hashref->{$key}).'&';
2898: } elsif(ref($hashref->{$key})) {
1.265 albertel 2899: $result.='&';
1.800 albertel 2900: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 2901: } else {
1.800 albertel 2902: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 2903: }
2904: }
1.168 albertel 2905: $result=~s/\&$//;
1.265 albertel 2906: $result .= '__END_HASH_REF__';
1.168 albertel 2907: return $result;
2908: }
2909:
2910: sub str2hash {
1.265 albertel 2911: my ($string)=@_;
2912: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
2913: return %$hash;
2914: }
2915:
2916: sub str2hashref {
1.168 albertel 2917: my ($string) = @_;
1.265 albertel 2918:
2919: my %hash;
2920:
2921: if($string !~ /^__HASH_REF__/) {
2922: if (! ($string eq '' || !defined($string))) {
2923: $hash{'error'}='Not hash reference';
2924: }
2925: return (\%hash, $string);
2926: }
2927:
2928: $string =~ s/^__HASH_REF__//;
2929:
2930: while($string !~ /^__END_HASH_REF__/) {
2931: #key
2932: my $key='';
2933: if($string =~ /^__HASH_REF__/) {
2934: ($key, $string)=&str2hashref($string);
2935: if(defined($key->{'error'})) {
2936: $hash{'error'}='Bad data';
2937: return (\%hash, $string);
2938: }
2939: } elsif($string =~ /^__ARRAY_REF__/) {
2940: ($key, $string)=&str2arrayref($string);
2941: if($key->[0] eq 'Array reference error') {
2942: $hash{'error'}='Bad data';
2943: return (\%hash, $string);
2944: }
2945: } else {
2946: $string =~ s/^(.*?)=//;
1.267 albertel 2947: $key=&unescape($1);
1.265 albertel 2948: }
2949: $string =~ s/^=//;
2950:
2951: #value
2952: my $value='';
2953: if($string =~ /^__HASH_REF__/) {
2954: ($value, $string)=&str2hashref($string);
2955: if(defined($value->{'error'})) {
2956: $hash{'error'}='Bad data';
2957: return (\%hash, $string);
2958: }
2959: } elsif($string =~ /^__ARRAY_REF__/) {
2960: ($value, $string)=&str2arrayref($string);
2961: if($value->[0] eq 'Array reference error') {
2962: $hash{'error'}='Bad data';
2963: return (\%hash, $string);
2964: }
2965: } else {
2966: $value=&get_scalar(\$string,'__END_HASH_REF__');
2967: }
2968: $string =~ s/^&//;
2969:
2970: $hash{$key}=$value;
1.204 albertel 2971: }
1.265 albertel 2972:
2973: $string =~ s/^__END_HASH_REF__//;
2974:
2975: return (\%hash, $string);
1.204 albertel 2976: }
2977:
2978: sub str2array {
1.265 albertel 2979: my ($string)=@_;
2980: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
2981: return @$array;
2982: }
2983:
2984: sub str2arrayref {
1.204 albertel 2985: my ($string) = @_;
1.265 albertel 2986: my @array;
2987:
2988: if($string !~ /^__ARRAY_REF__/) {
2989: if (! ($string eq '' || !defined($string))) {
2990: $array[0]='Array reference error';
2991: }
2992: return (\@array, $string);
2993: }
2994:
2995: $string =~ s/^__ARRAY_REF__//;
2996:
2997: while($string !~ /^__END_ARRAY_REF__/) {
2998: my $value='';
2999: if($string =~ /^__HASH_REF__/) {
3000: ($value, $string)=&str2hashref($string);
3001: if(defined($value->{'error'})) {
3002: $array[0] ='Array reference error';
3003: return (\@array, $string);
3004: }
3005: } elsif($string =~ /^__ARRAY_REF__/) {
3006: ($value, $string)=&str2arrayref($string);
3007: if($value->[0] eq 'Array reference error') {
3008: $array[0] ='Array reference error';
3009: return (\@array, $string);
3010: }
3011: } else {
3012: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3013: }
3014: $string =~ s/^&//;
3015:
3016: push(@array, $value);
1.191 harris41 3017: }
1.265 albertel 3018:
3019: $string =~ s/^__END_ARRAY_REF__//;
3020:
3021: return (\@array, $string);
1.168 albertel 3022: }
3023:
1.167 albertel 3024: # -------------------------------------------------------------------Temp Store
3025:
1.168 albertel 3026: sub tmpreset {
3027: my ($symb,$namespace,$domain,$stuname) = @_;
3028: if (!$symb) {
3029: $symb=&symbread();
1.620 albertel 3030: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3031: }
3032: $symb=escape($symb);
3033:
1.620 albertel 3034: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3035: $namespace=~s/\//\_/g;
3036: $namespace=~s/\W//g;
3037:
1.620 albertel 3038: if (!$domain) { $domain=$env{'user.domain'}; }
3039: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3040: if ($domain eq 'public' && $stuname eq 'public') {
3041: $stuname=$ENV{'REMOTE_ADDR'};
3042: }
1.168 albertel 3043: my $path=$perlvar{'lonDaemons'}.'/tmp';
3044: my %hash;
3045: if (tie(%hash,'GDBM_File',
3046: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3047: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3048: foreach my $key (keys %hash) {
1.180 albertel 3049: if ($key=~ /:$symb/) {
1.168 albertel 3050: delete($hash{$key});
3051: }
3052: }
3053: }
3054: }
3055:
1.167 albertel 3056: sub tmpstore {
1.168 albertel 3057: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3058:
3059: if (!$symb) {
3060: $symb=&symbread();
1.620 albertel 3061: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3062: }
3063: $symb=escape($symb);
3064:
3065: if (!$namespace) {
3066: # I don't think we would ever want to store this for a course.
3067: # it seems this will only be used if we don't have a course.
1.620 albertel 3068: #$namespace=$env{'request.course.id'};
1.168 albertel 3069: #if (!$namespace) {
1.620 albertel 3070: $namespace=$env{'request.state'};
1.168 albertel 3071: #}
3072: }
3073: $namespace=~s/\//\_/g;
3074: $namespace=~s/\W//g;
1.620 albertel 3075: if (!$domain) { $domain=$env{'user.domain'}; }
3076: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3077: if ($domain eq 'public' && $stuname eq 'public') {
3078: $stuname=$ENV{'REMOTE_ADDR'};
3079: }
1.168 albertel 3080: my $now=time;
3081: my %hash;
3082: my $path=$perlvar{'lonDaemons'}.'/tmp';
3083: if (tie(%hash,'GDBM_File',
3084: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3085: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3086: $hash{"version:$symb"}++;
3087: my $version=$hash{"version:$symb"};
3088: my $allkeys='';
3089: foreach my $key (keys(%$storehash)) {
3090: $allkeys.=$key.':';
1.591 albertel 3091: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3092: }
3093: $hash{"$version:$symb:timestamp"}=$now;
3094: $allkeys.='timestamp';
3095: $hash{"$version:keys:$symb"}=$allkeys;
3096: if (untie(%hash)) {
3097: return 'ok';
3098: } else {
3099: return "error:$!";
3100: }
3101: } else {
3102: return "error:$!";
3103: }
3104: }
1.167 albertel 3105:
1.168 albertel 3106: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3107:
1.168 albertel 3108: sub tmprestore {
3109: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3110:
1.168 albertel 3111: if (!$symb) {
3112: $symb=&symbread();
1.620 albertel 3113: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3114: }
3115: $symb=escape($symb);
3116:
1.620 albertel 3117: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3118:
1.620 albertel 3119: if (!$domain) { $domain=$env{'user.domain'}; }
3120: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3121: if ($domain eq 'public' && $stuname eq 'public') {
3122: $stuname=$ENV{'REMOTE_ADDR'};
3123: }
1.168 albertel 3124: my %returnhash;
3125: $namespace=~s/\//\_/g;
3126: $namespace=~s/\W//g;
3127: my %hash;
3128: my $path=$perlvar{'lonDaemons'}.'/tmp';
3129: if (tie(%hash,'GDBM_File',
3130: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3131: &GDBM_READER(),0640)) {
1.168 albertel 3132: my $version=$hash{"version:$symb"};
3133: $returnhash{'version'}=$version;
3134: my $scope;
3135: for ($scope=1;$scope<=$version;$scope++) {
3136: my $vkeys=$hash{"$scope:keys:$symb"};
3137: my @keys=split(/:/,$vkeys);
3138: my $key;
3139: $returnhash{"$scope:keys"}=$vkeys;
3140: foreach $key (@keys) {
1.591 albertel 3141: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3142: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3143: }
3144: }
1.168 albertel 3145: if (!(untie(%hash))) {
3146: return "error:$!";
3147: }
3148: } else {
3149: return "error:$!";
3150: }
3151: return %returnhash;
1.167 albertel 3152: }
3153:
1.9 www 3154: # ----------------------------------------------------------------------- Store
3155:
3156: sub store {
1.124 www 3157: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3158: my $home='';
3159:
1.168 albertel 3160: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3161:
1.213 www 3162: $symb=&symbclean($symb);
1.122 albertel 3163: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3164:
1.620 albertel 3165: if (!$domain) { $domain=$env{'user.domain'}; }
3166: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3167:
3168: &devalidate($symb,$stuname,$domain);
1.109 www 3169:
3170: $symb=escape($symb);
1.187 www 3171: if (!$namespace) {
1.620 albertel 3172: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3173: return '';
3174: }
3175: }
1.620 albertel 3176: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3177:
3178: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3179: $$storehash{'host'}=$perlvar{'lonHostID'};
3180:
1.12 www 3181: my $namevalue='';
1.800 albertel 3182: foreach my $key (keys(%$storehash)) {
3183: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3184: }
1.12 www 3185: $namevalue=~s/\&$//;
1.187 www 3186: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3187: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3188: }
3189:
1.47 www 3190: # -------------------------------------------------------------- Critical Store
3191:
3192: sub cstore {
1.124 www 3193: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3194: my $home='';
3195:
1.168 albertel 3196: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3197:
1.213 www 3198: $symb=&symbclean($symb);
1.122 albertel 3199: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3200:
1.620 albertel 3201: if (!$domain) { $domain=$env{'user.domain'}; }
3202: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3203:
3204: &devalidate($symb,$stuname,$domain);
1.109 www 3205:
3206: $symb=escape($symb);
1.187 www 3207: if (!$namespace) {
1.620 albertel 3208: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3209: return '';
3210: }
3211: }
1.620 albertel 3212: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3213:
3214: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3215: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3216:
1.47 www 3217: my $namevalue='';
1.800 albertel 3218: foreach my $key (keys(%$storehash)) {
3219: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3220: }
1.47 www 3221: $namevalue=~s/\&$//;
1.187 www 3222: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3223: return critical
3224: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3225: }
3226:
1.9 www 3227: # --------------------------------------------------------------------- Restore
3228:
3229: sub restore {
1.124 www 3230: my ($symb,$namespace,$domain,$stuname) = @_;
3231: my $home='';
3232:
1.168 albertel 3233: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3234:
1.122 albertel 3235: if (!$symb) {
3236: unless ($symb=escape(&symbread())) { return ''; }
3237: } else {
1.213 www 3238: $symb=&escape(&symbclean($symb));
1.122 albertel 3239: }
1.188 www 3240: if (!$namespace) {
1.620 albertel 3241: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3242: return '';
3243: }
3244: }
1.620 albertel 3245: if (!$domain) { $domain=$env{'user.domain'}; }
3246: if (!$stuname) { $stuname=$env{'user.name'}; }
3247: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3248: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3249:
1.12 www 3250: my %returnhash=();
1.800 albertel 3251: foreach my $line (split(/\&/,$answer)) {
3252: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3253: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3254: }
1.75 www 3255: my $version;
3256: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3257: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3258: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3259: }
1.75 www 3260: }
1.13 www 3261: return %returnhash;
1.34 www 3262: }
3263:
3264: # ---------------------------------------------------------- Course Description
3265:
3266: sub coursedescription {
1.731 albertel 3267: my ($courseid,$args)=@_;
1.34 www 3268: $courseid=~s/^\///;
1.49 www 3269: $courseid=~s/\_/\//g;
1.34 www 3270: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3271: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3272: my $normalid=$cdomain.'_'.$cnum;
3273: # need to always cache even if we get errors otherwise we keep
3274: # trying and trying and trying to get the course description.
3275: my %envhash=();
3276: my %returnhash=();
1.731 albertel 3277:
3278: my $expiretime=600;
3279: if ($env{'request.course.id'} eq $normalid) {
3280: $expiretime=120;
3281: }
3282:
3283: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3284: if (!$args->{'freshen_cache'}
3285: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3286: foreach my $key (keys(%env)) {
3287: next if ($key !~ /^\Q$prefix\E(.*)/);
3288: my ($setting) = $1;
3289: $returnhash{$setting} = $env{$key};
3290: }
3291: return %returnhash;
3292: }
3293:
3294: # get the data agin
3295: if (!$args->{'one_time'}) {
3296: $envhash{'course.'.$normalid.'.last_cache'}=time;
3297: }
1.811 albertel 3298:
1.34 www 3299: if ($chome ne 'no_host') {
1.302 albertel 3300: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3301: if (!exists($returnhash{'con_lost'})) {
3302: $returnhash{'home'}= $chome;
3303: $returnhash{'domain'} = $cdomain;
3304: $returnhash{'num'} = $cnum;
1.741 raeburn 3305: if (!defined($returnhash{'type'})) {
3306: $returnhash{'type'} = 'Course';
3307: }
1.130 albertel 3308: while (my ($name,$value) = each %returnhash) {
1.53 www 3309: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3310: }
1.270 www 3311: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3312: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3313: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3314: $envhash{'course.'.$normalid.'.home'}=$chome;
3315: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3316: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3317: }
3318: }
1.731 albertel 3319: if (!$args->{'one_time'}) {
3320: &appenv(%envhash);
3321: }
1.302 albertel 3322: return %returnhash;
1.461 www 3323: }
3324:
3325: # -------------------------------------------------See if a user is privileged
3326:
3327: sub privileged {
3328: my ($username,$domain)=@_;
3329: my $rolesdump=&reply("dump:$domain:$username:roles",
3330: &homeserver($username,$domain));
3331: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
3332: my $now=time;
3333: if ($rolesdump ne '') {
1.800 albertel 3334: foreach my $entry (split(/&/,$rolesdump)) {
3335: if ($entry!~/^rolesdef_/) {
3336: my ($area,$role)=split(/=/,$entry);
1.461 www 3337: $area=~s/\_\w\w$//;
3338: my ($trole,$tend,$tstart)=split(/_/,$role);
3339: if (($trole eq 'dc') || ($trole eq 'su')) {
3340: my $active=1;
3341: if ($tend) {
3342: if ($tend<$now) { $active=0; }
3343: }
3344: if ($tstart) {
3345: if ($tstart>$now) { $active=0; }
3346: }
3347: if ($active) { return 1; }
3348: }
3349: }
3350: }
3351: }
3352: return 0;
1.9 www 3353: }
1.1 albertel 3354:
1.103 harris41 3355: # -------------------------------------------------------- Get user privileges
1.11 www 3356:
3357: sub rolesinit {
3358: my ($domain,$username,$authhost)=@_;
3359: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12 www 3360: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11 www 3361: my %allroles=();
1.678 raeburn 3362: my %allgroups=();
1.11 www 3363: my $now=time;
1.743 albertel 3364: my %userroles = ('user.login.time' => $now);
1.678 raeburn 3365: my $group_privs;
1.11 www 3366:
3367: if ($rolesdump ne '') {
1.800 albertel 3368: foreach my $entry (split(/&/,$rolesdump)) {
3369: if ($entry!~/^rolesdef_/) {
3370: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3371: $area=~s/\_\w\w$//;
1.678 raeburn 3372: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3373: if ($role=~/^cr/) {
1.807 albertel 3374: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3375: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3376: ($tend,$tstart)=split('_',$trest);
3377: } else {
3378: $trole=$role;
3379: }
1.678 raeburn 3380: } elsif ($role =~ m|^gr/|) {
3381: ($trole,$tend,$tstart) = split(/_/,$role);
3382: ($trole,$group_privs) = split(/\//,$trole);
3383: $group_privs = &unescape($group_privs);
1.587 albertel 3384: } else {
3385: ($trole,$tend,$tstart)=split(/_/,$role);
3386: }
1.743 albertel 3387: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3388: $username);
3389: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3390: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3391: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3392: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3393: my $spec=$trole.'.'.$area;
3394: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3395: if ($trole =~ /^cr\//) {
1.567 raeburn 3396: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3397: } elsif ($trole eq 'gr') {
3398: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3399: } else {
1.567 raeburn 3400: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3401: }
1.12 www 3402: }
1.662 raeburn 3403: }
1.191 harris41 3404: }
1.743 albertel 3405: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3406: $userroles{'user.adv'} = $adv;
3407: $userroles{'user.author'} = $author;
1.620 albertel 3408: $env{'user.adv'}=$adv;
1.11 www 3409: }
1.743 albertel 3410: return \%userroles;
1.11 www 3411: }
3412:
1.567 raeburn 3413: sub set_arearole {
3414: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3415: # log the associated role with the area
3416: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3417: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3418: }
3419:
3420: sub custom_roleprivs {
3421: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3422: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3423: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3424: if (&hostname($homsvr) ne '') {
1.567 raeburn 3425: my ($rdummy,$roledef)=
3426: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3427: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3428: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3429: if (defined($syspriv)) {
3430: $$allroles{'cm./'}.=':'.$syspriv;
3431: $$allroles{$spec.'./'}.=':'.$syspriv;
3432: }
3433: if ($tdomain ne '') {
3434: if (defined($dompriv)) {
3435: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3436: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3437: }
3438: if (($trest ne '') && (defined($coursepriv))) {
3439: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3440: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3441: }
3442: }
3443: }
3444: }
3445: }
3446:
1.678 raeburn 3447: sub group_roleprivs {
3448: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3449: my $access = 1;
3450: my $now = time;
3451: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3452: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3453: if ($access) {
1.811 albertel 3454: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3455: $$allgroups{$course}{$group} .=':'.$group_privs;
3456: }
3457: }
1.567 raeburn 3458:
3459: sub standard_roleprivs {
3460: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3461: if (defined($pr{$trole.':s'})) {
3462: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3463: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3464: }
3465: if ($tdomain ne '') {
3466: if (defined($pr{$trole.':d'})) {
3467: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3468: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3469: }
3470: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3471: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3472: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3473: }
3474: }
3475: }
3476:
3477: sub set_userprivs {
1.678 raeburn 3478: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 3479: my $author=0;
3480: my $adv=0;
1.678 raeburn 3481: my %grouproles = ();
3482: if (keys(%{$allgroups}) > 0) {
3483: foreach my $role (keys %{$allroles}) {
1.681 raeburn 3484: my ($trole,$area,$sec,$extendedarea);
1.881 raeburn 3485: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678 raeburn 3486: $trole = $1;
3487: $area = $2;
1.681 raeburn 3488: $sec = $3;
3489: $extendedarea = $area.$sec;
3490: if (exists($$allgroups{$area})) {
3491: foreach my $group (keys(%{$$allgroups{$area}})) {
3492: my $spec = $trole.'.'.$extendedarea;
3493: $grouproles{$spec.'.'.$area.'/'.$group} =
3494: $$allgroups{$area}{$group};
1.678 raeburn 3495: }
3496: }
3497: }
3498: }
3499: }
1.800 albertel 3500: foreach my $group (keys(%grouproles)) {
3501: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3502: }
1.800 albertel 3503: foreach my $role (keys(%{$allroles})) {
3504: my %thesepriv;
3505: if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
3506: foreach my $item (split(/:/,$$allroles{$role})) {
3507: if ($item ne '') {
3508: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3509: if ($restrictions eq '') {
3510: $thesepriv{$privilege}='F';
3511: } elsif ($thesepriv{$privilege} ne 'F') {
3512: $thesepriv{$privilege}.=$restrictions;
3513: }
3514: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3515: }
3516: }
3517: my $thesestr='';
1.800 albertel 3518: foreach my $priv (keys(%thesepriv)) {
3519: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3520: }
3521: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3522: }
3523: return ($author,$adv);
3524: }
3525:
1.12 www 3526: # --------------------------------------------------------------- get interface
3527:
3528: sub get {
1.131 albertel 3529: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3530: my $items='';
1.800 albertel 3531: foreach my $item (@$storearr) {
3532: $items.=&escape($item).'&';
1.191 harris41 3533: }
1.12 www 3534: $items=~s/\&$//;
1.620 albertel 3535: if (!$udomain) { $udomain=$env{'user.domain'}; }
3536: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 3537: my $uhome=&homeserver($uname,$udomain);
3538:
1.133 albertel 3539: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3540: my @pairs=split(/\&/,$rep);
1.273 albertel 3541: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
3542: return @pairs;
3543: }
1.15 www 3544: my %returnhash=();
1.42 www 3545: my $i=0;
1.800 albertel 3546: foreach my $item (@$storearr) {
3547: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3548: $i++;
1.191 harris41 3549: }
1.15 www 3550: return %returnhash;
1.27 www 3551: }
3552:
3553: # --------------------------------------------------------------- del interface
3554:
3555: sub del {
1.133 albertel 3556: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 3557: my $items='';
1.800 albertel 3558: foreach my $item (@$storearr) {
3559: $items.=&escape($item).'&';
1.191 harris41 3560: }
1.27 www 3561: $items=~s/\&$//;
1.620 albertel 3562: if (!$udomain) { $udomain=$env{'user.domain'}; }
3563: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3564: my $uhome=&homeserver($uname,$udomain);
3565:
3566: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3567: }
3568:
3569: # -------------------------------------------------------------- dump interface
3570:
3571: sub dump {
1.755 albertel 3572: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3573: if (!$udomain) { $udomain=$env{'user.domain'}; }
3574: if (!$uname) { $uname=$env{'user.name'}; }
3575: my $uhome=&homeserver($uname,$udomain);
3576: if ($regexp) {
3577: $regexp=&escape($regexp);
3578: } else {
3579: $regexp='.';
3580: }
3581: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3582: my @pairs=split(/\&/,$rep);
3583: my %returnhash=();
3584: foreach my $item (@pairs) {
3585: my ($key,$value)=split(/=/,$item,2);
3586: $key = &unescape($key);
3587: next if ($key =~ /^error: 2 /);
3588: $returnhash{$key}=&thaw_unescape($value);
3589: }
3590: return %returnhash;
1.407 www 3591: }
3592:
1.717 albertel 3593: # --------------------------------------------------------- dumpstore interface
3594:
3595: sub dumpstore {
3596: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 3597: if (!$udomain) { $udomain=$env{'user.domain'}; }
3598: if (!$uname) { $uname=$env{'user.name'}; }
3599: my $uhome=&homeserver($uname,$udomain);
3600: if ($regexp) {
3601: $regexp=&escape($regexp);
3602: } else {
3603: $regexp='.';
3604: }
3605: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3606: my @pairs=split(/\&/,$rep);
3607: my %returnhash=();
3608: foreach my $item (@pairs) {
3609: my ($key,$value)=split(/=/,$item,2);
3610: next if ($key =~ /^error: 2 /);
3611: $returnhash{$key}=&thaw_unescape($value);
3612: }
3613: return %returnhash;
1.717 albertel 3614: }
3615:
1.407 www 3616: # -------------------------------------------------------------- keys interface
3617:
3618: sub getkeys {
3619: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 3620: if (!$udomain) { $udomain=$env{'user.domain'}; }
3621: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 3622: my $uhome=&homeserver($uname,$udomain);
3623: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3624: my @keyarray=();
1.800 albertel 3625: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 3626: next if ($key =~ /^error: 2 /);
1.800 albertel 3627: push(@keyarray,&unescape($key));
1.407 www 3628: }
3629: return @keyarray;
1.318 matthew 3630: }
3631:
1.319 matthew 3632: # --------------------------------------------------------------- currentdump
3633: sub currentdump {
1.328 matthew 3634: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 3635: $courseid = $env{'request.course.id'} if (! defined($courseid));
3636: $sdom = $env{'user.domain'} if (! defined($sdom));
3637: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 3638: my $uhome = &homeserver($sname,$sdom);
3639: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 3640: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 3641: #
1.318 matthew 3642: my %returnhash=();
1.319 matthew 3643: #
3644: if ($rep eq "unknown_cmd") {
3645: # an old lond will not know currentdump
3646: # Do a dump and make it look like a currentdump
1.822 albertel 3647: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 3648: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3649: my %hash = @tmp;
3650: @tmp=();
1.424 matthew 3651: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 3652: } else {
3653: my @pairs=split(/\&/,$rep);
1.800 albertel 3654: foreach my $pair (@pairs) {
3655: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 3656: my ($symb,$param) = split(/:/,$key);
3657: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 3658: &thaw_unescape($value);
1.319 matthew 3659: }
1.191 harris41 3660: }
1.12 www 3661: return %returnhash;
1.424 matthew 3662: }
3663:
3664: sub convert_dump_to_currentdump{
3665: my %hash = %{shift()};
3666: my %returnhash;
3667: # Code ripped from lond, essentially. The only difference
3668: # here is the unescaping done by lonnet::dump(). Conceivably
3669: # we might run in to problems with parameter names =~ /^v\./
3670: while (my ($key,$value) = each(%hash)) {
3671: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 3672: $symb = &unescape($symb);
3673: $param = &unescape($param);
1.424 matthew 3674: next if ($v eq 'version' || $symb eq 'keys');
3675: next if (exists($returnhash{$symb}) &&
3676: exists($returnhash{$symb}->{$param}) &&
3677: $returnhash{$symb}->{'v.'.$param} > $v);
3678: $returnhash{$symb}->{$param}=$value;
3679: $returnhash{$symb}->{'v.'.$param}=$v;
3680: }
3681: #
3682: # Remove all of the keys in the hashes which keep track of
3683: # the version of the parameter.
3684: while (my ($symb,$param_hash) = each(%returnhash)) {
3685: # use a foreach because we are going to delete from the hash.
3686: foreach my $key (keys(%$param_hash)) {
3687: delete($param_hash->{$key}) if ($key =~ /^v\./);
3688: }
3689: }
3690: return \%returnhash;
1.12 www 3691: }
3692:
1.627 albertel 3693: # ------------------------------------------------------ critical inc interface
3694:
3695: sub cinc {
3696: return &inc(@_,'critical');
3697: }
3698:
1.449 matthew 3699: # --------------------------------------------------------------- inc interface
3700:
3701: sub inc {
1.627 albertel 3702: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 3703: if (!$udomain) { $udomain=$env{'user.domain'}; }
3704: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 3705: my $uhome=&homeserver($uname,$udomain);
3706: my $items='';
3707: if (! ref($store)) {
3708: # got a single value, so use that instead
3709: $items = &escape($store).'=&';
3710: } elsif (ref($store) eq 'SCALAR') {
3711: $items = &escape($$store).'=&';
3712: } elsif (ref($store) eq 'ARRAY') {
3713: $items = join('=&',map {&escape($_);} @{$store});
3714: } elsif (ref($store) eq 'HASH') {
3715: while (my($key,$value) = each(%{$store})) {
3716: $items.= &escape($key).'='.&escape($value).'&';
3717: }
3718: }
3719: $items=~s/\&$//;
1.627 albertel 3720: if ($critical) {
3721: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
3722: } else {
3723: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
3724: }
1.449 matthew 3725: }
3726:
1.12 www 3727: # --------------------------------------------------------------- put interface
3728:
3729: sub put {
1.134 albertel 3730: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3731: if (!$udomain) { $udomain=$env{'user.domain'}; }
3732: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3733: my $uhome=&homeserver($uname,$udomain);
1.12 www 3734: my $items='';
1.800 albertel 3735: foreach my $item (keys(%$storehash)) {
3736: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3737: }
1.12 www 3738: $items=~s/\&$//;
1.134 albertel 3739: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 3740: }
3741:
1.631 albertel 3742: # ------------------------------------------------------------ newput interface
3743:
3744: sub newput {
3745: my ($namespace,$storehash,$udomain,$uname)=@_;
3746: if (!$udomain) { $udomain=$env{'user.domain'}; }
3747: if (!$uname) { $uname=$env{'user.name'}; }
3748: my $uhome=&homeserver($uname,$udomain);
3749: my $items='';
3750: foreach my $key (keys(%$storehash)) {
3751: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3752: }
3753: $items=~s/\&$//;
3754: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
3755: }
3756:
3757: # --------------------------------------------------------- putstore interface
3758:
1.524 raeburn 3759: sub putstore {
1.715 albertel 3760: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 3761: if (!$udomain) { $udomain=$env{'user.domain'}; }
3762: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 3763: my $uhome=&homeserver($uname,$udomain);
3764: my $items='';
1.715 albertel 3765: foreach my $key (keys(%$storehash)) {
3766: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 3767: }
1.715 albertel 3768: $items=~s/\&$//;
1.716 albertel 3769: my $esc_symb=&escape($symb);
3770: my $esc_v=&escape($version);
1.715 albertel 3771: my $reply =
1.716 albertel 3772: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 3773: $uhome);
3774: if ($reply eq 'unknown_cmd') {
1.716 albertel 3775: # gfall back to way things use to be done
1.715 albertel 3776: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
3777: $uname);
1.524 raeburn 3778: }
1.715 albertel 3779: return $reply;
3780: }
3781:
3782: sub old_putstore {
1.716 albertel 3783: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3784: if (!$udomain) { $udomain=$env{'user.domain'}; }
3785: if (!$uname) { $uname=$env{'user.name'}; }
3786: my $uhome=&homeserver($uname,$udomain);
3787: my %newstorehash;
1.800 albertel 3788: foreach my $item (keys(%$storehash)) {
3789: my $key = $version.':'.&escape($symb).':'.$item;
3790: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 3791: }
3792: my $items='';
3793: my %allitems = ();
1.800 albertel 3794: foreach my $item (keys(%newstorehash)) {
3795: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 3796: my $key = $1.':keys:'.$2;
3797: $allitems{$key} .= $3.':';
3798: }
1.800 albertel 3799: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 3800: }
1.800 albertel 3801: foreach my $item (keys(%allitems)) {
3802: $allitems{$item} =~ s/\:$//;
3803: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 3804: }
3805: $items=~s/\&$//;
3806: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 3807: }
3808:
1.47 www 3809: # ------------------------------------------------------ critical put interface
3810:
3811: sub cput {
1.134 albertel 3812: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3813: if (!$udomain) { $udomain=$env{'user.domain'}; }
3814: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3815: my $uhome=&homeserver($uname,$udomain);
1.47 www 3816: my $items='';
1.800 albertel 3817: foreach my $item (keys(%$storehash)) {
3818: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3819: }
1.47 www 3820: $items=~s/\&$//;
1.134 albertel 3821: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3822: }
3823:
3824: # -------------------------------------------------------------- eget interface
3825:
3826: sub eget {
1.133 albertel 3827: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3828: my $items='';
1.800 albertel 3829: foreach my $item (@$storearr) {
3830: $items.=&escape($item).'&';
1.191 harris41 3831: }
1.12 www 3832: $items=~s/\&$//;
1.620 albertel 3833: if (!$udomain) { $udomain=$env{'user.domain'}; }
3834: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3835: my $uhome=&homeserver($uname,$udomain);
3836: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3837: my @pairs=split(/\&/,$rep);
3838: my %returnhash=();
1.42 www 3839: my $i=0;
1.800 albertel 3840: foreach my $item (@$storearr) {
3841: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3842: $i++;
1.191 harris41 3843: }
1.12 www 3844: return %returnhash;
3845: }
3846:
1.667 albertel 3847: # ------------------------------------------------------------ tmpput interface
3848: sub tmpput {
1.802 raeburn 3849: my ($storehash,$server,$context)=@_;
1.667 albertel 3850: my $items='';
1.800 albertel 3851: foreach my $item (keys(%$storehash)) {
3852: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 3853: }
3854: $items=~s/\&$//;
1.802 raeburn 3855: if (defined($context)) {
3856: $items .= ':'.&escape($context);
3857: }
1.667 albertel 3858: return &reply("tmpput:$items",$server);
3859: }
3860:
3861: # ------------------------------------------------------------ tmpget interface
3862: sub tmpget {
1.688 albertel 3863: my ($token,$server)=@_;
3864: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3865: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 3866: my %returnhash;
3867: foreach my $item (split(/\&/,$rep)) {
3868: my ($key,$value)=split(/=/,$item);
3869: $returnhash{&unescape($key)}=&thaw_unescape($value);
3870: }
3871: return %returnhash;
3872: }
3873:
1.688 albertel 3874: # ------------------------------------------------------------ tmpget interface
3875: sub tmpdel {
3876: my ($token,$server)=@_;
3877: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3878: return &reply("tmpdel:$token",$server);
3879: }
3880:
1.765 albertel 3881: # -------------------------------------------------- portfolio access checking
3882:
3883: sub portfolio_access {
1.766 albertel 3884: my ($requrl) = @_;
1.765 albertel 3885: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
3886: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 3887: if ($result) {
3888: my %setters;
3889: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3890: my ($startblock,$endblock) =
3891: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
3892: if ($startblock && $endblock) {
3893: return 'B';
3894: }
3895: } else {
3896: my ($startblock,$endblock) =
3897: &Apache::loncommon::blockcheck(\%setters,'port');
3898: if ($startblock && $endblock) {
3899: return 'B';
3900: }
3901: }
3902: }
1.765 albertel 3903: if ($result eq 'ok') {
1.766 albertel 3904: return 'F';
1.765 albertel 3905: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 3906: return 'A';
1.765 albertel 3907: }
1.766 albertel 3908: return '';
1.765 albertel 3909: }
3910:
3911: sub get_portfolio_access {
1.767 albertel 3912: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
3913:
3914: if (!ref($access_hash)) {
3915: my $current_perms = &get_portfile_permissions($udom,$unum);
3916: my %access_controls = &get_access_controls($current_perms,$group,
3917: $file_name);
3918: $access_hash = $access_controls{$file_name};
3919: }
3920:
1.765 albertel 3921: my ($public,$guest,@domains,@users,@courses,@groups);
3922: my $now = time;
3923: if (ref($access_hash) eq 'HASH') {
3924: foreach my $key (keys(%{$access_hash})) {
3925: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
3926: if ($start > $now) {
3927: next;
3928: }
3929: if ($end && $end<$now) {
3930: next;
3931: }
3932: if ($scope eq 'public') {
3933: $public = $key;
3934: last;
3935: } elsif ($scope eq 'guest') {
3936: $guest = $key;
3937: } elsif ($scope eq 'domains') {
3938: push(@domains,$key);
3939: } elsif ($scope eq 'users') {
3940: push(@users,$key);
3941: } elsif ($scope eq 'course') {
3942: push(@courses,$key);
3943: } elsif ($scope eq 'group') {
3944: push(@groups,$key);
3945: }
3946: }
3947: if ($public) {
3948: return 'ok';
3949: }
3950: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3951: if ($guest) {
3952: return $guest;
3953: }
3954: } else {
3955: if (@domains > 0) {
3956: foreach my $domkey (@domains) {
3957: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
3958: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
3959: return 'ok';
3960: }
3961: }
3962: }
3963: }
3964: if (@users > 0) {
3965: foreach my $userkey (@users) {
1.865 raeburn 3966: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
3967: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
3968: if (ref($item) eq 'HASH') {
3969: if (($item->{'uname'} eq $env{'user.name'}) &&
3970: ($item->{'udom'} eq $env{'user.domain'})) {
3971: return 'ok';
3972: }
3973: }
3974: }
3975: }
1.765 albertel 3976: }
3977: }
3978: my %roleshash;
3979: my @courses_and_groups = @courses;
3980: push(@courses_and_groups,@groups);
3981: if (@courses_and_groups > 0) {
3982: my (%allgroups,%allroles);
3983: my ($start,$end,$role,$sec,$group);
3984: foreach my $envkey (%env) {
1.811 albertel 3985: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 3986: my $cid = $2.'_'.$3;
3987: if ($1 eq 'gr') {
3988: $group = $4;
3989: $allgroups{$cid}{$group} = $env{$envkey};
3990: } else {
3991: if ($4 eq '') {
3992: $sec = 'none';
3993: } else {
3994: $sec = $4;
3995: }
3996: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3997: }
1.811 albertel 3998: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 3999: my $cid = $2.'_'.$3;
4000: if ($4 eq '') {
4001: $sec = 'none';
4002: } else {
4003: $sec = $4;
4004: }
4005: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4006: }
4007: }
4008: if (keys(%allroles) == 0) {
4009: return;
4010: }
4011: foreach my $key (@courses_and_groups) {
4012: my %content = %{$$access_hash{$key}};
4013: my $cnum = $content{'number'};
4014: my $cdom = $content{'domain'};
4015: my $cid = $cdom.'_'.$cnum;
4016: if (!exists($allroles{$cid})) {
4017: next;
4018: }
4019: foreach my $role_id (keys(%{$content{'roles'}})) {
4020: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4021: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4022: my @status = @{$content{'roles'}{$role_id}{'access'}};
4023: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4024: foreach my $role (keys(%{$allroles{$cid}})) {
4025: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4026: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4027: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4028: if (grep/^all$/,@sections) {
4029: return 'ok';
4030: } else {
4031: if (grep/^$sec$/,@sections) {
4032: return 'ok';
4033: }
4034: }
4035: }
4036: }
4037: if (keys(%{$allgroups{$cid}}) == 0) {
4038: if (grep/^none$/,@groups) {
4039: return 'ok';
4040: }
4041: } else {
4042: if (grep/^all$/,@groups) {
4043: return 'ok';
4044: }
4045: foreach my $group (keys(%{$allgroups{$cid}})) {
4046: if (grep/^$group$/,@groups) {
4047: return 'ok';
4048: }
4049: }
4050: }
4051: }
4052: }
4053: }
4054: }
4055: }
4056: if ($guest) {
4057: return $guest;
4058: }
4059: }
4060: }
4061: return;
4062: }
4063:
4064: sub course_group_datechecker {
4065: my ($dates,$now,$status) = @_;
4066: my ($start,$end) = split(/\./,$dates);
4067: if (!$start && !$end) {
4068: return 'ok';
4069: }
4070: if (grep/^active$/,@{$status}) {
4071: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4072: return 'ok';
4073: }
4074: }
4075: if (grep/^previous$/,@{$status}) {
4076: if ($end > $now ) {
4077: return 'ok';
4078: }
4079: }
4080: if (grep/^future$/,@{$status}) {
4081: if ($start > $now) {
4082: return 'ok';
4083: }
4084: }
4085: return;
4086: }
4087:
4088: sub parse_portfolio_url {
4089: my ($url) = @_;
4090:
4091: my ($type,$udom,$unum,$group,$file_name);
4092:
1.823 albertel 4093: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4094: $type = 1;
4095: $udom = $1;
4096: $unum = $2;
4097: $file_name = $3;
1.823 albertel 4098: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4099: $type = 2;
4100: $udom = $1;
4101: $unum = $2;
4102: $group = $3;
4103: $file_name = $3.'/'.$4;
4104: }
4105: if (wantarray) {
4106: return ($type,$udom,$unum,$file_name,$group);
4107: }
4108: return $type;
4109: }
4110:
4111: sub is_portfolio_url {
4112: my ($url) = @_;
4113: return scalar(&parse_portfolio_url($url));
4114: }
4115:
1.798 raeburn 4116: sub is_portfolio_file {
4117: my ($file) = @_;
1.820 raeburn 4118: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4119: return 1;
4120: }
4121: return;
4122: }
4123:
4124:
1.341 www 4125: # ---------------------------------------------- Custom access rule evaluation
4126:
4127: sub customaccess {
4128: my ($priv,$uri)=@_;
1.807 albertel 4129: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 4130: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 4131: $udom = &LONCAPA::clean_domain($udom);
4132: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 4133: my $access=0;
1.800 albertel 4134: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 4135: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4136: if ($type eq 'user') {
4137: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 4138: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 4139: if ($tdom) {
4140: if ($tdom ne $env{'user.domain'}) { next; }
4141: }
1.896 albertel 4142: if ($tuname) {
4143: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 4144: }
4145: $access=($effect eq 'allow');
4146: last;
4147: }
4148: } else {
4149: if ($role) {
4150: if ($role ne $urole) { next; }
4151: }
4152: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4153: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4154: if ($tdom) {
4155: if ($tdom ne $udom) { next; }
4156: }
4157: if ($tcrs) {
4158: if ($tcrs ne $ucrs) { next; }
4159: }
4160: if ($tsec) {
4161: if ($tsec ne $usec) { next; }
4162: }
4163: $access=($effect eq 'allow');
4164: last;
4165: }
4166: if ($realm eq '' && $role eq '') {
4167: $access=($effect eq 'allow');
4168: }
1.402 bowersj2 4169: }
1.341 www 4170: }
4171: return $access;
4172: }
4173:
1.103 harris41 4174: # ------------------------------------------------- Check for a user privilege
1.12 www 4175:
4176: sub allowed {
1.810 raeburn 4177: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 4178: my $ver_orguri=$uri;
1.439 www 4179: $uri=&deversion($uri);
1.152 www 4180: my $orguri=$uri;
1.52 www 4181: $uri=&declutter($uri);
1.809 raeburn 4182:
1.810 raeburn 4183: if ($priv eq 'evb') {
4184: # Evade communication block restrictions for specified role in a course
4185: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4186: return $1;
4187: } else {
4188: return;
4189: }
4190: }
4191:
1.620 albertel 4192: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 4193: # Free bre access to adm and meta resources
1.775 albertel 4194: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 4195: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4196: && ($priv eq 'bre')) {
1.14 www 4197: return 'F';
1.159 www 4198: }
4199:
1.545 banghart 4200: # Free bre access to user's own portfolio contents
1.714 raeburn 4201: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 4202: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 4203: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 4204: my %setters;
4205: my ($startblock,$endblock) =
4206: &Apache::loncommon::blockcheck(\%setters,'port');
4207: if ($startblock && $endblock) {
4208: return 'B';
4209: } else {
4210: return 'F';
4211: }
1.545 banghart 4212: }
4213:
1.762 raeburn 4214: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 4215: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
4216: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
4217: if (exists($env{'request.course.id'})) {
4218: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4219: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4220: if (($domain eq $cdom) && ($name eq $cnum)) {
4221: my $courseprivid=$env{'request.course.id'};
4222: $courseprivid=~s/\_/\//;
4223: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
4224: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
4225: return $1;
1.762 raeburn 4226: } else {
4227: if ($env{'request.course.sec'}) {
4228: $courseprivid.='/'.$env{'request.course.sec'};
4229: }
4230: if ($env{'user.priv.'.$env{'request.role'}.'./'.
4231: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
4232: return $2;
4233: }
1.714 raeburn 4234: }
4235: }
4236: }
4237: }
4238:
1.159 www 4239: # Free bre to public access
4240:
4241: if ($priv eq 'bre') {
1.238 www 4242: my $copyright=&metadata($uri,'copyright');
1.620 albertel 4243: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 4244: return 'F';
4245: }
1.238 www 4246: if ($copyright eq 'priv') {
4247: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4248: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 4249: return '';
4250: }
4251: }
4252: if ($copyright eq 'domain') {
4253: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4254: unless (($env{'user.domain'} eq $1) ||
4255: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 4256: return '';
4257: }
1.262 matthew 4258: }
1.620 albertel 4259: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 4260: # Library role, so allow browsing of resources in this domain.
4261: return 'F';
1.238 www 4262: }
1.341 www 4263: if ($copyright eq 'custom') {
4264: unless (&customaccess($priv,$uri)) { return ''; }
4265: }
1.14 www 4266: }
1.264 matthew 4267: # Domain coordinator is trying to create a course
1.620 albertel 4268: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 4269: # uri is the requested domain in this case.
4270: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 4271: # a role of dc for the domain in question.
1.620 albertel 4272: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 4273: }
1.29 www 4274:
1.52 www 4275: my $thisallowed='';
4276: my $statecond=0;
4277: my $courseprivid='';
4278:
4279: # Course
4280:
1.620 albertel 4281: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4282: $thisallowed.=$1;
4283: }
1.29 www 4284:
1.52 www 4285: # Domain
4286:
1.620 albertel 4287: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 4288: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4289: $thisallowed.=$1;
4290: }
1.52 www 4291:
4292: # Course: uri itself is a course
1.66 www 4293: my $courseuri=$uri;
4294: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 4295: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 4296:
1.620 albertel 4297: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 4298: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4299: $thisallowed.=$1;
4300: }
1.29 www 4301:
1.665 albertel 4302: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 4303: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 4304: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 4305: $thisallowed='';
1.671 raeburn 4306: my ($match)=&is_on_map($uri);
4307: if ($match) {
4308: if ($env{'user.priv.'.$env{'request.role'}.'./'}
4309: =~/\Q$priv\E\&([^\:]*)/) {
4310: $thisallowed.=$1;
4311: }
4312: } else {
1.705 albertel 4313: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 4314: if ($refuri) {
4315: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 4316: $thisallowed='F';
1.671 raeburn 4317: } else {
4318: $refuri=&declutter($refuri);
4319: my ($match) = &is_on_map($refuri);
4320: if ($match) {
4321: $thisallowed='F';
4322: }
1.669 raeburn 4323: }
1.671 raeburn 4324: }
4325: }
1.314 www 4326: }
1.492 albertel 4327:
1.766 albertel 4328: if ($priv eq 'bre'
4329: && $thisallowed ne 'F'
4330: && $thisallowed ne '2'
4331: && &is_portfolio_url($uri)) {
4332: $thisallowed = &portfolio_access($uri);
4333: }
4334:
1.52 www 4335: # Full access at system, domain or course-wide level? Exit.
1.29 www 4336:
4337: if ($thisallowed=~/F/) {
4338: return 'F';
4339: }
4340:
1.52 www 4341: # If this is generating or modifying users, exit with special codes
1.29 www 4342:
1.643 www 4343: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
4344: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 4345: my ($audom,$auname)=split('/',$uri);
1.643 www 4346: # no author name given, so this just checks on the general right to make a co-author in this domain
4347: unless ($auname) { return $thisallowed; }
4348: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 4349: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
4350: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
4351: ($audom ne $env{'request.role.domain'}))) { return ''; }
4352: }
1.52 www 4353: return $thisallowed;
4354: }
4355: #
1.103 harris41 4356: # Gathered so far: system, domain and course wide privileges
1.52 www 4357: #
4358: # Course: See if uri or referer is an individual resource that is part of
4359: # the course
4360:
1.620 albertel 4361: if ($env{'request.course.id'}) {
1.232 www 4362:
1.620 albertel 4363: $courseprivid=$env{'request.course.id'};
4364: if ($env{'request.course.sec'}) {
4365: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 4366: }
4367: $courseprivid=~s/\_/\//;
4368: my $checkreferer=1;
1.232 www 4369: my ($match,$cond)=&is_on_map($uri);
4370: if ($match) {
4371: $statecond=$cond;
1.620 albertel 4372: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4373: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4374: $thisallowed.=$1;
4375: $checkreferer=0;
4376: }
1.29 www 4377: }
1.83 www 4378:
1.148 www 4379: if ($checkreferer) {
1.620 albertel 4380: my $refuri=$env{'httpref.'.$orguri};
1.148 www 4381: unless ($refuri) {
1.800 albertel 4382: foreach my $key (keys(%env)) {
4383: if ($key=~/^httpref\..*\*/) {
4384: my $pattern=$key;
1.156 www 4385: $pattern=~s/^httpref\.\/res\///;
1.148 www 4386: $pattern=~s/\*/\[\^\/\]\+/g;
4387: $pattern=~s/\//\\\//g;
1.152 www 4388: if ($orguri=~/$pattern/) {
1.800 albertel 4389: $refuri=$env{$key};
1.148 www 4390: }
4391: }
1.191 harris41 4392: }
1.148 www 4393: }
1.232 www 4394:
1.148 www 4395: if ($refuri) {
1.152 www 4396: $refuri=&declutter($refuri);
1.232 www 4397: my ($match,$cond)=&is_on_map($refuri);
4398: if ($match) {
4399: my $refstatecond=$cond;
1.620 albertel 4400: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4401: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4402: $thisallowed.=$1;
1.53 www 4403: $uri=$refuri;
4404: $statecond=$refstatecond;
1.52 www 4405: }
4406: }
1.148 www 4407: }
1.29 www 4408: }
1.52 www 4409: }
1.29 www 4410:
1.52 www 4411: #
1.103 harris41 4412: # Gathered now: all privileges that could apply, and condition number
1.52 www 4413: #
4414: #
4415: # Full or no access?
4416: #
1.29 www 4417:
1.52 www 4418: if ($thisallowed=~/F/) {
4419: return 'F';
4420: }
1.29 www 4421:
1.52 www 4422: unless ($thisallowed) {
4423: return '';
4424: }
1.29 www 4425:
1.52 www 4426: # Restrictions exist, deal with them
4427: #
4428: # C:according to course preferences
4429: # R:according to resource settings
4430: # L:unless locked
4431: # X:according to user session state
4432: #
4433:
4434: # Possibly locked functionality, check all courses
1.54 www 4435: # Locks might take effect only after 10 minutes cache expiration for other
4436: # courses, and 2 minutes for current course
1.52 www 4437:
4438: my $envkey;
4439: if ($thisallowed=~/L/) {
1.620 albertel 4440: foreach $envkey (keys %env) {
1.54 www 4441: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
4442: my $courseid=$2;
4443: my $roleid=$1.'.'.$2;
1.92 www 4444: $courseid=~s/^\///;
1.54 www 4445: my $expiretime=600;
1.620 albertel 4446: if ($env{'request.role'} eq $roleid) {
1.54 www 4447: $expiretime=120;
4448: }
4449: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
4450: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 4451: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 4452: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 4453: }
1.620 albertel 4454: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
4455: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
4456: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
4457: &log($env{'user.domain'},$env{'user.name'},
4458: $env{'user.home'},
1.57 www 4459: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 4460: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4461: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4462: return '';
4463: }
4464: }
1.620 albertel 4465: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
4466: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
4467: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
4468: &log($env{'user.domain'},$env{'user.name'},
4469: $env{'user.home'},
1.57 www 4470: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 4471: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4472: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4473: return '';
4474: }
4475: }
4476: }
1.29 www 4477: }
1.52 www 4478: }
4479:
4480: #
4481: # Rest of the restrictions depend on selected course
4482: #
4483:
1.620 albertel 4484: unless ($env{'request.course.id'}) {
1.766 albertel 4485: if ($thisallowed eq 'A') {
4486: return 'A';
1.814 raeburn 4487: } elsif ($thisallowed eq 'B') {
4488: return 'B';
1.766 albertel 4489: } else {
4490: return '1';
4491: }
1.52 www 4492: }
1.29 www 4493:
1.52 www 4494: #
4495: # Now user is definitely in a course
4496: #
1.53 www 4497:
4498:
4499: # Course preferences
4500:
4501: if ($thisallowed=~/C/) {
1.620 albertel 4502: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4503: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
4504: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 4505: =~/\Q$rolecode\E/) {
1.689 albertel 4506: if ($priv ne 'pch') {
4507: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4508: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
4509: $env{'request.course.id'});
4510: }
1.237 www 4511: return '';
4512: }
4513:
1.620 albertel 4514: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 4515: =~/\Q$unamedom\E/) {
1.689 albertel 4516: if ($priv ne 'pch') {
4517: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
4518: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
4519: $env{'request.course.id'});
4520: }
1.54 www 4521: return '';
4522: }
1.53 www 4523: }
4524:
4525: # Resource preferences
4526:
4527: if ($thisallowed=~/R/) {
1.620 albertel 4528: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 4529: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 4530: if ($priv ne 'pch') {
4531: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4532: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
4533: }
4534: return '';
1.54 www 4535: }
1.53 www 4536: }
1.30 www 4537:
1.246 www 4538: # Restricted by state or randomout?
1.30 www 4539:
1.52 www 4540: if ($thisallowed=~/X/) {
1.620 albertel 4541: if ($env{'acc.randomout'}) {
1.579 albertel 4542: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 4543: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 4544: return '';
4545: }
1.247 www 4546: }
4547: if (&condval($statecond)) {
1.52 www 4548: return '2';
4549: } else {
4550: return '';
4551: }
4552: }
1.30 www 4553:
1.766 albertel 4554: if ($thisallowed eq 'A') {
4555: return 'A';
1.814 raeburn 4556: } elsif ($thisallowed eq 'B') {
4557: return 'B';
1.766 albertel 4558: }
1.52 www 4559: return 'F';
1.232 www 4560: }
4561:
1.710 albertel 4562: sub split_uri_for_cond {
4563: my $uri=&deversion(&declutter(shift));
4564: my @uriparts=split(/\//,$uri);
4565: my $filename=pop(@uriparts);
4566: my $pathname=join('/',@uriparts);
4567: return ($pathname,$filename);
4568: }
1.232 www 4569: # --------------------------------------------------- Is a resource on the map?
4570:
4571: sub is_on_map {
1.710 albertel 4572: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 4573: #Trying to find the conditional for the file
1.620 albertel 4574: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 4575: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 4576: if ($match) {
1.289 bowersj2 4577: return (1,$1);
4578: } else {
1.434 www 4579: return (0,0);
1.289 bowersj2 4580: }
1.12 www 4581: }
4582:
1.427 www 4583: # --------------------------------------------------------- Get symb from alias
4584:
4585: sub get_symb_from_alias {
4586: my $symb=shift;
4587: my ($map,$resid,$url)=&decode_symb($symb);
4588: # Already is a symb
4589: if ($url) { return $symb; }
4590: # Must be an alias
4591: my $aliassymb='';
4592: my %bighash;
1.620 albertel 4593: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 4594: &GDBM_READER(),0640)) {
4595: my $rid=$bighash{'mapalias_'.$symb};
4596: if ($rid) {
4597: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 4598: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
4599: $resid,$bighash{'src_'.$rid});
1.427 www 4600: }
4601: untie %bighash;
4602: }
4603: return $aliassymb;
4604: }
4605:
1.12 www 4606: # ----------------------------------------------------------------- Define Role
4607:
4608: sub definerole {
4609: if (allowed('mcr','/')) {
4610: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 4611: foreach my $role (split(':',$sysrole)) {
4612: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4613: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
4614: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
4615: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4616: return "refused:s:$crole&$cqual";
4617: }
4618: }
1.191 harris41 4619: }
1.800 albertel 4620: foreach my $role (split(':',$domrole)) {
4621: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4622: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
4623: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
4624: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 4625: return "refused:d:$crole&$cqual";
4626: }
4627: }
1.191 harris41 4628: }
1.800 albertel 4629: foreach my $role (split(':',$courole)) {
4630: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4631: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
4632: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
4633: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4634: return "refused:c:$crole&$cqual";
4635: }
4636: }
1.191 harris41 4637: }
1.620 albertel 4638: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4639: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 4640: "rolesdef_$rolename=".
4641: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 4642: return reply($command,$env{'user.home'});
1.12 www 4643: } else {
4644: return 'refused';
4645: }
1.105 harris41 4646: }
4647:
4648: # ---------------- Make a metadata query against the network of library servers
4649:
4650: sub metadata_query {
1.244 matthew 4651: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 4652: my %rhash;
1.845 albertel 4653: my %libserv = &all_library();
1.244 matthew 4654: my @server_list = (defined($server_array) ? @$server_array
4655: : keys(%libserv) );
4656: for my $server (@server_list) {
1.118 harris41 4657: unless ($custom or $customshow) {
4658: my $reply=&reply("querysend:".&escape($query),$server);
4659: $rhash{$server}=$reply;
4660: }
4661: else {
4662: my $reply=&reply("querysend:".&escape($query).':'.
4663: &escape($custom).':'.&escape($customshow),
4664: $server);
4665: $rhash{$server}=$reply;
4666: }
1.112 harris41 4667: }
1.118 harris41 4668: return \%rhash;
1.240 www 4669: }
4670:
4671: # ----------------------------------------- Send log queries and wait for reply
4672:
4673: sub log_query {
4674: my ($uname,$udom,$query,%filters)=@_;
4675: my $uhome=&homeserver($uname,$udom);
4676: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 4677: my $uhost=&hostname($uhome);
1.800 albertel 4678: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 4679: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
4680: $uhome);
1.479 albertel 4681: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 4682: return get_query_reply($queryid);
4683: }
4684:
1.818 raeburn 4685: # -------------------------- Update MySQL table for portfolio file
4686:
4687: sub update_portfolio_table {
1.821 raeburn 4688: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818 raeburn 4689: my $homeserver = &homeserver($uname,$udom);
4690: my $queryid=
1.821 raeburn 4691: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
4692: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 4693: my $reply = &get_query_reply($queryid);
4694: return $reply;
4695: }
4696:
1.899 raeburn 4697: # -------------------------- Update MySQL allusers table
4698:
4699: sub update_allusers_table {
4700: my ($uname,$udom,$names) = @_;
4701: my $homeserver = &homeserver($uname,$udom);
4702: my $queryid=
4703: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
4704: 'lastname='.&escape($names->{'lastname'}).'%%'.
4705: 'firstname='.&escape($names->{'firstname'}).'%%'.
4706: 'middlename='.&escape($names->{'middlename'}).'%%'.
4707: 'generation='.&escape($names->{'generation'}).'%%'.
4708: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
4709: 'id='.&escape($names->{'id'}),$homeserver);
4710: my $reply = &get_query_reply($queryid);
4711: return $reply;
4712: }
4713:
1.508 raeburn 4714: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 4715:
4716: sub fetch_enrollment_query {
1.511 raeburn 4717: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 4718: my $homeserver;
1.547 raeburn 4719: my $maxtries = 1;
1.508 raeburn 4720: if ($context eq 'automated') {
4721: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 4722: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 4723: } else {
4724: $homeserver = &homeserver($cnum,$dom);
4725: }
1.838 albertel 4726: my $host=&hostname($homeserver);
1.506 raeburn 4727: my $cmd = '';
1.800 albertel 4728: foreach my $affiliate (keys %{$affiliatesref}) {
4729: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 4730: }
4731: $cmd =~ s/%%$//;
4732: $cmd = &escape($cmd);
4733: my $query = 'fetchenrollment';
1.620 albertel 4734: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 4735: unless ($queryid=~/^\Q$host\E\_/) {
4736: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
4737: return 'error: '.$queryid;
4738: }
1.506 raeburn 4739: my $reply = &get_query_reply($queryid);
1.547 raeburn 4740: my $tries = 1;
4741: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4742: $reply = &get_query_reply($queryid);
4743: $tries ++;
4744: }
1.526 raeburn 4745: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 4746: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 4747: } else {
1.901 albertel 4748: my @responses = split(/:/,$reply);
1.515 raeburn 4749: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 4750: foreach my $line (@responses) {
4751: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 4752: $$replyref{$key} = $value;
4753: }
4754: } else {
1.506 raeburn 4755: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 4756: foreach my $line (@responses) {
4757: my ($key,$value) = split(/=/,$line);
1.506 raeburn 4758: $$replyref{$key} = $value;
4759: if ($value > 0) {
1.800 albertel 4760: foreach my $item (@{$$affiliatesref{$key}}) {
4761: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 4762: my $destname = $pathname.'/'.$filename;
4763: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 4764: if ($xml_classlist =~ /^error/) {
4765: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
4766: } else {
1.506 raeburn 4767: if ( open(FILE,">$destname") ) {
4768: print FILE &unescape($xml_classlist);
4769: close(FILE);
1.526 raeburn 4770: } else {
4771: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 4772: }
4773: }
4774: }
4775: }
4776: }
4777: }
4778: return 'ok';
4779: }
4780: return 'error';
4781: }
4782:
1.242 www 4783: sub get_query_reply {
4784: my $queryid=shift;
1.240 www 4785: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
4786: my $reply='';
4787: for (1..100) {
4788: sleep 2;
4789: if (-e $replyfile.'.end') {
1.448 albertel 4790: if (open(my $fh,$replyfile)) {
1.904 albertel 4791: $reply = join('',<$fh>);
4792: close($fh);
1.240 www 4793: } else { return 'error: reply_file_error'; }
1.242 www 4794: return &unescape($reply);
4795: }
1.240 www 4796: }
1.242 www 4797: return 'timeout:'.$queryid;
1.240 www 4798: }
4799:
4800: sub courselog_query {
1.241 www 4801: #
4802: # possible filters:
4803: # url: url or symb
4804: # username
4805: # domain
4806: # action: view, submit, grade
4807: # start: timestamp
4808: # end: timestamp
4809: #
1.240 www 4810: my (%filters)=@_;
1.620 albertel 4811: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 4812: if ($filters{'url'}) {
4813: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
4814: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
4815: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
4816: }
1.620 albertel 4817: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4818: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 4819: return &log_query($cname,$cdom,'courselog',%filters);
4820: }
4821:
4822: sub userlog_query {
1.858 raeburn 4823: #
4824: # possible filters:
4825: # action: log check role
4826: # start: timestamp
4827: # end: timestamp
4828: #
1.240 www 4829: my ($uname,$udom,%filters)=@_;
4830: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 4831: }
4832:
1.506 raeburn 4833: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
4834:
4835: sub auto_run {
1.508 raeburn 4836: my ($cnum,$cdom) = @_;
1.876 raeburn 4837: my $response = 0;
4838: my $settings;
4839: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
4840: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
4841: $settings = $domconfig{'autoenroll'};
4842: if ($settings->{'run'} eq '1') {
4843: $response = 1;
4844: }
4845: } else {
4846: my $homeserver = &homeserver($cnum,$cdom);
4847: $response = &reply('autorun:'.$cdom,$homeserver);
4848: }
1.506 raeburn 4849: return $response;
4850: }
1.776 albertel 4851:
1.506 raeburn 4852: sub auto_get_sections {
1.508 raeburn 4853: my ($cnum,$cdom,$inst_coursecode) = @_;
4854: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 4855: my @secs = ();
1.511 raeburn 4856: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 4857: unless ($response eq 'refused') {
1.901 albertel 4858: @secs = split(/:/,$response);
1.506 raeburn 4859: }
4860: return @secs;
4861: }
1.776 albertel 4862:
1.506 raeburn 4863: sub auto_new_course {
1.508 raeburn 4864: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
4865: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 4866: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 4867: return $response;
4868: }
1.776 albertel 4869:
1.506 raeburn 4870: sub auto_validate_courseID {
1.508 raeburn 4871: my ($cnum,$cdom,$inst_course_id) = @_;
4872: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 4873: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 4874: return $response;
4875: }
1.776 albertel 4876:
1.506 raeburn 4877: sub auto_create_password {
1.873 raeburn 4878: my ($cnum,$cdom,$authparam,$udom) = @_;
4879: my ($homeserver,$response);
1.506 raeburn 4880: my $create_passwd = 0;
4881: my $authchk = '';
1.873 raeburn 4882: if ($udom =~ /^$match_domain$/) {
4883: $homeserver = &domain($udom,'primary');
4884: }
4885: if ($homeserver eq '') {
4886: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
4887: $homeserver = &homeserver($cnum,$cdom);
4888: }
4889: }
4890: if ($homeserver eq '') {
4891: $authchk = 'nodomain';
1.506 raeburn 4892: } else {
1.873 raeburn 4893: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
4894: if ($response eq 'refused') {
4895: $authchk = 'refused';
4896: } else {
1.901 albertel 4897: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 4898: }
1.506 raeburn 4899: }
4900: return ($authparam,$create_passwd,$authchk);
4901: }
4902:
1.706 raeburn 4903: sub auto_photo_permission {
4904: my ($cnum,$cdom,$students) = @_;
4905: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 4906: my ($outcome,$perm_reqd,$conditions) =
4907: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 4908: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4909: return (undef,undef);
4910: }
1.706 raeburn 4911: return ($outcome,$perm_reqd,$conditions);
4912: }
4913:
4914: sub auto_checkphotos {
4915: my ($uname,$udom,$pid) = @_;
4916: my $homeserver = &homeserver($uname,$udom);
4917: my ($result,$resulttype);
4918: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 4919: &escape($uname).':'.&escape($pid),
4920: $homeserver));
1.709 albertel 4921: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4922: return (undef,undef);
4923: }
1.706 raeburn 4924: if ($outcome) {
4925: ($result,$resulttype) = split(/:/,$outcome);
4926: }
4927: return ($result,$resulttype);
4928: }
4929:
4930: sub auto_photochoice {
4931: my ($cnum,$cdom) = @_;
4932: my $homeserver = &homeserver($cnum,$cdom);
4933: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 4934: &escape($cdom),
4935: $homeserver)));
1.709 albertel 4936: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4937: return (undef,undef);
4938: }
1.706 raeburn 4939: return ($update,$comment);
4940: }
4941:
4942: sub auto_photoupdate {
4943: my ($affiliatesref,$dom,$cnum,$photo) = @_;
4944: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 4945: my $host=&hostname($homeserver);
1.706 raeburn 4946: my $cmd = '';
4947: my $maxtries = 1;
1.800 albertel 4948: foreach my $affiliate (keys(%{$affiliatesref})) {
4949: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 4950: }
4951: $cmd =~ s/%%$//;
4952: $cmd = &escape($cmd);
4953: my $query = 'institutionalphotos';
4954: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
4955: unless ($queryid=~/^\Q$host\E\_/) {
4956: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
4957: return 'error: '.$queryid;
4958: }
4959: my $reply = &get_query_reply($queryid);
4960: my $tries = 1;
4961: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4962: $reply = &get_query_reply($queryid);
4963: $tries ++;
4964: }
4965: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
4966: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
4967: } else {
4968: my @responses = split(/:/,$reply);
4969: my $outcome = shift(@responses);
4970: foreach my $item (@responses) {
4971: my ($key,$value) = split(/=/,$item);
4972: $$photo{$key} = $value;
4973: }
4974: return $outcome;
4975: }
4976: return 'error';
4977: }
4978:
1.521 raeburn 4979: sub auto_instcode_format {
1.793 albertel 4980: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
4981: $cat_order) = @_;
1.521 raeburn 4982: my $courses = '';
1.772 raeburn 4983: my @homeservers;
1.521 raeburn 4984: if ($caller eq 'global') {
1.841 albertel 4985: my %servers = &get_servers($codedom,'library');
4986: foreach my $tryserver (keys(%servers)) {
4987: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4988: push(@homeservers,$tryserver);
4989: }
1.584 raeburn 4990: }
1.521 raeburn 4991: } else {
1.772 raeburn 4992: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 4993: }
1.793 albertel 4994: foreach my $code (keys(%{$instcodes})) {
4995: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 4996: }
4997: chop($courses);
1.772 raeburn 4998: my $ok_response = 0;
4999: my $response;
5000: while (@homeservers > 0 && $ok_response == 0) {
5001: my $server = shift(@homeservers);
5002: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5003: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5004: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 5005: split(/:/,$response);
1.772 raeburn 5006: %{$codes} = (%{$codes},&str2hash($codes_str));
5007: push(@{$codetitles},&str2array($codetitles_str));
5008: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5009: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5010: $ok_response = 1;
5011: }
5012: }
5013: if ($ok_response) {
1.521 raeburn 5014: return 'ok';
1.772 raeburn 5015: } else {
5016: return $response;
1.521 raeburn 5017: }
5018: }
5019:
1.792 raeburn 5020: sub auto_instcode_defaults {
5021: my ($domain,$returnhash,$code_order) = @_;
5022: my @homeservers;
1.841 albertel 5023:
5024: my %servers = &get_servers($domain,'library');
5025: foreach my $tryserver (keys(%servers)) {
5026: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5027: push(@homeservers,$tryserver);
5028: }
1.792 raeburn 5029: }
1.841 albertel 5030:
1.792 raeburn 5031: my $response;
1.841 albertel 5032: foreach my $server (@homeservers) {
1.792 raeburn 5033: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 5034: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5035:
5036: foreach my $pair (split(/\&/,$response)) {
5037: my ($name,$value)=split(/\=/,$pair);
5038: if ($name eq 'code_order') {
5039: @{$code_order} = split(/\&/,&unescape($value));
5040: } else {
5041: $returnhash->{&unescape($name)}=&unescape($value);
5042: }
5043: }
5044: return 'ok';
1.792 raeburn 5045: }
1.841 albertel 5046:
5047: return $response;
1.792 raeburn 5048: }
5049:
1.777 albertel 5050: sub auto_validate_class_sec {
1.918 raeburn 5051: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 5052: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 5053: my $ownerlist;
5054: if (ref($owners) eq 'ARRAY') {
5055: $ownerlist = join(',',@{$owners});
5056: } else {
5057: $ownerlist = $owners;
5058: }
1.773 raeburn 5059: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 5060: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 5061: return $response;
5062: }
5063:
1.679 raeburn 5064: # ------------------------------------------------------- Course Group routines
5065:
5066: sub get_coursegroups {
1.809 raeburn 5067: my ($cdom,$cnum,$group,$namespace) = @_;
5068: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 5069: }
5070:
1.679 raeburn 5071: sub modify_coursegroup {
5072: my ($cdom,$cnum,$groupsettings) = @_;
5073: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
5074: }
5075:
1.809 raeburn 5076: sub toggle_coursegroup_status {
5077: my ($cdom,$cnum,$group,$action) = @_;
5078: my ($from_namespace,$to_namespace);
5079: if ($action eq 'delete') {
5080: $from_namespace = 'coursegroups';
5081: $to_namespace = 'deleted_groups';
5082: } else {
5083: $from_namespace = 'deleted_groups';
5084: $to_namespace = 'coursegroups';
5085: }
5086: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 5087: if (my $tmp = &error(%curr_group)) {
5088: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
5089: return ('read error',$tmp);
5090: } else {
5091: my %savedsettings = %curr_group;
1.809 raeburn 5092: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 5093: my $deloutcome;
5094: if ($result eq 'ok') {
1.809 raeburn 5095: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 5096: } else {
5097: return ('write error',$result);
5098: }
5099: if ($deloutcome eq 'ok') {
5100: return 'ok';
5101: } else {
5102: return ('delete error',$deloutcome);
5103: }
5104: }
5105: }
5106:
1.679 raeburn 5107: sub modify_group_roles {
5108: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
5109: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
5110: my $role = 'gr/'.&escape($userprivs);
5111: my ($uname,$udom) = split(/:/,$user);
5112: my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684 raeburn 5113: if ($result eq 'ok') {
5114: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
5115: }
1.679 raeburn 5116: return $result;
5117: }
5118:
5119: sub modify_coursegroup_membership {
5120: my ($cdom,$cnum,$membership) = @_;
5121: my $result = &put('groupmembership',$membership,$cdom,$cnum);
5122: return $result;
5123: }
5124:
1.682 raeburn 5125: sub get_active_groups {
5126: my ($udom,$uname,$cdom,$cnum) = @_;
5127: my $now = time;
5128: my %groups = ();
5129: foreach my $key (keys(%env)) {
1.811 albertel 5130: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 5131: my ($start,$end) = split(/\./,$env{$key});
5132: if (($end!=0) && ($end<$now)) { next; }
5133: if (($start!=0) && ($start>$now)) { next; }
5134: if ($1 eq $cdom && $2 eq $cnum) {
5135: $groups{$3} = $env{$key} ;
5136: }
5137: }
5138: }
5139: return %groups;
5140: }
5141:
1.683 raeburn 5142: sub get_group_membership {
5143: my ($cdom,$cnum,$group) = @_;
5144: return(&dump('groupmembership',$cdom,$cnum,$group));
5145: }
5146:
5147: sub get_users_groups {
5148: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 5149: my @usersgroups;
1.683 raeburn 5150: my $cachetime=1800;
5151:
5152: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 5153: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
5154: if (defined($cached)) {
1.734 albertel 5155: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 5156: } else {
5157: $grouplist = '';
1.816 raeburn 5158: my $courseurl = &courseid_to_courseurl($courseid);
5159: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 5160: my $access_end = $env{'course.'.$courseid.
5161: '.default_enrollment_end_date'};
5162: my $now = time;
5163: foreach my $key (keys(%roleshash)) {
5164: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
5165: my $group = $1;
5166: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
5167: my $start = $2;
5168: my $end = $1;
5169: if ($start == -1) { next; } # deleted from group
5170: if (($start!=0) && ($start>$now)) { next; }
5171: if (($end!=0) && ($end<$now)) {
5172: if ($access_end && $access_end < $now) {
5173: if ($access_end - $end < 86400) {
5174: push(@usersgroups,$group);
1.733 raeburn 5175: }
5176: }
1.817 raeburn 5177: next;
1.733 raeburn 5178: }
1.817 raeburn 5179: push(@usersgroups,$group);
1.683 raeburn 5180: }
5181: }
5182: }
1.817 raeburn 5183: @usersgroups = &sort_course_groups($courseid,@usersgroups);
5184: $grouplist = join(':',@usersgroups);
5185: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 5186: }
1.733 raeburn 5187: return @usersgroups;
1.683 raeburn 5188: }
5189:
5190: sub devalidate_getgroups_cache {
5191: my ($udom,$uname,$cdom,$cnum)=@_;
5192: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 5193:
1.683 raeburn 5194: my $hashid="$udom:$uname:$courseid";
5195: &devalidate_cache_new('getgroups',$hashid);
5196: }
5197:
1.12 www 5198: # ------------------------------------------------------------------ Plain Text
5199:
5200: sub plaintext {
1.742 raeburn 5201: my ($short,$type,$cid) = @_;
1.758 albertel 5202: if ($short =~ /^cr/) {
5203: return (split('/',$short))[-1];
5204: }
1.742 raeburn 5205: if (!defined($cid)) {
5206: $cid = $env{'request.course.id'};
5207: }
5208: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
5209: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
5210: '.plaintext'});
5211: }
5212: my %rolenames = (
5213: Course => 'std',
5214: Group => 'alt1',
5215: );
5216: if (defined($type) &&
5217: defined($rolenames{$type}) &&
5218: defined($prp{$short}{$rolenames{$type}})) {
5219: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
5220: } else {
5221: return &Apache::lonlocal::mt($prp{$short}{'std'});
5222: }
1.12 www 5223: }
5224:
5225: # ----------------------------------------------------------------- Assign Role
5226:
5227: sub assignrole {
1.357 www 5228: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21 www 5229: my $mrole;
5230: if ($role =~ /^cr\//) {
1.393 www 5231: my $cwosec=$url;
1.811 albertel 5232: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 5233: unless (&allowed('ccr',$cwosec)) {
1.104 www 5234: &logthis('Refused custom assignrole: '.
5235: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 5236: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 5237: return 'refused';
5238: }
1.21 www 5239: $mrole='cr';
1.678 raeburn 5240: } elsif ($role =~ /^gr\//) {
5241: my $cwogrp=$url;
1.811 albertel 5242: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 5243: unless (&allowed('mdg',$cwogrp)) {
5244: &logthis('Refused group assignrole: '.
5245: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
5246: $env{'user.name'}.' at '.$env{'user.domain'});
5247: return 'refused';
5248: }
5249: $mrole='gr';
1.21 www 5250: } else {
1.82 www 5251: my $cwosec=$url;
1.811 albertel 5252: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 ! raeburn 5253: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
! 5254: my $refused;
! 5255: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
! 5256: if (!(&allowed('c'.$role,$url))) {
! 5257: $refused = 1;
! 5258: }
! 5259: } else {
! 5260: $refused = 1;
! 5261: }
! 5262: if ($refused) {
! 5263: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
! 5264: ' '.$role.' '.$end.' '.$start.' by '.
! 5265: $env{'user.name'}.' at '.$env{'user.domain'});
! 5266: return 'refused';
! 5267: }
1.104 www 5268: }
1.21 www 5269: $mrole=$role;
5270: }
1.620 albertel 5271: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5272: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 5273: if ($end) { $command.='_'.$end; }
1.21 www 5274: if ($start) {
5275: if ($end) {
1.81 www 5276: $command.='_'.$start;
1.21 www 5277: } else {
1.81 www 5278: $command.='_0_'.$start;
1.21 www 5279: }
5280: }
1.739 raeburn 5281: my $origstart = $start;
5282: my $origend = $end;
1.357 www 5283: # actually delete
5284: if ($deleteflag) {
1.373 www 5285: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 5286: # modify command to delete the role
1.620 albertel 5287: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 5288: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 5289: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 5290: # set start and finish to negative values for userrolelog
5291: $start=-1;
5292: $end=-1;
5293: }
5294: }
5295: # send command
1.349 www 5296: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 5297: # log new user role if status is ok
1.349 www 5298: if ($answer eq 'ok') {
1.663 raeburn 5299: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 5300: # for course roles, perform group memberships changes triggered by role change.
5301: unless ($role =~ /^gr/) {
5302: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
5303: $origstart);
5304: }
1.349 www 5305: }
5306: return $answer;
1.169 harris41 5307: }
5308:
5309: # -------------------------------------------------- Modify user authentication
1.197 www 5310: # Overrides without validation
5311:
1.169 harris41 5312: sub modifyuserauth {
5313: my ($udom,$uname,$umode,$upass)=@_;
5314: my $uhome=&homeserver($uname,$udom);
1.197 www 5315: unless (&allowed('mau',$udom)) { return 'refused'; }
5316: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 5317: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5318: ' in domain '.$env{'request.role.domain'});
1.169 harris41 5319: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
5320: &escape($upass),$uhome);
1.620 albertel 5321: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 5322: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
5323: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
5324: &log($udom,,$uname,$uhome,
1.620 albertel 5325: 'Authentication changed by '.$env{'user.domain'}.', '.
5326: $env{'user.name'}.', '.$umode.
1.197 www 5327: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 5328: unless ($reply eq 'ok') {
1.197 www 5329: &logthis('Authentication mode error: '.$reply);
1.169 harris41 5330: return 'error: '.$reply;
5331: }
1.170 harris41 5332: return 'ok';
1.80 www 5333: }
5334:
1.81 www 5335: # --------------------------------------------------------------- Modify a user
1.80 www 5336:
1.81 www 5337: sub modifyuser {
1.206 matthew 5338: my ($udom, $uname, $uid,
5339: $umode, $upass, $first,
5340: $middle, $last, $gene,
1.387 www 5341: $forceid, $desiredhome, $email)=@_;
1.807 albertel 5342: $udom= &LONCAPA::clean_domain($udom);
5343: $uname=&LONCAPA::clean_username($uname);
1.81 www 5344: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 5345: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 5346: $last.', '.$gene.'(forceid: '.$forceid.')'.
5347: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
5348: ' desiredhome not specified').
1.620 albertel 5349: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5350: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 5351: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 5352: # ----------------------------------------------------------------- Create User
1.406 albertel 5353: if (($uhome eq 'no_host') &&
5354: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 5355: my $unhome='';
1.844 albertel 5356: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 5357: $unhome = $desiredhome;
1.620 albertel 5358: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
5359: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 5360: } else { # load balancing routine for determining $unhome
1.81 www 5361: my $loadm=10000000;
1.841 albertel 5362: my %servers = &get_servers($udom,'library');
5363: foreach my $tryserver (keys(%servers)) {
5364: my $answer=reply('load',$tryserver);
5365: if (($answer=~/\d+/) && ($answer<$loadm)) {
5366: $loadm=$answer;
5367: $unhome=$tryserver;
5368: }
1.80 www 5369: }
5370: }
5371: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 5372: return 'error: unable to find a home server for '.$uname.
5373: ' in domain '.$udom;
1.80 www 5374: }
5375: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
5376: &escape($upass),$unhome);
5377: unless ($reply eq 'ok') {
5378: return 'error: '.$reply;
5379: }
1.230 stredwic 5380: $uhome=&homeserver($uname,$udom,'true');
1.80 www 5381: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 5382: return 'error: unable verify users home machine.';
1.80 www 5383: }
1.209 matthew 5384: } # End of creation of new user
1.80 www 5385: # ---------------------------------------------------------------------- Add ID
5386: if ($uid) {
5387: $uid=~tr/A-Z/a-z/;
5388: my %uidhash=&idrget($udom,$uname);
1.196 www 5389: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
5390: && (!$forceid)) {
1.80 www 5391: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 5392: return 'error: user id "'.$uid.'" does not match '.
5393: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 5394: }
5395: } else {
5396: &idput($udom,($uname => $uid));
5397: }
5398: }
5399: # -------------------------------------------------------------- Add names, etc
1.313 matthew 5400: my @tmp=&get('environment',
1.899 raeburn 5401: ['firstname','middlename','lastname','generation','id',
5402: 'permanentemail'],
1.134 albertel 5403: $udom,$uname);
1.313 matthew 5404: my %names;
5405: if ($tmp[0] =~ m/^error:.*/) {
5406: %names=();
5407: } else {
5408: %names = @tmp;
5409: }
1.388 www 5410: #
5411: # Make sure to not trash student environment if instructor does not bother
5412: # to supply name and email information
5413: #
5414: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 5415: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 5416: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 5417: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 5418: if ($email) {
5419: $email=~s/[^\w\@\.\-\,]//gs;
5420: if ($email=~/\@/) { $names{'notification'} = $email;
5421: $names{'critnotification'} = $email;
5422: $names{'permanentemail'} = $email; }
5423: }
1.899 raeburn 5424: if ($uid) { $names{'id'} = $uid; }
1.134 albertel 5425: my $reply = &put('environment', \%names, $udom,$uname);
5426: if ($reply ne 'ok') { return 'error: '.$reply; }
1.899 raeburn 5427: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680 www 5428: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81 www 5429: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 5430: $umode.', '.$first.', '.$middle.', '.
5431: $last.', '.$gene.' by '.
1.620 albertel 5432: $env{'user.name'}.' at '.$env{'user.domain'});
1.134 albertel 5433: return 'ok';
1.80 www 5434: }
5435:
1.81 www 5436: # -------------------------------------------------------------- Modify student
1.80 www 5437:
1.81 www 5438: sub modifystudent {
5439: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515 raeburn 5440: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455 albertel 5441: if (!$cid) {
1.620 albertel 5442: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5443: return 'not_in_class';
5444: }
1.80 www 5445: }
5446: # --------------------------------------------------------------- Make the user
1.81 www 5447: my $reply=&modifyuser
1.209 matthew 5448: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 5449: $desiredhome,$email);
1.80 www 5450: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 5451: # This will cause &modify_student_enrollment to get the uid from the
5452: # students environment
5453: $uid = undef if (!$forceid);
1.455 albertel 5454: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515 raeburn 5455: $gene,$usec,$end,$start,$type,$locktype,$cid);
1.297 matthew 5456: return $reply;
5457: }
5458:
5459: sub modify_student_enrollment {
1.515 raeburn 5460: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455 albertel 5461: my ($cdom,$cnum,$chome);
5462: if (!$cid) {
1.620 albertel 5463: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5464: return 'not_in_class';
5465: }
1.620 albertel 5466: $cdom=$env{'course.'.$cid.'.domain'};
5467: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 5468: } else {
5469: ($cdom,$cnum)=split(/_/,$cid);
5470: }
1.620 albertel 5471: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 5472: if (!$chome) {
1.457 raeburn 5473: $chome=&homeserver($cnum,$cdom);
1.297 matthew 5474: }
1.455 albertel 5475: if (!$chome) { return 'unknown_course'; }
1.297 matthew 5476: # Make sure the user exists
1.81 www 5477: my $uhome=&homeserver($uname,$udom);
5478: if (($uhome eq '') || ($uhome eq 'no_host')) {
5479: return 'error: no such user';
5480: }
1.297 matthew 5481: # Get student data if we were not given enough information
5482: if (!defined($first) || $first eq '' ||
5483: !defined($last) || $last eq '' ||
5484: !defined($uid) || $uid eq '' ||
5485: !defined($middle) || $middle eq '' ||
5486: !defined($gene) || $gene eq '') {
1.294 matthew 5487: # They did not supply us with enough data to enroll the student, so
5488: # we need to pick up more information.
1.297 matthew 5489: my %tmp = &get('environment',
1.294 matthew 5490: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 5491: ,$udom,$uname);
5492:
1.800 albertel 5493: #foreach my $key (keys(%tmp)) {
5494: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 5495: #}
1.294 matthew 5496: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
5497: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
5498: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 5499: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 5500: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
5501: }
1.556 albertel 5502: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 5503: my $reply=cput('classlist',
5504: {"$uname:$udom" =>
1.515 raeburn 5505: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 5506: $cdom,$cnum);
1.81 www 5507: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
5508: return 'error: '.$reply;
1.652 albertel 5509: } else {
5510: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 5511: }
1.297 matthew 5512: # Add student role to user
1.83 www 5513: my $uurl='/'.$cid;
1.81 www 5514: $uurl=~s/\_/\//g;
5515: if ($usec) {
5516: $uurl.='/'.$usec;
5517: }
5518: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21 www 5519: }
5520:
1.556 albertel 5521: sub format_name {
5522: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
5523: my $name;
5524: if ($first ne 'lastname') {
5525: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
5526: } else {
5527: if ($lastname=~/\S/) {
5528: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
5529: $name=~s/\s+,/,/;
5530: } else {
5531: $name.= $firstname.' '.$middlename.' '.$generation;
5532: }
5533: }
5534: $name=~s/^\s+//;
5535: $name=~s/\s+$//;
5536: $name=~s/\s+/ /g;
5537: return $name;
5538: }
5539:
1.84 www 5540: # ------------------------------------------------- Write to course preferences
5541:
5542: sub writecoursepref {
5543: my ($courseid,%prefs)=@_;
5544: $courseid=~s/^\///;
5545: $courseid=~s/\_/\//g;
5546: my ($cdomain,$cnum)=split(/\//,$courseid);
5547: my $chome=homeserver($cnum,$cdomain);
5548: if (($chome eq '') || ($chome eq 'no_host')) {
5549: return 'error: no such course';
5550: }
5551: my $cstring='';
1.800 albertel 5552: foreach my $pref (keys(%prefs)) {
5553: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 5554: }
1.84 www 5555: $cstring=~s/\&$//;
5556: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
5557: }
5558:
5559: # ---------------------------------------------------------- Make/modify course
5560:
5561: sub createcourse {
1.741 raeburn 5562: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
5563: $course_owner,$crstype)=@_;
1.84 www 5564: $url=&declutter($url);
5565: my $cid='';
1.264 matthew 5566: unless (&allowed('ccc',$udom)) {
1.84 www 5567: return 'refused';
5568: }
5569: # ------------------------------------------------------------------- Create ID
1.674 www 5570: my $uname=int(1+rand(9)).
5571: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
5572: substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84 www 5573: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
5574: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 5575: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 5576: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5577: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
5578: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 5579: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5580: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5581: return 'error: unable to generate unique course-ID';
5582: }
5583: }
1.264 matthew 5584: # ------------------------------------------------ Check supplied server name
1.620 albertel 5585: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845 albertel 5586: if (! &is_library($course_server)) {
1.264 matthew 5587: return 'error:bad server name '.$course_server;
5588: }
1.84 www 5589: # ------------------------------------------------------------- Make the course
5590: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 5591: $course_server);
1.84 www 5592: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 5593: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5594: if (($uhome eq '') || ($uhome eq 'no_host')) {
5595: return 'error: no such course';
5596: }
1.271 www 5597: # ----------------------------------------------------------------- Course made
1.516 raeburn 5598: # log existence
1.918 raeburn 5599: my $newcourse = {
5600: $udom.'_'.$uname => {
1.921 raeburn 5601: description => $description,
5602: inst_code => $inst_code,
5603: owner => $course_owner,
5604: type => $crstype,
1.918 raeburn 5605: },
5606: };
1.921 raeburn 5607: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 5608: # set toplevel url
1.271 www 5609: my $topurl=$url;
5610: unless ($nonstandard) {
5611: # ------------------------------------------ For standard courses, make top url
5612: my $mapurl=&clutter($url);
1.278 www 5613: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 5614: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 5615: <map>
5616: <resource id="1" type="start"></resource>
5617: <resource id="2" src="$mapurl"></resource>
5618: <resource id="3" type="finish"></resource>
5619: <link index="1" from="1" to="2"></link>
5620: <link index="2" from="2" to="3"></link>
5621: </map>
5622: ENDINITMAP
5623: $topurl=&declutter(
1.638 albertel 5624: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 5625: );
5626: }
5627: # ----------------------------------------------------------- Write preferences
1.84 www 5628: &writecoursepref($udom.'_'.$uname,
5629: ('description' => $description,
1.271 www 5630: 'url' => $topurl));
1.84 www 5631: return '/'.$udom.'/'.$uname;
5632: }
5633:
1.813 albertel 5634: sub is_course {
5635: my ($cdom,$cnum) = @_;
5636: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.918 raeburn 5637: undef,'.',undef,1);
1.813 albertel 5638: if (exists($courses{$cdom.'_'.$cnum})) {
5639: return 1;
5640: }
5641: return 0;
5642: }
5643:
1.21 www 5644: # ---------------------------------------------------------- Assign Custom Role
5645:
5646: sub assigncustomrole {
1.357 www 5647: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21 www 5648: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357 www 5649: $end,$start,$deleteflag);
1.21 www 5650: }
5651:
5652: # ----------------------------------------------------------------- Revoke Role
5653:
5654: sub revokerole {
1.357 www 5655: my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21 www 5656: my $now=time;
1.357 www 5657: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21 www 5658: }
5659:
5660: # ---------------------------------------------------------- Revoke Custom Role
5661:
5662: sub revokecustomrole {
1.357 www 5663: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21 www 5664: my $now=time;
1.357 www 5665: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
5666: $deleteflag);
1.17 www 5667: }
5668:
1.533 banghart 5669: # ------------------------------------------------------------ Disk usage
1.535 albertel 5670: sub diskusage {
1.533 banghart 5671: my ($udom,$uname,$directoryRoot)=@_;
5672: $directoryRoot =~ s/\/$//;
1.535 albertel 5673: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514 albertel 5674: return $listing;
1.512 banghart 5675: }
5676:
1.566 banghart 5677: sub is_locked {
5678: my ($file_name, $domain, $user) = @_;
5679: my @check;
5680: my $is_locked;
5681: push @check, $file_name;
1.613 albertel 5682: my %locked = &get('file_permissions',\@check,
1.620 albertel 5683: $env{'user.domain'},$env{'user.name'});
1.615 albertel 5684: my ($tmp)=keys(%locked);
5685: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 5686:
1.566 banghart 5687: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 5688: $is_locked = 'false';
5689: foreach my $entry (@{$locked{$file_name}}) {
5690: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 5691: $is_locked = 'true';
5692: last;
1.745 raeburn 5693: }
5694: }
1.566 banghart 5695: } else {
5696: $is_locked = 'false';
5697: }
5698: }
5699:
1.759 albertel 5700: sub declutter_portfile {
5701: my ($file) = @_;
1.833 albertel 5702: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 5703: return $file;
5704: }
5705:
1.559 banghart 5706: # ------------------------------------------------------------- Mark as Read Only
5707:
5708: sub mark_as_readonly {
5709: my ($domain,$user,$files,$what) = @_;
1.613 albertel 5710: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5711: my ($tmp)=keys(%current_permissions);
5712: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 5713: foreach my $file (@{$files}) {
1.759 albertel 5714: $file = &declutter_portfile($file);
1.561 banghart 5715: push(@{$current_permissions{$file}},$what);
1.559 banghart 5716: }
1.613 albertel 5717: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 5718: return;
5719: }
5720:
1.572 banghart 5721: # ------------------------------------------------------------Save Selected Files
5722:
5723: sub save_selected_files {
5724: my ($user, $path, @files) = @_;
5725: my $filename = $user."savedfiles";
1.573 banghart 5726: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 5727: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 5728: foreach my $file (@files) {
1.620 albertel 5729: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 5730: }
5731: foreach my $file (@other_files) {
1.574 banghart 5732: print (OUT $file."\n");
1.572 banghart 5733: }
1.574 banghart 5734: close (OUT);
1.572 banghart 5735: return 'ok';
5736: }
5737:
1.574 banghart 5738: sub clear_selected_files {
5739: my ($user) = @_;
5740: my $filename = $user."savedfiles";
5741: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5742: print (OUT undef);
5743: close (OUT);
5744: return ("ok");
5745: }
5746:
1.572 banghart 5747: sub files_in_path {
5748: my ($user, $path) = @_;
5749: my $filename = $user."savedfiles";
5750: my %return_files;
1.574 banghart 5751: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 5752: while (my $line_in = <IN>) {
1.574 banghart 5753: chomp ($line_in);
5754: my @paths_and_file = split (m!/!, $line_in);
5755: my $file_part = pop (@paths_and_file);
5756: my $path_part = join ('/', @paths_and_file);
1.573 banghart 5757: $path_part.='/';
5758: my $path_and_file = $path_part.$file_part;
5759: if ($path_part eq $path) {
5760: $return_files{$file_part}= 'selected';
5761: }
5762: }
1.574 banghart 5763: close (IN);
5764: return (\%return_files);
1.572 banghart 5765: }
5766:
5767: # called in portfolio select mode, to show files selected NOT in current directory
5768: sub files_not_in_path {
5769: my ($user, $path) = @_;
5770: my $filename = $user."savedfiles";
5771: my @return_files;
5772: my $path_part;
1.800 albertel 5773: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5774: while (my $line = <IN>) {
1.572 banghart 5775: #ok, I know it's clunky, but I want it to work
1.800 albertel 5776: my @paths_and_file = split(m|/|, $line);
5777: my $file_part = pop(@paths_and_file);
5778: chomp($file_part);
5779: my $path_part = join('/', @paths_and_file);
1.572 banghart 5780: $path_part .= '/';
5781: my $path_and_file = $path_part.$file_part;
5782: if ($path_part ne $path) {
1.800 albertel 5783: push(@return_files, ($path_and_file));
1.572 banghart 5784: }
5785: }
1.800 albertel 5786: close(OUT);
1.574 banghart 5787: return (@return_files);
1.572 banghart 5788: }
5789:
1.745 raeburn 5790: #----------------------------------------------Get portfolio file permissions
1.629 banghart 5791:
1.745 raeburn 5792: sub get_portfile_permissions {
5793: my ($domain,$user) = @_;
1.613 albertel 5794: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5795: my ($tmp)=keys(%current_permissions);
5796: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 5797: return \%current_permissions;
5798: }
5799:
5800: #---------------------------------------------Get portfolio file access controls
5801:
1.749 raeburn 5802: sub get_access_controls {
1.745 raeburn 5803: my ($current_permissions,$group,$file) = @_;
1.769 albertel 5804: my %access;
5805: my $real_file = $file;
5806: $file =~ s/\.meta$//;
1.745 raeburn 5807: if (defined($file)) {
1.749 raeburn 5808: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
5809: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 5810: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 5811: }
5812: }
1.745 raeburn 5813: } else {
1.749 raeburn 5814: foreach my $key (keys(%{$current_permissions})) {
5815: if ($key =~ /\0accesscontrol$/) {
5816: if (defined($group)) {
5817: if ($key !~ m-^\Q$group\E/-) {
5818: next;
5819: }
5820: }
5821: my ($fullpath) = split(/\0/,$key);
5822: if (ref($$current_permissions{$key}) eq 'HASH') {
5823: foreach my $control (keys(%{$$current_permissions{$key}})) {
5824: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
5825: }
5826: }
5827: }
5828: }
5829: }
5830: return %access;
5831: }
5832:
5833: sub modify_access_controls {
5834: my ($file_name,$changes,$domain,$user)=@_;
5835: my ($outcome,$deloutcome);
5836: my %store_permissions;
5837: my %new_values;
5838: my %new_control;
5839: my %translation;
5840: my @deletions = ();
5841: my $now = time;
5842: if (exists($$changes{'activate'})) {
5843: if (ref($$changes{'activate'}) eq 'HASH') {
5844: my @newitems = sort(keys(%{$$changes{'activate'}}));
5845: my $numnew = scalar(@newitems);
5846: for (my $i=0; $i<$numnew; $i++) {
5847: my $newkey = $newitems[$i];
5848: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 5849: if ($newkey =~ /^\d+:/) {
5850: $newkey =~ s/^(\d+)/$newid/;
5851: $translation{$1} = $newid;
5852: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
5853: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
5854: $translation{$1} = $newid;
5855: }
1.749 raeburn 5856: $new_values{$file_name."\0".$newkey} =
5857: $$changes{'activate'}{$newitems[$i]};
5858: $new_control{$newkey} = $now;
5859: }
5860: }
5861: }
5862: my %todelete;
5863: my %changed_items;
5864: foreach my $action ('delete','update') {
5865: if (exists($$changes{$action})) {
5866: if (ref($$changes{$action}) eq 'HASH') {
5867: foreach my $key (keys(%{$$changes{$action}})) {
5868: my ($itemnum) = ($key =~ /^([^:]+):/);
5869: if ($action eq 'delete') {
5870: $todelete{$itemnum} = 1;
5871: } else {
5872: $changed_items{$itemnum} = $key;
5873: }
5874: }
1.745 raeburn 5875: }
5876: }
1.749 raeburn 5877: }
5878: # get lock on access controls for file.
5879: my $lockhash = {
5880: $file_name."\0".'locked_access_records' => $env{'user.name'}.
5881: ':'.$env{'user.domain'},
5882: };
5883: my $tries = 0;
5884: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5885:
5886: while (($gotlock ne 'ok') && $tries <3) {
5887: $tries ++;
5888: sleep 1;
5889: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5890: }
5891: if ($gotlock eq 'ok') {
5892: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
5893: my ($tmp)=keys(%curr_permissions);
5894: if ($tmp=~/^error:/) { undef(%curr_permissions); }
5895: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
5896: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
5897: if (ref($curr_controls) eq 'HASH') {
5898: foreach my $control_item (keys(%{$curr_controls})) {
5899: my ($itemnum) = ($control_item =~ /^([^:]+):/);
5900: if (defined($todelete{$itemnum})) {
5901: push(@deletions,$file_name."\0".$control_item);
5902: } else {
5903: if (defined($changed_items{$itemnum})) {
5904: $new_control{$changed_items{$itemnum}} = $now;
5905: push(@deletions,$file_name."\0".$control_item);
5906: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
5907: } else {
5908: $new_control{$control_item} = $$curr_controls{$control_item};
5909: }
5910: }
1.745 raeburn 5911: }
5912: }
5913: }
1.749 raeburn 5914: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
5915: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
5916: $outcome = &put('file_permissions',\%new_values,$domain,$user);
5917: # remove lock
5918: my @del_lock = ($file_name."\0".'locked_access_records');
5919: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 5920: my ($file,$group);
5921: if (&is_course($domain,$user)) {
5922: ($group,$file) = split(/\//,$file_name,2);
5923: } else {
5924: $file = $file_name;
5925: }
5926: my $sqlresult =
5927: &update_portfolio_table($user,$domain,$file,'portfolio_access',
5928: $group);
1.749 raeburn 5929: } else {
5930: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 5931: }
1.749 raeburn 5932: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 5933: }
5934:
1.827 raeburn 5935: sub make_public_indefinitely {
5936: my ($requrl) = @_;
5937: my $now = time;
5938: my $action = 'activate';
5939: my $aclnum = 0;
5940: if (&is_portfolio_url($requrl)) {
5941: my (undef,$udom,$unum,$file_name,$group) =
5942: &parse_portfolio_url($requrl);
5943: my $current_perms = &get_portfile_permissions($udom,$unum);
5944: my %access_controls = &get_access_controls($current_perms,
5945: $group,$file_name);
5946: foreach my $key (keys(%{$access_controls{$file_name}})) {
5947: my ($num,$scope,$end,$start) =
5948: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5949: if ($scope eq 'public') {
5950: if ($start <= $now && $end == 0) {
5951: $action = 'none';
5952: } else {
5953: $action = 'update';
5954: $aclnum = $num;
5955: }
5956: last;
5957: }
5958: }
5959: if ($action eq 'none') {
5960: return 'ok';
5961: } else {
5962: my %changes;
5963: my $newend = 0;
5964: my $newstart = $now;
5965: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
5966: $changes{$action}{$newkey} = {
5967: type => 'public',
5968: time => {
5969: start => $newstart,
5970: end => $newend,
5971: },
5972: };
5973: my ($outcome,$deloutcome,$new_values,$translation) =
5974: &modify_access_controls($file_name,\%changes,$udom,$unum);
5975: return $outcome;
5976: }
5977: } else {
5978: return 'invalid';
5979: }
5980: }
5981:
1.745 raeburn 5982: #------------------------------------------------------Get Marked as Read Only
5983:
5984: sub get_marked_as_readonly {
5985: my ($domain,$user,$what,$group) = @_;
5986: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 5987: my @readonly_files;
1.629 banghart 5988: my $cmp1=$what;
5989: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 5990: while (my ($file_name,$value) = each(%{$current_permissions})) {
5991: if (defined($group)) {
5992: if ($file_name !~ m-^\Q$group\E/-) {
5993: next;
5994: }
5995: }
1.561 banghart 5996: if (ref($value) eq "ARRAY"){
5997: foreach my $stored_what (@{$value}) {
1.629 banghart 5998: my $cmp2=$stored_what;
1.759 albertel 5999: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 6000: $cmp2=join('',@{$stored_what});
1.745 raeburn 6001: }
1.629 banghart 6002: if ($cmp1 eq $cmp2) {
1.561 banghart 6003: push(@readonly_files, $file_name);
1.745 raeburn 6004: last;
1.563 banghart 6005: } elsif (!defined($what)) {
6006: push(@readonly_files, $file_name);
1.745 raeburn 6007: last;
1.561 banghart 6008: }
6009: }
1.745 raeburn 6010: }
1.561 banghart 6011: }
6012: return @readonly_files;
6013: }
1.577 banghart 6014: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 6015:
1.577 banghart 6016: sub get_marked_as_readonly_hash {
1.745 raeburn 6017: my ($current_permissions,$group,$what) = @_;
1.577 banghart 6018: my %readonly_files;
1.745 raeburn 6019: while (my ($file_name,$value) = each(%{$current_permissions})) {
6020: if (defined($group)) {
6021: if ($file_name !~ m-^\Q$group\E/-) {
6022: next;
6023: }
6024: }
1.577 banghart 6025: if (ref($value) eq "ARRAY"){
6026: foreach my $stored_what (@{$value}) {
1.745 raeburn 6027: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 6028: foreach my $lock_descriptor(@{$stored_what}) {
6029: if ($lock_descriptor eq 'graded') {
6030: $readonly_files{$file_name} = 'graded';
6031: } elsif ($lock_descriptor eq 'handback') {
6032: $readonly_files{$file_name} = 'handback';
6033: } else {
6034: if (!exists($readonly_files{$file_name})) {
6035: $readonly_files{$file_name} = 'locked';
6036: }
6037: }
1.745 raeburn 6038: }
1.750 banghart 6039: }
1.577 banghart 6040: }
6041: }
6042: }
6043: return %readonly_files;
6044: }
1.559 banghart 6045: # ------------------------------------------------------------ Unmark as Read Only
6046:
6047: sub unmark_as_readonly {
1.629 banghart 6048: # unmarks $file_name (if $file_name is defined), or all files locked by $what
6049: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 6050: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 6051: $file_name = &declutter_portfile($file_name);
1.634 albertel 6052: my $symb_crs = $what;
6053: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 6054: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 6055: my ($tmp)=keys(%current_permissions);
6056: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6057: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 6058: foreach my $file (@readonly_files) {
1.759 albertel 6059: my $clean_file = &declutter_portfile($file);
6060: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 6061: my $current_locks = $current_permissions{$file};
1.563 banghart 6062: my @new_locks;
6063: my @del_keys;
6064: if (ref($current_locks) eq "ARRAY"){
6065: foreach my $locker (@{$current_locks}) {
1.632 albertel 6066: my $compare=$locker;
1.749 raeburn 6067: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 6068: $compare=join('',@{$locker});
1.746 raeburn 6069: if ($compare ne $symb_crs) {
6070: push(@new_locks, $locker);
6071: }
1.563 banghart 6072: }
6073: }
1.650 albertel 6074: if (scalar(@new_locks) > 0) {
1.563 banghart 6075: $current_permissions{$file} = \@new_locks;
6076: } else {
6077: push(@del_keys, $file);
1.613 albertel 6078: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 6079: delete($current_permissions{$file});
1.563 banghart 6080: }
6081: }
1.561 banghart 6082: }
1.613 albertel 6083: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6084: return;
6085: }
1.512 banghart 6086:
1.17 www 6087: # ------------------------------------------------------------ Directory lister
6088:
6089: sub dirlist {
1.253 stredwic 6090: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
6091:
1.18 www 6092: $uri=~s/^\///;
6093: $uri=~s/\/$//;
1.253 stredwic 6094: my ($udom, $uname);
6095: (undef,$udom,$uname)=split(/\//,$uri);
6096: if(defined($userdomain)) {
6097: $udom = $userdomain;
6098: }
6099: if(defined($username)) {
6100: $uname = $username;
6101: }
6102:
6103: my $dirRoot = $perlvar{'lonDocRoot'};
6104: if(defined($alternateDirectoryRoot)) {
6105: $dirRoot = $alternateDirectoryRoot;
6106: $dirRoot =~ s/\/$//;
1.751 banghart 6107: }
1.253 stredwic 6108:
6109: if($udom) {
6110: if($uname) {
1.800 albertel 6111: my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
6112: &homeserver($uname,$udom));
1.605 matthew 6113: my @listing_results;
6114: if ($listing eq 'unknown_cmd') {
1.800 albertel 6115: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
6116: &homeserver($uname,$udom));
1.605 matthew 6117: @listing_results = split(/:/,$listing);
6118: } else {
6119: @listing_results = map { &unescape($_); } split(/:/,$listing);
6120: }
6121: return @listing_results;
1.253 stredwic 6122: } elsif(!defined($alternateDirectoryRoot)) {
1.800 albertel 6123: my %allusers;
1.841 albertel 6124: my %servers = &get_servers($udom,'library');
6125: foreach my $tryserver (keys(%servers)) {
6126: my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
6127: $udom, $tryserver);
6128: my @listing_results;
6129: if ($listing eq 'unknown_cmd') {
6130: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
6131: $udom, $tryserver);
6132: @listing_results = split(/:/,$listing);
6133: } else {
6134: @listing_results =
6135: map { &unescape($_); } split(/:/,$listing);
6136: }
6137: if ($listing_results[0] ne 'no_such_dir' &&
6138: $listing_results[0] ne 'empty' &&
6139: $listing_results[0] ne 'con_lost') {
6140: foreach my $line (@listing_results) {
6141: my ($entry) = split(/&/,$line,2);
6142: $allusers{$entry} = 1;
6143: }
6144: }
1.253 stredwic 6145: }
6146: my $alluserstr='';
1.800 albertel 6147: foreach my $user (sort(keys(%allusers))) {
6148: $alluserstr.=$user.'&user:';
1.253 stredwic 6149: }
6150: $alluserstr=~s/:$//;
6151: return split(/:/,$alluserstr);
6152: } else {
1.800 albertel 6153: return ('missing user name');
1.253 stredwic 6154: }
6155: } elsif(!defined($alternateDirectoryRoot)) {
1.841 albertel 6156: my @all_domains = sort(&all_domains());
6157: foreach my $domain (@all_domains) {
6158: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
6159: }
6160: return @all_domains;
6161: } else {
1.800 albertel 6162: return ('missing domain');
1.275 stredwic 6163: }
6164: }
6165:
6166: # --------------------------------------------- GetFileTimestamp
6167: # This function utilizes dirlist and returns the date stamp for
6168: # when it was last modified. It will also return an error of -1
6169: # if an error occurs
6170:
1.410 matthew 6171: ##
6172: ## FIXME: This subroutine assumes its caller knows something about the
6173: ## directory structure of the home server for the student ($root).
6174: ## Not a good assumption to make. Since this is for looking up files
6175: ## in user directories, the full path should be constructed by lond, not
6176: ## whatever machine we request data from.
6177: ##
1.275 stredwic 6178: sub GetFileTimestamp {
6179: my ($studentDomain,$studentName,$filename,$root)=@_;
1.807 albertel 6180: $studentDomain = &LONCAPA::clean_domain($studentDomain);
6181: $studentName = &LONCAPA::clean_username($studentName);
1.275 stredwic 6182: my $subdir=$studentName.'__';
6183: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
6184: my $proname="$studentDomain/$subdir/$studentName";
6185: $proname .= '/'.$filename;
1.375 matthew 6186: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
6187: $studentName, $root);
1.275 stredwic 6188: my @stats = split('&', $fileStat);
6189: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 6190: # @stats contains first the filename, then the stat output
6191: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 6192: } else {
6193: return -1;
1.253 stredwic 6194: }
1.26 www 6195: }
6196:
1.712 albertel 6197: sub stat_file {
6198: my ($uri) = @_;
1.787 albertel 6199: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 6200:
1.712 albertel 6201: my ($udom,$uname,$file,$dir);
6202: if ($uri =~ m-^/(uploaded|editupload)/-) {
6203: ($udom,$uname,$file) =
1.811 albertel 6204: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 6205: $file = 'userfiles/'.$file;
1.740 www 6206: $dir = &propath($udom,$uname);
1.712 albertel 6207: }
6208: if ($uri =~ m-^/res/-) {
6209: ($udom,$uname) =
1.807 albertel 6210: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 6211: $file = $uri;
6212: }
6213:
6214: if (!$udom || !$uname || !$file) {
6215: # unable to handle the uri
6216: return ();
6217: }
6218:
6219: my ($result) = &dirlist($file,$udom,$uname,$dir);
6220: my @stats = split('&', $result);
1.721 banghart 6221:
1.712 albertel 6222: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
6223: shift(@stats); #filename is first
6224: return @stats;
6225: }
6226: return ();
6227: }
6228:
1.26 www 6229: # -------------------------------------------------------- Value of a Condition
6230:
1.713 albertel 6231: # gets the value of a specific preevaluated condition
6232: # stored in the string $env{user.state.<cid>}
6233: # or looks up a condition reference in the bighash and if if hasn't
6234: # already been evaluated recurses into docondval to get the value of
6235: # the condition, then memoizing it to
6236: # $env{user.state.<cid>.<condition>}
1.40 www 6237: sub directcondval {
6238: my $number=shift;
1.620 albertel 6239: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 6240: &Apache::lonuserstate::evalstate();
6241: }
1.713 albertel 6242: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
6243: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
6244: } elsif ($number =~ /^_/) {
6245: my $sub_condition;
6246: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6247: &GDBM_READER(),0640)) {
6248: $sub_condition=$bighash{'conditions'.$number};
6249: untie(%bighash);
6250: }
6251: my $value = &docondval($sub_condition);
6252: &appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
6253: return $value;
6254: }
1.620 albertel 6255: if ($env{'user.state.'.$env{'request.course.id'}}) {
6256: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 6257: } else {
6258: return 2;
6259: }
6260: }
6261:
1.713 albertel 6262: # get the collection of conditions for this resource
1.26 www 6263: sub condval {
6264: my $condidx=shift;
1.54 www 6265: my $allpathcond='';
1.713 albertel 6266: foreach my $cond (split(/\|/,$condidx)) {
6267: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
6268: $allpathcond.=
6269: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
6270: }
1.191 harris41 6271: }
1.54 www 6272: $allpathcond=~s/\|$//;
1.713 albertel 6273: return &docondval($allpathcond);
6274: }
6275:
6276: #evaluates an expression of conditions
6277: sub docondval {
6278: my ($allpathcond) = @_;
6279: my $result=0;
6280: if ($env{'request.course.id'}
6281: && defined($allpathcond)) {
6282: my $operand='|';
6283: my @stack;
6284: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
6285: if ($chunk eq '(') {
6286: push @stack,($operand,$result);
6287: } elsif ($chunk eq ')') {
6288: my $before=pop @stack;
6289: if (pop @stack eq '&') {
6290: $result=$result>$before?$before:$result;
6291: } else {
6292: $result=$result>$before?$result:$before;
6293: }
6294: } elsif (($chunk eq '&') || ($chunk eq '|')) {
6295: $operand=$chunk;
6296: } else {
6297: my $new=directcondval($chunk);
6298: if ($operand eq '&') {
6299: $result=$result>$new?$new:$result;
6300: } else {
6301: $result=$result>$new?$result:$new;
6302: }
6303: }
6304: }
1.26 www 6305: }
6306: return $result;
1.421 albertel 6307: }
6308:
6309: # ---------------------------------------------------- Devalidate courseresdata
6310:
6311: sub devalidatecourseresdata {
6312: my ($coursenum,$coursedomain)=@_;
6313: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6314: &devalidate_cache_new('courseres',$hashid);
1.28 www 6315: }
6316:
1.763 www 6317:
1.200 www 6318: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 6319: #
6320: # Parameters:
6321: # $coursenum - Number of the course.
6322: # $coursedomain - Domain at which the course was created.
6323: # Returns:
6324: # A hash of the course parameters along (I think) with timestamps
6325: # and version info.
1.877 foxr 6326:
1.624 albertel 6327: sub get_courseresdata {
6328: my ($coursenum,$coursedomain)=@_;
1.200 www 6329: my $coursehom=&homeserver($coursenum,$coursedomain);
6330: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6331: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 6332: my %dumpreply;
1.417 albertel 6333: unless (defined($cached)) {
1.624 albertel 6334: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 6335: $result=\%dumpreply;
1.251 albertel 6336: my ($tmp) = keys(%dumpreply);
6337: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 6338: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 6339: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
6340: return $tmp;
1.416 albertel 6341: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 6342: $result=undef;
1.599 albertel 6343: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 6344: }
6345: }
1.624 albertel 6346: return $result;
6347: }
6348:
1.633 albertel 6349: sub devalidateuserresdata {
6350: my ($uname,$udom)=@_;
6351: my $hashid="$udom:$uname";
6352: &devalidate_cache_new('userres',$hashid);
6353: }
6354:
1.624 albertel 6355: sub get_userresdata {
6356: my ($uname,$udom)=@_;
6357: #most student don\'t have any data set, check if there is some data
6358: if (&EXT_cache_status($udom,$uname)) { return undef; }
6359:
6360: my $hashid="$udom:$uname";
6361: my ($result,$cached)=&is_cached_new('userres',$hashid);
6362: if (!defined($cached)) {
6363: my %resourcedata=&dump('resourcedata',$udom,$uname);
6364: $result=\%resourcedata;
6365: &do_cache_new('userres',$hashid,$result,600);
6366: }
6367: my ($tmp)=keys(%$result);
6368: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
6369: return $result;
6370: }
6371: #error 2 occurs when the .db doesn't exist
6372: if ($tmp!~/error: 2 /) {
1.672 albertel 6373: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 6374: " Trying to get resource data for ".
6375: $uname." at ".$udom.": ".
6376: $tmp."</font>");
6377: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 6378: #&EXT_cache_set($udom,$uname);
6379: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 6380: undef($tmp); # not really an error so don't send it back
1.624 albertel 6381: }
6382: return $tmp;
6383: }
1.879 foxr 6384: #----------------------------------------------- resdata - return resource data
6385: # Purpose:
6386: # Return resource data for either users or for a course.
6387: # Parameters:
6388: # $name - Course/user name.
6389: # $domain - Name of the domain the user/course is registered on.
6390: # $type - Type of thing $name is (must be 'course' or 'user'
6391: # @which - Array of names of resources desired.
6392: # Returns:
6393: # The value of the first reasource in @which that is found in the
6394: # resource hash.
6395: # Exceptional Conditions:
6396: # If the $type passed in is not valid (not the string 'course' or
6397: # 'user', an undefined reference is returned.
6398: # If none of the resources are found, an undef is returned
1.624 albertel 6399: sub resdata {
6400: my ($name,$domain,$type,@which)=@_;
6401: my $result;
6402: if ($type eq 'course') {
6403: $result=&get_courseresdata($name,$domain);
6404: } elsif ($type eq 'user') {
6405: $result=&get_userresdata($name,$domain);
6406: }
6407: if (!ref($result)) { return $result; }
1.251 albertel 6408: foreach my $item (@which) {
1.927 albertel 6409: if (defined($result->{$item->[0]})) {
6410: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 6411: }
1.250 albertel 6412: }
1.291 albertel 6413: return undef;
1.200 www 6414: }
6415:
1.379 matthew 6416: #
6417: # EXT resource caching routines
6418: #
6419:
6420: sub clear_EXT_cache_status {
1.383 albertel 6421: &delenv('cache.EXT.');
1.379 matthew 6422: }
6423:
6424: sub EXT_cache_status {
6425: my ($target_domain,$target_user) = @_;
1.383 albertel 6426: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 6427: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 6428: # We know already the user has no data
6429: return 1;
6430: } else {
6431: return 0;
6432: }
6433: }
6434:
6435: sub EXT_cache_set {
6436: my ($target_domain,$target_user) = @_;
1.383 albertel 6437: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633 albertel 6438: #&appenv($cachename => time);
1.379 matthew 6439: }
6440:
1.28 www 6441: # --------------------------------------------------------- Value of a Variable
1.58 www 6442: sub EXT {
1.715 albertel 6443:
1.395 albertel 6444: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 6445: unless ($varname) { return ''; }
1.218 albertel 6446: #get real user name/domain, courseid and symb
6447: my $courseid;
1.359 albertel 6448: my $publicuser;
1.427 www 6449: if ($symbparm) {
6450: $symbparm=&get_symb_from_alias($symbparm);
6451: }
1.218 albertel 6452: if (!($uname && $udom)) {
1.790 albertel 6453: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 6454: if (!$symbparm) { $symbparm=$cursymb; }
6455: } else {
1.620 albertel 6456: $courseid=$env{'request.course.id'};
1.218 albertel 6457: }
1.48 www 6458: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
6459: my $rest;
1.320 albertel 6460: if (defined($therest[0])) {
1.48 www 6461: $rest=join('.',@therest);
6462: } else {
6463: $rest='';
6464: }
1.320 albertel 6465:
1.57 www 6466: my $qualifierrest=$qualifier;
6467: if ($rest) { $qualifierrest.='.'.$rest; }
6468: my $spacequalifierrest=$space;
6469: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 6470: if ($realm eq 'user') {
1.48 www 6471: # --------------------------------------------------------------- user.resource
6472: if ($space eq 'resource') {
1.651 albertel 6473: if ( (defined($Apache::lonhomework::parsing_a_problem)
6474: || defined($Apache::lonhomework::parsing_a_task))
6475: &&
1.744 albertel 6476: ($symbparm eq &symbread()) ) {
6477: # if we are in the middle of processing the resource the
6478: # get the value we are planning on committing
6479: if (defined($Apache::lonhomework::results{$qualifierrest})) {
6480: return $Apache::lonhomework::results{$qualifierrest};
6481: } else {
6482: return $Apache::lonhomework::history{$qualifierrest};
6483: }
1.335 albertel 6484: } else {
1.359 albertel 6485: my %restored;
1.620 albertel 6486: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 6487: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
6488: } else {
6489: %restored=&restore($symbparm,$courseid,$udom,$uname);
6490: }
1.335 albertel 6491: return $restored{$qualifierrest};
6492: }
1.48 www 6493: # ----------------------------------------------------------------- user.access
6494: } elsif ($space eq 'access') {
1.218 albertel 6495: # FIXME - not supporting calls for a specific user
1.48 www 6496: return &allowed($qualifier,$rest);
6497: # ------------------------------------------ user.preferences, user.environment
6498: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 6499: if (($uname eq $env{'user.name'}) &&
6500: ($udom eq $env{'user.domain'})) {
6501: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 6502: } else {
1.359 albertel 6503: my %returnhash;
6504: if (!$publicuser) {
6505: %returnhash=&userenvironment($udom,$uname,
6506: $qualifierrest);
6507: }
1.218 albertel 6508: return $returnhash{$qualifierrest};
6509: }
1.48 www 6510: # ----------------------------------------------------------------- user.course
6511: } elsif ($space eq 'course') {
1.218 albertel 6512: # FIXME - not supporting calls for a specific user
1.620 albertel 6513: return $env{join('.',('request.course',$qualifier))};
1.48 www 6514: # ------------------------------------------------------------------- user.role
6515: } elsif ($space eq 'role') {
1.218 albertel 6516: # FIXME - not supporting calls for a specific user
1.620 albertel 6517: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 6518: if ($qualifier eq 'value') {
6519: return $role;
6520: } elsif ($qualifier eq 'extent') {
6521: return $where;
6522: }
6523: # ----------------------------------------------------------------- user.domain
6524: } elsif ($space eq 'domain') {
1.218 albertel 6525: return $udom;
1.48 www 6526: # ------------------------------------------------------------------- user.name
6527: } elsif ($space eq 'name') {
1.218 albertel 6528: return $uname;
1.48 www 6529: # ---------------------------------------------------- Any other user namespace
1.29 www 6530: } else {
1.359 albertel 6531: my %reply;
6532: if (!$publicuser) {
6533: %reply=&get($space,[$qualifierrest],$udom,$uname);
6534: }
6535: return $reply{$qualifierrest};
1.48 www 6536: }
1.236 www 6537: } elsif ($realm eq 'query') {
6538: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 6539: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
6540: [$spacequalifierrest]);
1.620 albertel 6541: return $env{'form.'.$spacequalifierrest};
1.236 www 6542: } elsif ($realm eq 'request') {
1.48 www 6543: # ------------------------------------------------------------- request.browser
6544: if ($space eq 'browser') {
1.430 www 6545: if ($qualifier eq 'textremote') {
1.676 albertel 6546: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 6547: return 1;
6548: } else {
6549: return 0;
6550: }
6551: } else {
1.620 albertel 6552: return $env{'browser.'.$qualifier};
1.430 www 6553: }
1.57 www 6554: # ------------------------------------------------------------ request.filename
6555: } else {
1.620 albertel 6556: return $env{'request.'.$spacequalifierrest};
1.29 www 6557: }
1.28 www 6558: } elsif ($realm eq 'course') {
1.48 www 6559: # ---------------------------------------------------------- course.description
1.620 albertel 6560: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 6561: } elsif ($realm eq 'resource') {
1.165 www 6562:
1.620 albertel 6563: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 6564: if (!$symbparm) { $symbparm=&symbread(); }
6565: }
1.693 albertel 6566:
6567: if ($space eq 'title') {
6568: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
6569: return &gettitle($symbparm);
6570: }
6571:
6572: if ($space eq 'map') {
6573: my ($map) = &decode_symb($symbparm);
6574: return &symbread($map);
6575: }
1.905 albertel 6576: if ($space eq 'filename') {
6577: if ($symbparm) {
6578: return &clutter((&decode_symb($symbparm))[2]);
6579: }
6580: return &hreflocation('',$env{'request.filename'});
6581: }
1.693 albertel 6582:
6583: my ($section, $group, @groups);
1.593 albertel 6584: my ($courselevelm,$courselevel);
1.539 albertel 6585: if ($symbparm && defined($courseid) &&
1.620 albertel 6586: $courseid eq $env{'request.course.id'}) {
1.165 www 6587:
1.218 albertel 6588: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 6589:
1.60 www 6590: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 6591: my $symbp=$symbparm;
1.735 albertel 6592: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 6593:
6594: my $symbparm=$symbp.'.'.$spacequalifierrest;
6595: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
6596:
1.620 albertel 6597: if (($env{'user.name'} eq $uname) &&
6598: ($env{'user.domain'} eq $udom)) {
6599: $section=$env{'request.course.sec'};
1.733 raeburn 6600: @groups = split(/:/,$env{'request.course.groups'});
6601: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 6602: } else {
1.539 albertel 6603: if (! defined($usection)) {
1.551 albertel 6604: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 6605: } else {
6606: $section = $usection;
6607: }
1.733 raeburn 6608: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 6609: }
6610:
6611: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
6612: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
6613: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
6614:
1.593 albertel 6615: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 6616: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 6617: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 6618:
1.60 www 6619: # ----------------------------------------------------------- first, check user
1.624 albertel 6620:
6621: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 6622: ([$courselevelr,'resource'],
6623: [$courselevelm,'map' ],
6624: [$courselevel, 'course' ]));
1.931 albertel 6625: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 6626:
1.594 albertel 6627: # ------------------------------------------------ second, check some of course
1.684 raeburn 6628: my $coursereply;
1.691 raeburn 6629: if (@groups > 0) {
6630: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
6631: $mapparm,$spacequalifierrest);
1.927 albertel 6632: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 6633: }
1.96 www 6634:
1.684 raeburn 6635: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 6636: $env{'course.'.$courseid.'.domain'},
6637: 'course',
6638: ([$seclevelr, 'resource'],
6639: [$seclevelm, 'map' ],
6640: [$seclevel, 'course' ],
6641: [$courselevelr,'resource']));
6642: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 6643:
1.60 www 6644: # ------------------------------------------------------ third, check map parms
1.218 albertel 6645: my %parmhash=();
6646: my $thisparm='';
6647: if (tie(%parmhash,'GDBM_File',
1.620 albertel 6648: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 6649: &GDBM_READER(),0640)) {
1.218 albertel 6650: $thisparm=$parmhash{$symbparm};
6651: untie(%parmhash);
6652: }
1.927 albertel 6653: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 6654: }
1.594 albertel 6655: # ------------------------------------------ fourth, look in resource metadata
1.71 www 6656:
1.218 albertel 6657: $spacequalifierrest=~s/\./\_/;
1.282 albertel 6658: my $filename;
6659: if (!$symbparm) { $symbparm=&symbread(); }
6660: if ($symbparm) {
1.409 www 6661: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 6662: } else {
1.620 albertel 6663: $filename=$env{'request.filename'};
1.282 albertel 6664: }
6665: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 6666: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 6667: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 6668: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 6669:
1.927 albertel 6670: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 6671: if ($symbparm && defined($courseid) &&
1.620 albertel 6672: $courseid eq $env{'request.course.id'}) {
1.624 albertel 6673: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
6674: $env{'course.'.$courseid.'.domain'},
6675: 'course',
1.927 albertel 6676: ([$courselevelm,'map' ],
6677: [$courselevel, 'course']));
6678: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 6679: }
1.145 www 6680: # ------------------------------------------------------------------ Cascade up
1.218 albertel 6681: unless ($space eq '0') {
1.336 albertel 6682: my @parts=split(/_/,$space);
6683: my $id=pop(@parts);
6684: my $part=join('_',@parts);
6685: if ($part eq '') { $part='0'; }
1.927 albertel 6686: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 6687: $symbparm,$udom,$uname,$section,1);
1.927 albertel 6688: if (@partgeneral) { return &get_reply(\@partgeneral); }
1.218 albertel 6689: }
1.395 albertel 6690: if ($recurse) { return undef; }
6691: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 6692: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 6693: # ---------------------------------------------------- Any other user namespace
6694: } elsif ($realm eq 'environment') {
6695: # ----------------------------------------------------------------- environment
1.620 albertel 6696: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
6697: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 6698: } else {
1.770 albertel 6699: if ($uname eq 'anonymous' && $udom eq '') {
6700: return '';
6701: }
1.219 albertel 6702: my %returnhash=&userenvironment($udom,$uname,
6703: $spacequalifierrest);
6704: return $returnhash{$spacequalifierrest};
6705: }
1.28 www 6706: } elsif ($realm eq 'system') {
1.48 www 6707: # ----------------------------------------------------------------- system.time
6708: if ($space eq 'time') {
6709: return time;
6710: }
1.696 albertel 6711: } elsif ($realm eq 'server') {
6712: # ----------------------------------------------------------------- system.time
6713: if ($space eq 'name') {
6714: return $ENV{'SERVER_NAME'};
6715: }
1.28 www 6716: }
1.48 www 6717: return '';
1.61 www 6718: }
6719:
1.927 albertel 6720: sub get_reply {
6721: my ($reply_value) = @_;
6722: if (wantarray) {
6723: return @$reply_value;
6724: }
6725: return $reply_value->[0];
6726: }
6727:
1.691 raeburn 6728: sub check_group_parms {
6729: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
6730: my @groupitems = ();
6731: my $resultitem;
1.927 albertel 6732: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 6733: foreach my $group (@{$groups}) {
6734: foreach my $level (@levels) {
1.927 albertel 6735: my $item = $courseid.'.['.$group.'].'.$level->[0];
6736: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 6737: }
6738: }
6739: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
6740: $env{'course.'.$courseid.'.domain'},
6741: 'course',@groupitems);
6742: return $coursereply;
6743: }
6744:
6745: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 6746: my ($courseid,@groups) = @_;
6747: @groups = sort(@groups);
1.691 raeburn 6748: return @groups;
6749: }
6750:
1.395 albertel 6751: sub packages_tab_default {
6752: my ($uri,$varname)=@_;
6753: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 6754:
6755: my (@extension,@specifics,$do_default);
6756: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 6757: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 6758: if ($pack_type eq 'default') {
6759: $do_default=1;
6760: } elsif ($pack_type eq 'extension') {
6761: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 6762: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 6763: # only look at packages defaults for packages that this id is
1.738 albertel 6764: push(@specifics,[$package,$pack_type,$pack_part]);
6765: }
6766: }
6767: # first look for a package that matches the requested part id
6768: foreach my $package (@specifics) {
6769: my (undef,$pack_type,$pack_part)=@{$package};
6770: next if ($pack_part ne $part);
6771: if (defined($packagetab{"$pack_type&$name&default"})) {
6772: return $packagetab{"$pack_type&$name&default"};
6773: }
6774: }
6775: # look for any possible matching non extension_ package
6776: foreach my $package (@specifics) {
6777: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 6778: if (defined($packagetab{"$pack_type&$name&default"})) {
6779: return $packagetab{"$pack_type&$name&default"};
6780: }
1.585 albertel 6781: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 6782: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
6783: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 6784: }
6785: }
1.738 albertel 6786: # look for any posible extension_ match
6787: foreach my $package (@extension) {
6788: my ($package,$pack_type)=@{$package};
6789: if (defined($packagetab{"$pack_type&$name&default"})) {
6790: return $packagetab{"$pack_type&$name&default"};
6791: }
6792: if (defined($packagetab{$package."&$name&default"})) {
6793: return $packagetab{$package."&$name&default"};
6794: }
6795: }
6796: # look for a global default setting
6797: if ($do_default && defined($packagetab{"default&$name&default"})) {
6798: return $packagetab{"default&$name&default"};
6799: }
1.395 albertel 6800: return undef;
6801: }
6802:
1.334 albertel 6803: sub add_prefix_and_part {
6804: my ($prefix,$part)=@_;
6805: my $keyroot;
6806: if (defined($prefix) && $prefix !~ /^__/) {
6807: # prefix that has a part already
6808: $keyroot=$prefix;
6809: } elsif (defined($prefix)) {
6810: # prefix that is missing a part
6811: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
6812: } else {
6813: # no prefix at all
6814: if (defined($part)) { $keyroot='_'.$part; }
6815: }
6816: return $keyroot;
6817: }
6818:
1.71 www 6819: # ---------------------------------------------------------------- Get metadata
6820:
1.599 albertel 6821: my %metaentry;
1.71 www 6822: sub metadata {
1.176 www 6823: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 6824: $uri=&declutter($uri);
1.288 albertel 6825: # if it is a non metadata possible uri return quickly
1.529 albertel 6826: if (($uri eq '') ||
6827: (($uri =~ m|^/*adm/|) &&
1.698 albertel 6828: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 6829: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
6830: return undef;
6831: }
6832: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
6833: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 6834: return undef;
1.288 albertel 6835: }
1.73 www 6836: my $filename=$uri;
6837: $uri=~s/\.meta$//;
1.172 www 6838: #
6839: # Is the metadata already cached?
1.177 www 6840: # Look at timestamp of caching
1.172 www 6841: # Everything is cached by the main uri, libraries are never directly cached
6842: #
1.428 albertel 6843: if (!defined($liburi)) {
1.599 albertel 6844: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 6845: if (defined($cached)) { return $result->{':'.$what}; }
6846: }
6847: {
1.172 www 6848: #
6849: # Is this a recursive call for a library?
6850: #
1.599 albertel 6851: # if (! exists($metacache{$uri})) {
6852: # $metacache{$uri}={};
6853: # }
1.924 albertel 6854: my $cachetime = 60*60;
1.171 www 6855: if ($liburi) {
6856: $liburi=&declutter($liburi);
6857: $filename=$liburi;
1.401 bowersj2 6858: } else {
1.599 albertel 6859: &devalidate_cache_new('meta',$uri);
6860: undef(%metaentry);
1.401 bowersj2 6861: }
1.140 www 6862: my %metathesekeys=();
1.73 www 6863: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 6864: my $metastring;
1.924 albertel 6865: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 6866: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 6867: $metastring =
1.929 albertel 6868: &Apache::lonnet::ssi_body($which,
1.924 albertel 6869: ('grade_target' => 'meta'));
6870: $cachetime = 1; # only want this cached in the child not long term
6871: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 6872: my $file=&filelocation('',&clutter($filename));
1.599 albertel 6873: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 6874: $metastring=&getfile($file);
1.489 albertel 6875: }
1.208 albertel 6876: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 6877: my $token;
1.140 www 6878: undef %metathesekeys;
1.71 www 6879: while ($token=$parser->get_token) {
1.339 albertel 6880: if ($token->[0] eq 'S') {
6881: if (defined($token->[2]->{'package'})) {
1.172 www 6882: #
6883: # This is a package - get package info
6884: #
1.339 albertel 6885: my $package=$token->[2]->{'package'};
6886: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6887: if (defined($token->[2]->{'id'})) {
6888: $keyroot.='_'.$token->[2]->{'id'};
6889: }
1.599 albertel 6890: if ($metaentry{':packages'}) {
6891: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 6892: } else {
1.599 albertel 6893: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 6894: }
1.736 albertel 6895: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 6896: my $part=$keyroot;
6897: $part=~s/^\_//;
1.736 albertel 6898: if ($pack_entry=~/^\Q$package\E\&/ ||
6899: $pack_entry=~/^\Q$package\E_0\&/) {
6900: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 6901: # ignore package.tab specified default values
6902: # here &package_tab_default() will fetch those
6903: if ($subp eq 'default') { next; }
1.736 albertel 6904: my $value=$packagetab{$pack_entry};
1.432 albertel 6905: my $unikey;
6906: if ($pack =~ /_0$/) {
6907: $unikey='parameter_0_'.$name;
6908: $part=0;
6909: } else {
6910: $unikey='parameter'.$keyroot.'_'.$name;
6911: }
1.339 albertel 6912: if ($subp eq 'display') {
6913: $value.=' [Part: '.$part.']';
6914: }
1.599 albertel 6915: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 6916: $metathesekeys{$unikey}=1;
1.599 albertel 6917: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6918: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 6919: }
1.599 albertel 6920: if (defined($metaentry{':'.$unikey.'.default'})) {
6921: $metaentry{':'.$unikey}=
6922: $metaentry{':'.$unikey.'.default'};
1.356 albertel 6923: }
1.339 albertel 6924: }
6925: }
6926: } else {
1.172 www 6927: #
6928: # This is not a package - some other kind of start tag
1.339 albertel 6929: #
6930: my $entry=$token->[1];
6931: my $unikey;
6932: if ($entry eq 'import') {
6933: $unikey='';
6934: } else {
6935: $unikey=$entry;
6936: }
6937: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6938:
6939: if (defined($token->[2]->{'id'})) {
6940: $unikey.='_'.$token->[2]->{'id'};
6941: }
1.175 www 6942:
1.339 albertel 6943: if ($entry eq 'import') {
1.175 www 6944: #
6945: # Importing a library here
1.339 albertel 6946: #
6947: if ($depthcount<20) {
6948: my $location=$parser->get_text('/import');
6949: my $dir=$filename;
6950: $dir=~s|[^/]*$||;
6951: $location=&filelocation($dir,$location);
1.736 albertel 6952: my $metadata =
6953: &metadata($uri,'keys', $location,$unikey,
6954: $depthcount+1);
6955: foreach my $meta (split(',',$metadata)) {
6956: $metaentry{':'.$meta}=$metaentry{':'.$meta};
6957: $metathesekeys{$meta}=1;
1.339 albertel 6958: }
6959: }
6960: } else {
6961:
6962: if (defined($token->[2]->{'name'})) {
6963: $unikey.='_'.$token->[2]->{'name'};
6964: }
6965: $metathesekeys{$unikey}=1;
1.736 albertel 6966: foreach my $param (@{$token->[3]}) {
6967: $metaentry{':'.$unikey.'.'.$param} =
6968: $token->[2]->{$param};
1.339 albertel 6969: }
6970: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 6971: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 6972: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
6973: # only ws inside the tag, and not in default, so use default
6974: # as value
1.599 albertel 6975: $metaentry{':'.$unikey}=$default;
1.908 albertel 6976: } elsif ( $internaltext =~ /\S/ ) {
6977: # something interesting inside the tag
6978: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 6979: } else {
1.908 albertel 6980: # no interesting values, don't set a default
1.339 albertel 6981: }
1.172 www 6982: # end of not-a-package not-a-library import
1.339 albertel 6983: }
1.172 www 6984: # end of not-a-package start tag
1.339 albertel 6985: }
1.172 www 6986: # the next is the end of "start tag"
1.339 albertel 6987: }
6988: }
1.483 albertel 6989: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 6990: $extension = lc($extension);
6991: if ($extension eq 'htm') { $extension='html'; }
6992:
1.737 albertel 6993: foreach my $key (keys(%packagetab)) {
1.483 albertel 6994: #no specific packages #how's our extension
6995: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 6996: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 6997: \%metathesekeys);
6998: }
1.883 albertel 6999:
7000: if (!exists($metaentry{':packages'})
7001: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 7002: foreach my $key (keys(%packagetab)) {
1.483 albertel 7003: #no specific packages well let's get default then
7004: if ($key!~/^default&/) { next; }
1.488 albertel 7005: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 7006: \%metathesekeys);
7007: }
7008: }
1.338 www 7009: # are there custom rights to evaluate
1.599 albertel 7010: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 7011:
1.338 www 7012: #
7013: # Importing a rights file here
1.339 albertel 7014: #
7015: unless ($depthcount) {
1.599 albertel 7016: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 7017: my $dir=$filename;
7018: $dir=~s|[^/]*$||;
7019: $location=&filelocation($dir,$location);
1.736 albertel 7020: my $rights_metadata =
7021: &metadata($uri,'keys',$location,'_rights',
7022: $depthcount+1);
7023: foreach my $rights (split(',',$rights_metadata)) {
7024: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
7025: $metathesekeys{$rights}=1;
1.339 albertel 7026: }
7027: }
7028: }
1.737 albertel 7029: # uniqifiy package listing
7030: my %seen;
7031: my @uniq_packages =
7032: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
7033: $metaentry{':packages'} = join(',',@uniq_packages);
7034:
7035: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 7036: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
7037: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 7038: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 7039: # this is the end of "was not already recently cached
1.71 www 7040: }
1.599 albertel 7041: return $metaentry{':'.$what};
1.261 albertel 7042: }
7043:
1.488 albertel 7044: sub metadata_create_package_def {
1.483 albertel 7045: my ($uri,$key,$package,$metathesekeys)=@_;
7046: my ($pack,$name,$subp)=split(/\&/,$key);
7047: if ($subp eq 'default') { next; }
7048:
1.599 albertel 7049: if (defined($metaentry{':packages'})) {
7050: $metaentry{':packages'}.=','.$package;
1.483 albertel 7051: } else {
1.599 albertel 7052: $metaentry{':packages'}=$package;
1.483 albertel 7053: }
7054: my $value=$packagetab{$key};
7055: my $unikey;
7056: $unikey='parameter_0_'.$name;
1.599 albertel 7057: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 7058: $$metathesekeys{$unikey}=1;
1.599 albertel 7059: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7060: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 7061: }
1.599 albertel 7062: if (defined($metaentry{':'.$unikey.'.default'})) {
7063: $metaentry{':'.$unikey}=
7064: $metaentry{':'.$unikey.'.default'};
1.483 albertel 7065: }
7066: }
7067:
1.261 albertel 7068: sub metadata_generate_part0 {
7069: my ($metadata,$metacache,$uri) = @_;
7070: my %allnames;
1.737 albertel 7071: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 7072: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 7073: my $part=$$metacache{':'.$metakey.'.part'};
7074: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 7075: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 7076: $allnames{$name}=$part;
7077: }
7078: }
7079: }
7080: foreach my $name (keys(%allnames)) {
7081: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 7082: my $key=":parameter_0_$name";
1.261 albertel 7083: $$metacache{"$key.part"}='0';
7084: $$metacache{"$key.name"}=$name;
1.428 albertel 7085: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 7086: $allnames{$name}.'_'.$name.
7087: '.type'};
1.428 albertel 7088: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 7089: '.display'};
1.644 www 7090: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 7091: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 7092: $$metacache{"$key.display"}=$olddis;
7093: }
1.71 www 7094: }
7095:
1.764 albertel 7096: # ------------------------------------------------------ Devalidate title cache
7097:
7098: sub devalidate_title_cache {
7099: my ($url)=@_;
7100: if (!$env{'request.course.id'}) { return; }
7101: my $symb=&symbread($url);
7102: if (!$symb) { return; }
7103: my $key=$env{'request.course.id'}."\0".$symb;
7104: &devalidate_cache_new('title',$key);
7105: }
7106:
1.301 www 7107: # ------------------------------------------------- Get the title of a resource
7108:
7109: sub gettitle {
7110: my $urlsymb=shift;
7111: my $symb=&symbread($urlsymb);
1.534 albertel 7112: if ($symb) {
1.620 albertel 7113: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 7114: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 7115: if (defined($cached)) {
7116: return $result;
7117: }
1.534 albertel 7118: my ($map,$resid,$url)=&decode_symb($symb);
7119: my $title='';
1.907 albertel 7120: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
7121: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
7122: } else {
7123: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7124: &GDBM_READER(),0640)) {
7125: my $mapid=$bighash{'map_pc_'.&clutter($map)};
7126: $title=$bighash{'title_'.$mapid.'.'.$resid};
7127: untie(%bighash);
7128: }
1.534 albertel 7129: }
7130: $title=~s/\&colon\;/\:/gs;
7131: if ($title) {
1.599 albertel 7132: return &do_cache_new('title',$key,$title,600);
1.534 albertel 7133: }
7134: $urlsymb=$url;
7135: }
7136: my $title=&metadata($urlsymb,'title');
7137: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
7138: return $title;
1.301 www 7139: }
1.613 albertel 7140:
1.614 albertel 7141: sub get_slot {
7142: my ($which,$cnum,$cdom)=@_;
7143: if (!$cnum || !$cdom) {
1.790 albertel 7144: (undef,my $courseid)=&whichuser();
1.620 albertel 7145: $cdom=$env{'course.'.$courseid.'.domain'};
7146: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 7147: }
1.703 albertel 7148: my $key=join("\0",'slots',$cdom,$cnum,$which);
7149: my %slotinfo;
7150: if (exists($remembered{$key})) {
7151: $slotinfo{$which} = $remembered{$key};
7152: } else {
7153: %slotinfo=&get('slots',[$which],$cdom,$cnum);
7154: &Apache::lonhomework::showhash(%slotinfo);
7155: my ($tmp)=keys(%slotinfo);
7156: if ($tmp=~/^error:/) { return (); }
7157: $remembered{$key} = $slotinfo{$which};
7158: }
1.616 albertel 7159: if (ref($slotinfo{$which}) eq 'HASH') {
7160: return %{$slotinfo{$which}};
7161: }
7162: return $slotinfo{$which};
1.614 albertel 7163: }
1.31 www 7164: # ------------------------------------------------- Update symbolic store links
7165:
7166: sub symblist {
7167: my ($mapname,%newhash)=@_;
1.438 www 7168: $mapname=&deversion(&declutter($mapname));
1.31 www 7169: my %hash;
1.620 albertel 7170: if (($env{'request.course.fn'}) && (%newhash)) {
7171: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7172: &GDBM_WRCREAT(),0640)) {
1.711 albertel 7173: foreach my $url (keys %newhash) {
7174: next if ($url eq 'last_known'
7175: && $env{'form.no_update_last_known'});
7176: $hash{declutter($url)}=&encode_symb($mapname,
7177: $newhash{$url}->[1],
7178: $newhash{$url}->[0]);
1.191 harris41 7179: }
1.31 www 7180: if (untie(%hash)) {
7181: return 'ok';
7182: }
7183: }
7184: }
7185: return 'error';
1.212 www 7186: }
7187:
7188: # --------------------------------------------------------------- Verify a symb
7189:
7190: sub symbverify {
1.510 www 7191: my ($symb,$thisurl)=@_;
7192: my $thisfn=$thisurl;
1.439 www 7193: $thisfn=&declutter($thisfn);
1.215 www 7194: # direct jump to resource in page or to a sequence - will construct own symbs
7195: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
7196: # check URL part
1.409 www 7197: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 7198:
1.431 www 7199: unless ($url eq $thisfn) { return 0; }
1.213 www 7200:
1.216 www 7201: $symb=&symbclean($symb);
1.510 www 7202: $thisurl=&deversion($thisurl);
1.439 www 7203: $thisfn=&deversion($thisfn);
1.213 www 7204:
7205: my %bighash;
7206: my $okay=0;
1.431 www 7207:
1.620 albertel 7208: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7209: &GDBM_READER(),0640)) {
1.510 www 7210: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 7211: unless ($ids) {
1.510 www 7212: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 7213: }
7214: if ($ids) {
7215: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 7216: foreach my $id (split(/\,/,$ids)) {
7217: my ($mapid,$resid)=split(/\./,$id);
1.216 www 7218: if (
7219: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
7220: eq $symb) {
1.620 albertel 7221: if (($env{'request.role.adv'}) ||
1.800 albertel 7222: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 7223: $okay=1;
7224: }
7225: }
1.216 www 7226: }
7227: }
1.213 www 7228: untie(%bighash);
7229: }
7230: return $okay;
1.31 www 7231: }
7232:
1.210 www 7233: # --------------------------------------------------------------- Clean-up symb
7234:
7235: sub symbclean {
7236: my $symb=shift;
1.568 albertel 7237: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 7238: # remove version from map
7239: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 7240:
1.210 www 7241: # remove version from URL
7242: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 7243:
1.507 www 7244: # remove wrapper
7245:
1.510 www 7246: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 7247: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 7248: return $symb;
1.409 www 7249: }
7250:
7251: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 7252:
7253: sub encode_symb {
7254: my ($map,$resid,$url)=@_;
7255: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
7256: }
1.409 www 7257:
7258: sub decode_symb {
1.568 albertel 7259: my $symb=shift;
7260: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
7261: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 7262: return (&fixversion($map),$resid,&fixversion($url));
7263: }
7264:
7265: sub fixversion {
7266: my $fn=shift;
1.609 banghart 7267: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 7268: my %bighash;
7269: my $uri=&clutter($fn);
1.620 albertel 7270: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 7271: # is this cached?
1.599 albertel 7272: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 7273: if (defined($cached)) { return $result; }
7274: # unfortunately not cached, or expired
1.620 albertel 7275: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 7276: &GDBM_READER(),0640)) {
7277: if ($bighash{'version_'.$uri}) {
7278: my $version=$bighash{'version_'.$uri};
1.444 www 7279: unless (($version eq 'mostrecent') ||
7280: ($version==&getversion($uri))) {
1.440 www 7281: $uri=~s/\.(\w+)$/\.$version\.$1/;
7282: }
7283: }
7284: untie %bighash;
1.413 www 7285: }
1.599 albertel 7286: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 7287: }
7288:
7289: sub deversion {
7290: my $url=shift;
7291: $url=~s/\.\d+\.(\w+)$/\.$1/;
7292: return $url;
1.210 www 7293: }
7294:
1.31 www 7295: # ------------------------------------------------------ Return symb list entry
7296:
7297: sub symbread {
1.249 www 7298: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 7299: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 7300: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 7301: # no filename provided? try from environment
1.44 www 7302: unless ($thisfn) {
1.620 albertel 7303: if ($env{'request.symb'}) {
7304: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 7305: }
1.620 albertel 7306: $thisfn=$env{'request.filename'};
1.44 www 7307: }
1.569 albertel 7308: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 7309: # is that filename actually a symb? Verify, clean, and return
7310: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 7311: if (&symbverify($thisfn,$1)) {
1.620 albertel 7312: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 7313: }
1.242 www 7314: }
1.44 www 7315: $thisfn=declutter($thisfn);
1.31 www 7316: my %hash;
1.37 www 7317: my %bighash;
7318: my $syval='';
1.620 albertel 7319: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 7320: my $targetfn = $thisfn;
1.609 banghart 7321: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 7322: $targetfn = 'adm/wrapper/'.$thisfn;
7323: }
1.687 albertel 7324: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
7325: $targetfn=$1;
7326: }
1.620 albertel 7327: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7328: &GDBM_READER(),0640)) {
1.481 raeburn 7329: $syval=$hash{$targetfn};
1.37 www 7330: untie(%hash);
7331: }
7332: # ---------------------------------------------------------- There was an entry
7333: if ($syval) {
1.601 albertel 7334: #unless ($syval=~/\_\d+$/) {
1.620 albertel 7335: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601 albertel 7336: #&appenv('request.ambiguous' => $thisfn);
1.620 albertel 7337: #return $env{$cache_str}='';
1.601 albertel 7338: #}
7339: #$syval.=$1;
7340: #}
1.37 www 7341: } else {
7342: # ------------------------------------------------------- Was not in symb table
1.620 albertel 7343: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7344: &GDBM_READER(),0640)) {
1.37 www 7345: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 7346: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 7347: unless ($ids) {
7348: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 7349: }
7350: unless ($ids) {
7351: # alias?
7352: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 7353: }
1.37 www 7354: if ($ids) {
7355: # ------------------------------------------------------------------- Has ID(s)
7356: my @possibilities=split(/\,/,$ids);
1.39 www 7357: if ($#possibilities==0) {
7358: # ----------------------------------------------- There is only one possibility
1.37 www 7359: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 7360: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7361: $resid,$thisfn);
1.249 www 7362: } elsif (!$donotrecurse) {
1.39 www 7363: # ------------------------------------------ There is more than one possibility
7364: my $realpossible=0;
1.800 albertel 7365: foreach my $id (@possibilities) {
7366: my $file=$bighash{'src_'.$id};
1.39 www 7367: if (&allowed('bre',$file)) {
1.800 albertel 7368: my ($mapid,$resid)=split(/\./,$id);
1.39 www 7369: if ($bighash{'map_type_'.$mapid} ne 'page') {
7370: $realpossible++;
1.626 albertel 7371: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7372: $resid,$thisfn);
1.39 www 7373: }
7374: }
1.191 harris41 7375: }
1.39 www 7376: if ($realpossible!=1) { $syval=''; }
1.249 www 7377: } else {
7378: $syval='';
1.37 www 7379: }
7380: }
7381: untie(%bighash)
1.481 raeburn 7382: }
1.31 www 7383: }
1.62 www 7384: if ($syval) {
1.620 albertel 7385: return $env{$cache_str}=$syval;
1.62 www 7386: }
1.31 www 7387: }
1.44 www 7388: &appenv('request.ambiguous' => $thisfn);
1.620 albertel 7389: return $env{$cache_str}='';
1.31 www 7390: }
7391:
7392: # ---------------------------------------------------------- Return random seed
7393:
1.32 www 7394: sub numval {
7395: my $txt=shift;
7396: $txt=~tr/A-J/0-9/;
7397: $txt=~tr/a-j/0-9/;
7398: $txt=~tr/K-T/0-9/;
7399: $txt=~tr/k-t/0-9/;
7400: $txt=~tr/U-Z/0-5/;
7401: $txt=~tr/u-z/0-5/;
7402: $txt=~s/\D//g;
1.564 albertel 7403: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 7404: return int($txt);
1.368 albertel 7405: }
7406:
1.484 albertel 7407: sub numval2 {
7408: my $txt=shift;
7409: $txt=~tr/A-J/0-9/;
7410: $txt=~tr/a-j/0-9/;
7411: $txt=~tr/K-T/0-9/;
7412: $txt=~tr/k-t/0-9/;
7413: $txt=~tr/U-Z/0-5/;
7414: $txt=~tr/u-z/0-5/;
7415: $txt=~s/\D//g;
7416: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7417: my $total;
7418: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 7419: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 7420: return int($total);
7421: }
7422:
1.575 albertel 7423: sub numval3 {
7424: use integer;
7425: my $txt=shift;
7426: $txt=~tr/A-J/0-9/;
7427: $txt=~tr/a-j/0-9/;
7428: $txt=~tr/K-T/0-9/;
7429: $txt=~tr/k-t/0-9/;
7430: $txt=~tr/U-Z/0-5/;
7431: $txt=~tr/u-z/0-5/;
7432: $txt=~s/\D//g;
7433: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7434: my $total;
7435: foreach my $val (@txts) { $total+=$val; }
7436: if ($_64bit) { $total=(($total<<32)>>32); }
7437: return $total;
7438: }
7439:
1.675 albertel 7440: sub digest {
7441: my ($data)=@_;
7442: my $digest=&Digest::MD5::md5($data);
7443: my ($a,$b,$c,$d)=unpack("iiii",$digest);
7444: my ($e,$f);
7445: {
7446: use integer;
7447: $e=($a+$b);
7448: $f=($c+$d);
7449: if ($_64bit) {
7450: $e=(($e<<32)>>32);
7451: $f=(($f<<32)>>32);
7452: }
7453: }
7454: if (wantarray) {
7455: return ($e,$f);
7456: } else {
7457: my $g;
7458: {
7459: use integer;
7460: $g=($e+$f);
7461: if ($_64bit) {
7462: $g=(($g<<32)>>32);
7463: }
7464: }
7465: return $g;
7466: }
7467: }
7468:
1.368 albertel 7469: sub latest_rnd_algorithm_id {
1.675 albertel 7470: return '64bit5';
1.366 albertel 7471: }
1.32 www 7472:
1.503 albertel 7473: sub get_rand_alg {
7474: my ($courseid)=@_;
1.790 albertel 7475: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 7476: if ($courseid) {
1.620 albertel 7477: return $env{"course.$courseid.rndseed"};
1.503 albertel 7478: }
7479: return &latest_rnd_algorithm_id();
7480: }
7481:
1.562 albertel 7482: sub validCODE {
7483: my ($CODE)=@_;
7484: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
7485: return 0;
7486: }
7487:
1.491 albertel 7488: sub getCODE {
1.620 albertel 7489: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 7490: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
7491: defined($Apache::lonhomework::parsing_a_task) ) &&
7492: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 7493: return $Apache::lonhomework::history{'resource.CODE'};
7494: }
7495: return undef;
7496: }
7497:
1.31 www 7498: sub rndseed {
1.155 albertel 7499: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 7500: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 7501: if (!defined($symb)) {
1.366 albertel 7502: unless ($symb=$wsymb) { return time; }
7503: }
7504: if (!$courseid) { $courseid=$wcourseid; }
7505: if (!$domain) { $domain=$wdomain; }
7506: if (!$username) { $username=$wusername }
1.503 albertel 7507: my $which=&get_rand_alg();
1.803 albertel 7508:
1.491 albertel 7509: if (defined(&getCODE())) {
1.675 albertel 7510: if ($which eq '64bit5') {
7511: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
7512: } elsif ($which eq '64bit4') {
1.575 albertel 7513: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
7514: } else {
7515: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
7516: }
1.675 albertel 7517: } elsif ($which eq '64bit5') {
7518: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 7519: } elsif ($which eq '64bit4') {
7520: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 7521: } elsif ($which eq '64bit3') {
7522: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 7523: } elsif ($which eq '64bit2') {
7524: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 7525: } elsif ($which eq '64bit') {
7526: return &rndseed_64bit($symb,$courseid,$domain,$username);
7527: }
7528: return &rndseed_32bit($symb,$courseid,$domain,$username);
7529: }
7530:
7531: sub rndseed_32bit {
7532: my ($symb,$courseid,$domain,$username)=@_;
7533: {
7534: use integer;
7535: my $symbchck=unpack("%32C*",$symb) << 27;
7536: my $symbseed=numval($symb) << 22;
7537: my $namechck=unpack("%32C*",$username) << 17;
7538: my $nameseed=numval($username) << 12;
7539: my $domainseed=unpack("%32C*",$domain) << 7;
7540: my $courseseed=unpack("%32C*",$courseid);
7541: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 7542: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7543: #&logthis("rndseed :$num:$symb");
1.564 albertel 7544: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 7545: return $num;
7546: }
7547: }
7548:
7549: sub rndseed_64bit {
7550: my ($symb,$courseid,$domain,$username)=@_;
7551: {
7552: use integer;
7553: my $symbchck=unpack("%32S*",$symb) << 21;
7554: my $symbseed=numval($symb) << 10;
7555: my $namechck=unpack("%32S*",$username);
7556:
7557: my $nameseed=numval($username) << 21;
7558: my $domainseed=unpack("%32S*",$domain) << 10;
7559: my $courseseed=unpack("%32S*",$courseid);
7560:
7561: my $num1=$symbchck+$symbseed+$namechck;
7562: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7563: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7564: #&logthis("rndseed :$num:$symb");
1.564 albertel 7565: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 7566: return "$num1,$num2";
1.155 albertel 7567: }
1.366 albertel 7568: }
7569:
1.443 albertel 7570: sub rndseed_64bit2 {
7571: my ($symb,$courseid,$domain,$username)=@_;
7572: {
7573: use integer;
7574: # strings need to be an even # of cahracters long, it it is odd the
7575: # last characters gets thrown away
7576: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7577: my $symbseed=numval($symb) << 10;
7578: my $namechck=unpack("%32S*",$username.' ');
7579:
7580: my $nameseed=numval($username) << 21;
1.501 albertel 7581: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7582: my $courseseed=unpack("%32S*",$courseid.' ');
7583:
7584: my $num1=$symbchck+$symbseed+$namechck;
7585: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7586: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7587: #&logthis("rndseed :$num:$symb");
1.803 albertel 7588: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 7589: return "$num1,$num2";
7590: }
7591: }
7592:
7593: sub rndseed_64bit3 {
7594: my ($symb,$courseid,$domain,$username)=@_;
7595: {
7596: use integer;
7597: # strings need to be an even # of cahracters long, it it is odd the
7598: # last characters gets thrown away
7599: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7600: my $symbseed=numval2($symb) << 10;
7601: my $namechck=unpack("%32S*",$username.' ');
7602:
7603: my $nameseed=numval2($username) << 21;
1.443 albertel 7604: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7605: my $courseseed=unpack("%32S*",$courseid.' ');
7606:
7607: my $num1=$symbchck+$symbseed+$namechck;
7608: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7609: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7610: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 7611: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7612:
1.503 albertel 7613: return "$num1:$num2";
1.443 albertel 7614: }
7615: }
7616:
1.575 albertel 7617: sub rndseed_64bit4 {
7618: my ($symb,$courseid,$domain,$username)=@_;
7619: {
7620: use integer;
7621: # strings need to be an even # of cahracters long, it it is odd the
7622: # last characters gets thrown away
7623: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7624: my $symbseed=numval3($symb) << 10;
7625: my $namechck=unpack("%32S*",$username.' ');
7626:
7627: my $nameseed=numval3($username) << 21;
7628: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7629: my $courseseed=unpack("%32S*",$courseid.' ');
7630:
7631: my $num1=$symbchck+$symbseed+$namechck;
7632: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7633: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7634: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 7635: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7636:
7637: return "$num1:$num2";
7638: }
7639: }
7640:
1.675 albertel 7641: sub rndseed_64bit5 {
7642: my ($symb,$courseid,$domain,$username)=@_;
7643: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
7644: return "$num1:$num2";
7645: }
7646:
1.366 albertel 7647: sub rndseed_CODE_64bit {
7648: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 7649: {
1.366 albertel 7650: use integer;
1.443 albertel 7651: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 7652: my $symbseed=numval2($symb);
1.491 albertel 7653: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7654: my $CODEseed=numval(&getCODE());
1.443 albertel 7655: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 7656: my $num1=$symbseed+$CODEchck;
7657: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7658: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7659: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 7660: if ($_64bit) { $num1=(($num1<<32)>>32); }
7661: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 7662: return "$num1:$num2";
1.366 albertel 7663: }
7664: }
7665:
1.575 albertel 7666: sub rndseed_CODE_64bit4 {
7667: my ($symb,$courseid,$domain,$username)=@_;
7668: {
7669: use integer;
7670: my $symbchck=unpack("%32S*",$symb.' ') << 16;
7671: my $symbseed=numval3($symb);
7672: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7673: my $CODEseed=numval3(&getCODE());
7674: my $courseseed=unpack("%32S*",$courseid.' ');
7675: my $num1=$symbseed+$CODEchck;
7676: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7677: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7678: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 7679: if ($_64bit) { $num1=(($num1<<32)>>32); }
7680: if ($_64bit) { $num2=(($num2<<32)>>32); }
7681: return "$num1:$num2";
7682: }
7683: }
7684:
1.675 albertel 7685: sub rndseed_CODE_64bit5 {
7686: my ($symb,$courseid,$domain,$username)=@_;
7687: my $code = &getCODE();
7688: my ($num1,$num2)=&digest("$symb,$courseid,$code");
7689: return "$num1:$num2";
7690: }
7691:
1.366 albertel 7692: sub setup_random_from_rndseed {
7693: my ($rndseed)=@_;
1.503 albertel 7694: if ($rndseed =~/([,:])/) {
7695: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 7696: &Math::Random::random_set_seed(abs($num1),abs($num2));
7697: } else {
7698: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 7699: }
1.36 albertel 7700: }
7701:
1.474 albertel 7702: sub latest_receipt_algorithm_id {
1.835 albertel 7703: return 'receipt3';
1.474 albertel 7704: }
7705:
1.480 www 7706: sub recunique {
7707: my $fucourseid=shift;
7708: my $unique;
1.835 albertel 7709: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
7710: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7711: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 7712: } else {
7713: $unique=$perlvar{'lonReceipt'};
7714: }
7715: return unpack("%32C*",$unique);
7716: }
7717:
7718: sub recprefix {
7719: my $fucourseid=shift;
7720: my $prefix;
1.835 albertel 7721: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
7722: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7723: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 7724: } else {
7725: $prefix=$perlvar{'lonHostID'};
7726: }
7727: return unpack("%32C*",$prefix);
7728: }
7729:
1.76 www 7730: sub ireceipt {
1.474 albertel 7731: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 7732:
7733: my $return =&recprefix($fucourseid).'-';
7734:
7735: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
7736: $env{'request.state'} eq 'construct') {
7737: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
7738: return $return;
7739: }
7740:
1.76 www 7741: my $cuname=unpack("%32C*",$funame);
7742: my $cudom=unpack("%32C*",$fudom);
7743: my $cucourseid=unpack("%32C*",$fucourseid);
7744: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 7745: my $cunique=&recunique($fucourseid);
1.474 albertel 7746: my $cpart=unpack("%32S*",$part);
1.835 albertel 7747: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
7748:
1.790 albertel 7749: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 7750:
7751: $return.= ($cunique%$cuname+
7752: $cunique%$cudom+
7753: $cusymb%$cuname+
7754: $cusymb%$cudom+
7755: $cucourseid%$cuname+
7756: $cucourseid%$cudom+
7757: $cpart%$cuname+
7758: $cpart%$cudom);
7759: } else {
7760: $return.= ($cunique%$cuname+
7761: $cunique%$cudom+
7762: $cusymb%$cuname+
7763: $cusymb%$cudom+
7764: $cucourseid%$cuname+
7765: $cucourseid%$cudom);
7766: }
7767: return $return;
1.76 www 7768: }
7769:
7770: sub receipt {
1.474 albertel 7771: my ($part)=@_;
1.790 albertel 7772: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 7773: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 7774: }
1.260 ng 7775:
1.790 albertel 7776: sub whichuser {
7777: my ($passedsymb)=@_;
7778: my ($symb,$courseid,$domain,$name,$publicuser);
7779: if (defined($env{'form.grade_symb'})) {
7780: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
7781: my $allowed=&allowed('vgr',$tmp_courseid);
7782: if (!$allowed &&
7783: exists($env{'request.course.sec'}) &&
7784: $env{'request.course.sec'} !~ /^\s*$/) {
7785: $allowed=&allowed('vgr',$tmp_courseid.
7786: '/'.$env{'request.course.sec'});
7787: }
7788: if ($allowed) {
7789: ($symb)=&get_env_multiple('form.grade_symb');
7790: $courseid=$tmp_courseid;
7791: ($domain)=&get_env_multiple('form.grade_domain');
7792: ($name)=&get_env_multiple('form.grade_username');
7793: return ($symb,$courseid,$domain,$name,$publicuser);
7794: }
7795: }
7796: if (!$passedsymb) {
7797: $symb=&symbread();
7798: } else {
7799: $symb=$passedsymb;
7800: }
7801: $courseid=$env{'request.course.id'};
7802: $domain=$env{'user.domain'};
7803: $name=$env{'user.name'};
7804: if ($name eq 'public' && $domain eq 'public') {
7805: if (!defined($env{'form.username'})) {
7806: $env{'form.username'}.=time.rand(10000000);
7807: }
7808: $name.=$env{'form.username'};
7809: }
7810: return ($symb,$courseid,$domain,$name,$publicuser);
7811:
7812: }
7813:
1.36 albertel 7814: # ------------------------------------------------------------ Serves up a file
1.472 albertel 7815: # returns either the contents of the file or
7816: # -1 if the file doesn't exist
1.481 raeburn 7817: #
7818: # if the target is a file that was uploaded via DOCS,
7819: # a check will be made to see if a current copy exists on the local server,
7820: # if it does this will be served, otherwise a copy will be retrieved from
7821: # the home server for the course and stored in /home/httpd/html/userfiles on
7822: # the local server.
1.472 albertel 7823:
1.36 albertel 7824: sub getfile {
1.538 albertel 7825: my ($file) = @_;
1.609 banghart 7826: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 7827: &repcopy($file);
7828: return &readfile($file);
7829: }
7830:
7831: sub repcopy_userfile {
7832: my ($file)=@_;
1.609 banghart 7833: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 7834: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 7835: my ($cdom,$cnum,$filename) =
1.811 albertel 7836: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 7837: my $uri="/uploaded/$cdom/$cnum/$filename";
7838: if (-e "$file") {
1.828 www 7839: # we already have a local copy, check it out
1.538 albertel 7840: my @fileinfo = stat($file);
1.828 www 7841: my $rtncode;
7842: my $info;
1.538 albertel 7843: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 7844: if ($lwpresp ne 'ok') {
1.828 www 7845: # there is no such file anymore, even though we had a local copy
1.482 albertel 7846: if ($rtncode eq '404') {
1.538 albertel 7847: unlink($file);
1.482 albertel 7848: }
7849: return -1;
7850: }
7851: if ($info < $fileinfo[9]) {
1.828 www 7852: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 7853: return 'ok';
1.828 www 7854: } else {
7855: # the file is outdated, get rid of it
7856: unlink($file);
1.482 albertel 7857: }
1.828 www 7858: }
7859: # one way or the other, at this point, we don't have the file
7860: # construct the correct path for the file
7861: my @parts = ($cdom,$cnum);
7862: if ($filename =~ m|^(.+)/[^/]+$|) {
7863: push @parts, split(/\//,$1);
7864: }
7865: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
7866: foreach my $part (@parts) {
7867: $path .= '/'.$part;
7868: if (!-e $path) {
7869: mkdir($path,0770);
1.482 albertel 7870: }
7871: }
1.828 www 7872: # now the path exists for sure
7873: # get a user agent
7874: my $ua=new LWP::UserAgent;
7875: my $transferfile=$file.'.in.transfer';
7876: # FIXME: this should flock
7877: if (-e $transferfile) { return 'ok'; }
7878: my $request;
7879: $uri=~s/^\///;
1.838 albertel 7880: $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828 www 7881: my $response=$ua->request($request,$transferfile);
7882: # did it work?
7883: if ($response->is_error()) {
7884: unlink($transferfile);
7885: &logthis("Userfile repcopy failed for $uri");
7886: return -1;
7887: }
7888: # worked, rename the transfer file
7889: rename($transferfile,$file);
1.607 raeburn 7890: return 'ok';
1.481 raeburn 7891: }
7892:
1.517 albertel 7893: sub tokenwrapper {
7894: my $uri=shift;
1.552 albertel 7895: $uri=~s|^http\://([^/]+)||;
7896: $uri=~s|^/||;
1.620 albertel 7897: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 7898: my $token=$1;
1.552 albertel 7899: my (undef,$udom,$uname,$file)=split('/',$uri,4);
7900: if ($udom && $uname && $file) {
7901: $file=~s|(\?\.*)*$||;
1.620 albertel 7902: &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838 albertel 7903: return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517 albertel 7904: (($uri=~/\?/)?'&':'?').'token='.$token.
7905: '&tokenissued='.$perlvar{'lonHostID'};
7906: } else {
7907: return '/adm/notfound.html';
7908: }
7909: }
7910:
1.828 www 7911: # call with reqtype HEAD: get last modification time
7912: # call with reqtype GET: get the file contents
7913: # Do not call this with reqtype GET for large files! It loads everything into memory
7914: #
1.481 raeburn 7915: sub getuploaded {
7916: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
7917: $uri=~s/^\///;
1.838 albertel 7918: $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481 raeburn 7919: my $ua=new LWP::UserAgent;
7920: my $request=new HTTP::Request($reqtype,$uri);
7921: my $response=$ua->request($request);
7922: $$rtncode = $response->code;
1.482 albertel 7923: if (! $response->is_success()) {
7924: return 'failed';
7925: }
7926: if ($reqtype eq 'HEAD') {
1.486 www 7927: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 7928: } elsif ($reqtype eq 'GET') {
7929: $$info = $response->content;
1.472 albertel 7930: }
1.482 albertel 7931: return 'ok';
1.36 albertel 7932: }
7933:
1.481 raeburn 7934: sub readfile {
7935: my $file = shift;
7936: if ( (! -e $file ) || ($file eq '') ) { return -1; };
7937: my $fh;
7938: open($fh,"<$file");
7939: my $a='';
1.800 albertel 7940: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 7941: return $a;
7942: }
7943:
1.36 albertel 7944: sub filelocation {
1.590 banghart 7945: my ($dir,$file) = @_;
7946: my $location;
7947: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 7948:
7949: if ($file =~ m-^/adm/-) {
7950: $file=~s-^/adm/wrapper/-/-;
7951: $file=~s-^/adm/coursedocs/showdoc/-/-;
7952: }
1.882 albertel 7953:
1.590 banghart 7954: if ($file=~m:^/~:) { # is a contruction space reference
7955: $location = $file;
7956: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 7957: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 7958: # is a correct contruction space reference
7959: $location = $file;
1.609 banghart 7960: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 7961: my ($udom,$uname,$filename)=
1.811 albertel 7962: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 7963: my $home=&homeserver($uname,$udom);
7964: my $is_me=0;
7965: my @ids=¤t_machine_ids();
7966: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
7967: if ($is_me) {
1.740 www 7968: $location=&propath($udom,$uname).
1.590 banghart 7969: '/userfiles/'.$filename;
7970: } else {
7971: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
7972: $udom.'/'.$uname.'/'.$filename;
7973: }
1.882 albertel 7974: } elsif ($file =~ m-^/adm/-) {
7975: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 7976: } else {
7977: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
7978: $file=~s:^/res/:/:;
7979: if ( !( $file =~ m:^/:) ) {
7980: $location = $dir. '/'.$file;
7981: } else {
7982: $location = '/home/httpd/html/res'.$file;
7983: }
1.59 albertel 7984: }
1.590 banghart 7985: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 7986: while ($location=~m{/\.\./}) {
7987: if ($location =~ m{/[^/]+/\.\./}) {
7988: $location=~ s{/[^/]+/\.\./}{/}g;
7989: } else {
7990: $location=~ s{/\.\./}{/}g;
7991: }
7992: } #remove dir/..
1.590 banghart 7993: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
7994: return $location;
1.46 www 7995: }
1.36 albertel 7996:
1.46 www 7997: sub hreflocation {
7998: my ($dir,$file)=@_;
1.460 albertel 7999: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666 albertel 8000: $file=filelocation($dir,$file);
1.700 albertel 8001: } elsif ($file=~m-^/adm/-) {
8002: $file=~s-^/adm/wrapper/-/-;
8003: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 8004: }
8005: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
8006: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 8007: } elsif ($file=~m-/home/($match_username)/public_html/-) {
8008: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 8009: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 8010: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 8011: -/uploaded/$1/$2/-x;
1.46 www 8012: }
1.913 albertel 8013: if ($file=~ m{^/userfiles/}) {
8014: $file =~ s{^/userfiles/}{/uploaded/};
8015: }
1.462 albertel 8016: return $file;
1.465 albertel 8017: }
8018:
8019: sub current_machine_domains {
1.853 albertel 8020: return &machine_domains(&hostname($perlvar{'lonHostID'}));
8021: }
8022:
8023: sub machine_domains {
8024: my ($hostname) = @_;
1.465 albertel 8025: my @domains;
1.838 albertel 8026: my %hostname = &all_hostnames();
1.465 albertel 8027: while( my($id, $name) = each(%hostname)) {
1.467 matthew 8028: # &logthis("-$id-$name-$hostname-");
1.465 albertel 8029: if ($hostname eq $name) {
1.844 albertel 8030: push(@domains,&host_domain($id));
1.465 albertel 8031: }
8032: }
8033: return @domains;
8034: }
8035:
8036: sub current_machine_ids {
1.853 albertel 8037: return &machine_ids(&hostname($perlvar{'lonHostID'}));
8038: }
8039:
8040: sub machine_ids {
8041: my ($hostname) = @_;
8042: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 8043: my @ids;
1.888 albertel 8044: my %name_to_host = &all_names();
1.889 albertel 8045: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
8046: return @{ $name_to_host{$hostname} };
8047: }
8048: return;
1.31 www 8049: }
8050:
1.824 raeburn 8051: sub additional_machine_domains {
8052: my @domains;
8053: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
8054: while( my $line = <$fh>) {
8055: $line =~ s/\s//g;
8056: push(@domains,$line);
8057: }
8058: return @domains;
8059: }
8060:
8061: sub default_login_domain {
8062: my $domain = $perlvar{'lonDefDomain'};
8063: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
8064: foreach my $posdom (¤t_machine_domains(),
8065: &additional_machine_domains()) {
8066: if (lc($posdom) eq lc($testdomain)) {
8067: $domain=$posdom;
8068: last;
8069: }
8070: }
8071: return $domain;
8072: }
8073:
1.31 www 8074: # ------------------------------------------------------------- Declutters URLs
8075:
8076: sub declutter {
8077: my $thisfn=shift;
1.569 albertel 8078: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 8079: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 8080: $thisfn=~s/^\///;
1.697 albertel 8081: $thisfn=~s|^adm/wrapper/||;
8082: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 8083: $thisfn=~s/^res\///;
1.235 www 8084: $thisfn=~s/\?.+$//;
1.268 www 8085: return $thisfn;
8086: }
8087:
8088: # ------------------------------------------------------------- Clutter up URLs
8089:
8090: sub clutter {
8091: my $thisfn='/'.&declutter(shift);
1.887 albertel 8092: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 8093: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 8094: $thisfn='/res'.$thisfn;
8095: }
1.694 albertel 8096: if ($thisfn !~m|/adm|) {
1.695 albertel 8097: if ($thisfn =~ m|/ext/|) {
1.694 albertel 8098: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 8099: } else {
8100: my ($ext) = ($thisfn =~ /\.(\w+)$/);
8101: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 8102: if ($embstyle eq 'ssi'
8103: || ($embstyle eq 'hdn')
8104: || ($embstyle eq 'rat')
8105: || ($embstyle eq 'prv')
8106: || ($embstyle eq 'ign')) {
8107: #do nothing with these
8108: } elsif (($embstyle eq 'img')
1.695 albertel 8109: || ($embstyle eq 'emb')
8110: || ($embstyle eq 'wrp')) {
8111: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 8112: } elsif ($embstyle eq 'unk'
8113: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 8114: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 8115: } else {
1.718 www 8116: # &logthis("Got a blank emb style");
1.695 albertel 8117: }
1.694 albertel 8118: }
8119: }
1.31 www 8120: return $thisfn;
1.12 www 8121: }
8122:
1.787 albertel 8123: sub clutter_with_no_wrapper {
8124: my $uri = &clutter(shift);
8125: if ($uri =~ m-^/adm/-) {
8126: $uri =~ s-^/adm/wrapper/-/-;
8127: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
8128: }
8129: return $uri;
8130: }
8131:
1.557 albertel 8132: sub freeze_escape {
8133: my ($value)=@_;
8134: if (ref($value)) {
8135: $value=&nfreeze($value);
8136: return '__FROZEN__'.&escape($value);
8137: }
8138: return &escape($value);
8139: }
8140:
1.11 www 8141:
1.557 albertel 8142: sub thaw_unescape {
8143: my ($value)=@_;
8144: if ($value =~ /^__FROZEN__/) {
8145: substr($value,0,10,undef);
8146: $value=&unescape($value);
8147: return &thaw($value);
8148: }
8149: return &unescape($value);
8150: }
8151:
1.436 albertel 8152: sub correct_line_ends {
8153: my ($result)=@_;
8154: $$result =~s/\r\n/\n/mg;
8155: $$result =~s/\r/\n/mg;
1.415 albertel 8156: }
1.1 albertel 8157: # ================================================================ Main Program
8158:
1.184 www 8159: sub goodbye {
1.204 albertel 8160: &logthis("Starting Shut down");
1.443 albertel 8161: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 8162: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 8163: #converted
1.599 albertel 8164: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 8165: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
8166: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
8167: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 8168: #1.1 only
1.870 albertel 8169: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
8170: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
8171: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
8172: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
8173: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 8174: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
8175: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 8176: &flushcourselogs();
8177: &logthis("Shutting down");
8178: }
8179:
1.852 albertel 8180: sub get_dns {
1.869 albertel 8181: my ($url,$func,$ignore_cache) = @_;
8182: if (!$ignore_cache) {
8183: my ($content,$cached)=
8184: &Apache::lonnet::is_cached_new('dns',$url);
8185: if ($cached) {
8186: &$func($content);
8187: return;
8188: }
8189: }
8190:
8191: my %alldns;
1.852 albertel 8192: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8193: foreach my $dns (<$config>) {
8194: next if ($dns !~ /^\^(\S*)/x);
1.869 albertel 8195: $alldns{$1} = 1;
8196: }
8197: while (%alldns) {
8198: my ($dns) = keys(%alldns);
8199: delete($alldns{$dns});
1.852 albertel 8200: my $ua=new LWP::UserAgent;
8201: my $request=new HTTP::Request('GET',"http://$dns$url");
8202: my $response=$ua->request($request);
8203: next if ($response->is_error());
8204: my @content = split("\n",$response->content);
1.869 albertel 8205: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 8206: &$func(\@content);
1.869 albertel 8207: return;
1.852 albertel 8208: }
8209: close($config);
1.871 albertel 8210: my $which = (split('/',$url))[3];
8211: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
8212: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 8213: my @content = <$config>;
8214: &$func(\@content);
8215: return;
1.852 albertel 8216: }
1.327 albertel 8217: # ------------------------------------------------------------ Read domain file
8218: {
1.852 albertel 8219: my $loaded;
1.846 albertel 8220: my %domain;
8221:
1.852 albertel 8222: sub parse_domain_tab {
8223: my ($lines) = @_;
8224: foreach my $line (@$lines) {
8225: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 8226:
1.846 albertel 8227: chomp($line);
1.852 albertel 8228: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 8229: my %this_domain;
8230: foreach my $field ('description', 'auth_def', 'auth_arg_def',
8231: 'lang_def', 'city', 'longi', 'lati',
8232: 'primary') {
8233: $this_domain{$field} = shift(@elements);
8234: }
8235: $domain{$name} = \%this_domain;
1.852 albertel 8236: }
8237: }
1.864 albertel 8238:
8239: sub reset_domain_info {
8240: undef($loaded);
8241: undef(%domain);
8242: }
8243:
1.852 albertel 8244: sub load_domain_tab {
1.869 albertel 8245: my ($ignore_cache) = @_;
8246: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 8247: my $fh;
8248: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
8249: my @lines = <$fh>;
8250: &parse_domain_tab(\@lines);
1.448 albertel 8251: }
1.852 albertel 8252: close($fh);
8253: $loaded = 1;
1.327 albertel 8254: }
1.846 albertel 8255:
8256: sub domain {
1.852 albertel 8257: &load_domain_tab() if (!$loaded);
8258:
1.846 albertel 8259: my ($name,$what) = @_;
8260: return if ( !exists($domain{$name}) );
8261:
8262: if (!$what) {
8263: return $domain{$name}{'description'};
8264: }
8265: return $domain{$name}{$what};
8266: }
1.327 albertel 8267: }
8268:
8269:
1.1 albertel 8270: # ------------------------------------------------------------- Read hosts file
8271: {
1.838 albertel 8272: my %hostname;
1.844 albertel 8273: my %hostdom;
1.845 albertel 8274: my %libserv;
1.852 albertel 8275: my $loaded;
1.888 albertel 8276: my %name_to_host;
1.852 albertel 8277:
8278: sub parse_hosts_tab {
8279: my ($file) = @_;
8280: foreach my $configline (@$file) {
8281: next if ($configline =~ /^(\#|\s*$ )/x);
8282: next if ($configline =~ /^\^/);
8283: chomp($configline);
8284: my ($id,$domain,$role,$name)=split(/:/,$configline);
8285: $name=~s/\s//g;
8286: if ($id && $domain && $role && $name) {
8287: $hostname{$id}=$name;
1.888 albertel 8288: push(@{$name_to_host{$name}}, $id);
1.852 albertel 8289: $hostdom{$id}=$domain;
8290: if ($role eq 'library') { $libserv{$id}=$name; }
8291: }
8292: }
8293: }
1.864 albertel 8294:
8295: sub reset_hosts_info {
1.897 albertel 8296: &purge_remembered();
1.864 albertel 8297: &reset_domain_info();
8298: &reset_hosts_ip_info();
1.892 albertel 8299: undef(%name_to_host);
1.864 albertel 8300: undef(%hostname);
8301: undef(%hostdom);
8302: undef(%libserv);
8303: undef($loaded);
8304: }
1.1 albertel 8305:
1.852 albertel 8306: sub load_hosts_tab {
1.869 albertel 8307: my ($ignore_cache) = @_;
8308: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 8309: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8310: my @config = <$config>;
8311: &parse_hosts_tab(\@config);
8312: close($config);
8313: $loaded=1;
1.1 albertel 8314: }
1.852 albertel 8315:
1.838 albertel 8316: sub hostname {
1.852 albertel 8317: &load_hosts_tab() if (!$loaded);
8318:
1.838 albertel 8319: my ($lonid) = @_;
8320: return $hostname{$lonid};
8321: }
1.845 albertel 8322:
1.838 albertel 8323: sub all_hostnames {
1.852 albertel 8324: &load_hosts_tab() if (!$loaded);
8325:
1.838 albertel 8326: return %hostname;
8327: }
1.845 albertel 8328:
1.888 albertel 8329: sub all_names {
8330: &load_hosts_tab() if (!$loaded);
8331:
8332: return %name_to_host;
8333: }
8334:
1.845 albertel 8335: sub is_library {
1.852 albertel 8336: &load_hosts_tab() if (!$loaded);
8337:
1.845 albertel 8338: return exists($libserv{$_[0]});
8339: }
8340:
8341: sub all_library {
1.852 albertel 8342: &load_hosts_tab() if (!$loaded);
8343:
1.845 albertel 8344: return %libserv;
8345: }
8346:
1.841 albertel 8347: sub get_servers {
1.852 albertel 8348: &load_hosts_tab() if (!$loaded);
8349:
1.841 albertel 8350: my ($domain,$type) = @_;
8351: my %possible_hosts = ($type eq 'library') ? %libserv
8352: : %hostname;
8353: my %result;
1.842 albertel 8354: if (ref($domain) eq 'ARRAY') {
8355: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 8356: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 8357: $result{$host} = $hostname;
8358: }
8359: }
8360: } else {
8361: while ( my ($host,$hostname) = each(%possible_hosts)) {
8362: if ($hostdom{$host} eq $domain) {
8363: $result{$host} = $hostname;
8364: }
1.841 albertel 8365: }
8366: }
8367: return %result;
8368: }
1.845 albertel 8369:
1.844 albertel 8370: sub host_domain {
1.852 albertel 8371: &load_hosts_tab() if (!$loaded);
8372:
1.844 albertel 8373: my ($lonid) = @_;
8374: return $hostdom{$lonid};
8375: }
8376:
1.841 albertel 8377: sub all_domains {
1.852 albertel 8378: &load_hosts_tab() if (!$loaded);
8379:
1.841 albertel 8380: my %seen;
8381: my @uniq = grep(!$seen{$_}++, values(%hostdom));
8382: return @uniq;
8383: }
1.1 albertel 8384: }
8385:
1.847 albertel 8386: {
8387: my %iphost;
1.856 albertel 8388: my %name_to_ip;
8389: my %lonid_to_ip;
1.869 albertel 8390:
1.847 albertel 8391: sub get_hosts_from_ip {
8392: my ($ip) = @_;
8393: my %iphosts = &get_iphost();
8394: if (ref($iphosts{$ip})) {
8395: return @{$iphosts{$ip}};
8396: }
8397: return;
1.839 albertel 8398: }
1.864 albertel 8399:
8400: sub reset_hosts_ip_info {
8401: undef(%iphost);
8402: undef(%name_to_ip);
8403: undef(%lonid_to_ip);
8404: }
1.856 albertel 8405:
8406: sub get_host_ip {
8407: my ($lonid) = @_;
8408: if (exists($lonid_to_ip{$lonid})) {
8409: return $lonid_to_ip{$lonid};
8410: }
8411: my $name=&hostname($lonid);
8412: my $ip = gethostbyname($name);
8413: return if (!$ip || length($ip) ne 4);
8414: $ip=inet_ntoa($ip);
8415: $name_to_ip{$name} = $ip;
8416: $lonid_to_ip{$lonid} = $ip;
8417: return $ip;
8418: }
1.847 albertel 8419:
8420: sub get_iphost {
1.869 albertel 8421: my ($ignore_cache) = @_;
1.894 albertel 8422:
1.869 albertel 8423: if (!$ignore_cache) {
8424: if (%iphost) {
8425: return %iphost;
8426: }
8427: my ($ip_info,$cached)=
8428: &Apache::lonnet::is_cached_new('iphost','iphost');
8429: if ($cached) {
8430: %iphost = %{$ip_info->[0]};
8431: %name_to_ip = %{$ip_info->[1]};
8432: %lonid_to_ip = %{$ip_info->[2]};
8433: return %iphost;
8434: }
8435: }
1.894 albertel 8436:
8437: # get yesterday's info for fallback
8438: my %old_name_to_ip;
8439: my ($ip_info,$cached)=
8440: &Apache::lonnet::is_cached_new('iphost','iphost');
8441: if ($cached) {
8442: %old_name_to_ip = %{$ip_info->[1]};
8443: }
8444:
1.888 albertel 8445: my %name_to_host = &all_names();
8446: foreach my $name (keys(%name_to_host)) {
1.847 albertel 8447: my $ip;
8448: if (!exists($name_to_ip{$name})) {
8449: $ip = gethostbyname($name);
8450: if (!$ip || length($ip) ne 4) {
1.894 albertel 8451: if (defined($old_name_to_ip{$name})) {
8452: $ip = $old_name_to_ip{$name};
8453: &logthis("Can't find $name defaulting to old $ip");
8454: } else {
8455: &logthis("Name $name no IP found");
8456: next;
8457: }
8458: } else {
8459: $ip=inet_ntoa($ip);
1.847 albertel 8460: }
8461: $name_to_ip{$name} = $ip;
8462: } else {
8463: $ip = $name_to_ip{$name};
1.653 albertel 8464: }
1.888 albertel 8465: foreach my $id (@{ $name_to_host{$name} }) {
8466: $lonid_to_ip{$id} = $ip;
8467: }
8468: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 8469: }
1.869 albertel 8470: &Apache::lonnet::do_cache_new('iphost','iphost',
8471: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 8472: 48*60*60);
1.869 albertel 8473:
1.847 albertel 8474: return %iphost;
1.598 albertel 8475: }
8476: }
8477:
1.862 albertel 8478: BEGIN {
8479:
8480: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
8481: unless ($readit) {
8482: {
8483: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
8484: %perlvar = (%perlvar,%{$configvars});
8485: }
8486:
8487:
1.1 albertel 8488: # ------------------------------------------------------ Read spare server file
8489: {
1.448 albertel 8490: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 8491:
8492: while (my $configline=<$config>) {
8493: chomp($configline);
1.284 matthew 8494: if ($configline) {
1.784 albertel 8495: my ($host,$type) = split(':',$configline,2);
1.785 albertel 8496: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 8497: push(@{ $spareid{$type} }, $host);
1.1 albertel 8498: }
8499: }
1.448 albertel 8500: close($config);
1.1 albertel 8501: }
1.11 www 8502: # ------------------------------------------------------------ Read permissions
8503: {
1.448 albertel 8504: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 8505:
8506: while (my $configline=<$config>) {
1.448 albertel 8507: chomp($configline);
8508: if ($configline) {
8509: my ($role,$perm)=split(/ /,$configline);
8510: if ($perm ne '') { $pr{$role}=$perm; }
8511: }
1.11 www 8512: }
1.448 albertel 8513: close($config);
1.11 www 8514: }
8515:
8516: # -------------------------------------------- Read plain texts for permissions
8517: {
1.448 albertel 8518: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 8519:
8520: while (my $configline=<$config>) {
1.448 albertel 8521: chomp($configline);
8522: if ($configline) {
1.742 raeburn 8523: my ($short,@plain)=split(/:/,$configline);
8524: %{$prp{$short}} = ();
8525: if (@plain > 0) {
8526: $prp{$short}{'std'} = $plain[0];
8527: for (my $i=1; $i<@plain; $i++) {
8528: $prp{$short}{'alt'.$i} = $plain[$i];
8529: }
8530: }
1.448 albertel 8531: }
1.135 www 8532: }
1.448 albertel 8533: close($config);
1.135 www 8534: }
8535:
8536: # ---------------------------------------------------------- Read package table
8537: {
1.448 albertel 8538: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 8539:
8540: while (my $configline=<$config>) {
1.483 albertel 8541: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 8542: chomp($configline);
8543: my ($short,$plain)=split(/:/,$configline);
8544: my ($pack,$name)=split(/\&/,$short);
8545: if ($plain ne '') {
8546: $packagetab{$pack.'&'.$name.'&name'}=$name;
8547: $packagetab{$short}=$plain;
8548: }
1.11 www 8549: }
1.448 albertel 8550: close($config);
1.329 matthew 8551: }
8552:
8553: # ------------- set up temporary directory
8554: {
8555: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
8556:
1.11 www 8557: }
8558:
1.794 albertel 8559: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
8560: 'compress_threshold'=> 20_000,
8561: });
1.185 www 8562:
1.281 www 8563: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 8564: $dumpcount=0;
1.22 www 8565:
1.163 harris41 8566: &logtouch();
1.672 albertel 8567: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 8568: $readit=1;
1.564 albertel 8569: {
8570: use integer;
8571: my $test=(2**32)+1;
1.568 albertel 8572: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 8573: &logthis(" Detected 64bit platform ($_64bit)");
8574: }
1.195 www 8575: }
1.1 albertel 8576: }
1.179 www 8577:
1.1 albertel 8578: 1;
1.191 harris41 8579: __END__
8580:
1.243 albertel 8581: =pod
8582:
1.191 harris41 8583: =head1 NAME
8584:
1.243 albertel 8585: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 8586:
8587: =head1 SYNOPSIS
8588:
1.243 albertel 8589: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 8590:
8591: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
8592:
1.243 albertel 8593: Common parameters:
8594:
8595: =over 4
8596:
8597: =item *
8598:
8599: $uname : an internal username (if $cname expecting a course Id specifically)
8600:
8601: =item *
8602:
8603: $udom : a domain (if $cdom expecting a course's domain specifically)
8604:
8605: =item *
8606:
8607: $symb : a resource instance identifier
8608:
8609: =item *
8610:
8611: $namespace : the name of a .db file that contains the data needed or
8612: being set.
8613:
8614: =back
8615:
1.394 bowersj2 8616: =head1 OVERVIEW
1.191 harris41 8617:
1.394 bowersj2 8618: lonnet provides subroutines which interact with the
8619: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
8620: about classes, users, and resources.
1.243 albertel 8621:
8622: For many of these objects you can also use this to store data about
8623: them or modify them in various ways.
1.191 harris41 8624:
1.394 bowersj2 8625: =head2 Symbs
1.191 harris41 8626:
1.394 bowersj2 8627: To identify a specific instance of a resource, LON-CAPA uses symbols
8628: or "symbs"X<symb>. These identifiers are built from the URL of the
8629: map, the resource number of the resource in the map, and the URL of
8630: the resource itself. The latter is somewhat redundant, but might help
8631: if maps change.
8632:
8633: An example is
8634:
8635: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
8636:
8637: The respective map entry is
8638:
8639: <resource id="19" src="/res/msu/korte/tests/part12.problem"
8640: title="Problem 2">
8641: </resource>
8642:
8643: Symbs are used by the random number generator, as well as to store and
8644: restore data specific to a certain instance of for example a problem.
8645:
8646: =head2 Storing And Retrieving Data
8647:
8648: X<store()>X<cstore()>X<restore()>Three of the most important functions
8649: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
8650: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
8651: is is the non-critical message twin of cstore. These functions are for
8652: handlers to store a perl hash to a user's permanent data space in an
8653: easy manner, and to retrieve it again on another call. It is expected
8654: that a handler would use this once at the beginning to retrieve data,
8655: and then again once at the end to send only the new data back.
8656:
8657: The data is stored in the user's data directory on the user's
8658: homeserver under the ID of the course.
8659:
8660: The hash that is returned by restore will have all of the previous
8661: value for all of the elements of the hash.
8662:
8663: Example:
8664:
8665: #creating a hash
8666: my %hash;
8667: $hash{'foo'}='bar';
8668:
8669: #storing it
8670: &Apache::lonnet::cstore(\%hash);
8671:
8672: #changing a value
8673: $hash{'foo'}='notbar';
8674:
8675: #adding a new value
8676: $hash{'bar'}='foo';
8677: &Apache::lonnet::cstore(\%hash);
8678:
8679: #retrieving the hash
8680: my %history=&Apache::lonnet::restore();
8681:
8682: #print the hash
8683: foreach my $key (sort(keys(%history))) {
8684: print("\%history{$key} = $history{$key}");
8685: }
8686:
8687: Will print out:
1.191 harris41 8688:
1.394 bowersj2 8689: %history{1:foo} = bar
8690: %history{1:keys} = foo:timestamp
8691: %history{1:timestamp} = 990455579
8692: %history{2:bar} = foo
8693: %history{2:foo} = notbar
8694: %history{2:keys} = foo:bar:timestamp
8695: %history{2:timestamp} = 990455580
8696: %history{bar} = foo
8697: %history{foo} = notbar
8698: %history{timestamp} = 990455580
8699: %history{version} = 2
8700:
8701: Note that the special hash entries C<keys>, C<version> and
8702: C<timestamp> were added to the hash. C<version> will be equal to the
8703: total number of versions of the data that have been stored. The
8704: C<timestamp> attribute will be the UNIX time the hash was
8705: stored. C<keys> is available in every historical section to list which
8706: keys were added or changed at a specific historical revision of a
8707: hash.
8708:
8709: B<Warning>: do not store the hash that restore returns directly. This
8710: will cause a mess since it will restore the historical keys as if the
8711: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 8712:
1.394 bowersj2 8713: Calling convention:
1.191 harris41 8714:
1.394 bowersj2 8715: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
8716: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 8717:
1.394 bowersj2 8718: For more detailed information, see lonnet specific documentation.
1.191 harris41 8719:
1.394 bowersj2 8720: =head1 RETURN MESSAGES
1.191 harris41 8721:
1.394 bowersj2 8722: =over 4
1.191 harris41 8723:
1.394 bowersj2 8724: =item * B<con_lost>: unable to contact remote host
1.191 harris41 8725:
1.394 bowersj2 8726: =item * B<con_delayed>: unable to contact remote host, message will be delivered
8727: when the connection is brought back up
1.191 harris41 8728:
1.394 bowersj2 8729: =item * B<con_failed>: unable to contact remote host and unable to save message
8730: for later delivery
1.191 harris41 8731:
1.394 bowersj2 8732: =item * B<error:>: an error a occured, a description of the error follows the :
1.191 harris41 8733:
1.394 bowersj2 8734: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 8735: that was requested
1.191 harris41 8736:
1.243 albertel 8737: =back
1.191 harris41 8738:
1.243 albertel 8739: =head1 PUBLIC SUBROUTINES
1.191 harris41 8740:
1.243 albertel 8741: =head2 Session Environment Functions
1.191 harris41 8742:
1.243 albertel 8743: =over 4
1.191 harris41 8744:
1.394 bowersj2 8745: =item *
8746: X<appenv()>
8747: B<appenv(%hash)>: the value of %hash is written to
8748: the user envirnoment file, and will be restored for each access this
1.620 albertel 8749: user makes during this session, also modifies the %env for the current
1.394 bowersj2 8750: process
1.191 harris41 8751:
8752: =item *
1.394 bowersj2 8753: X<delenv()>
8754: B<delenv($regexp)>: removes all items from the session
8755: environment file that matches the regular expression in $regexp. The
1.620 albertel 8756: values are also delted from the current processes %env.
1.191 harris41 8757:
1.795 albertel 8758: =item * get_env_multiple($name)
8759:
8760: gets $name from the %env hash, it seemlessly handles the cases where multiple
8761: values may be defined and end up as an array ref.
8762:
8763: returns an array of values
8764:
1.243 albertel 8765: =back
8766:
8767: =head2 User Information
1.191 harris41 8768:
1.243 albertel 8769: =over 4
1.191 harris41 8770:
8771: =item *
1.394 bowersj2 8772: X<queryauthenticate()>
8773: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 8774: authentication scheme
8775:
8776: =item *
1.394 bowersj2 8777: X<authenticate()>
8778: B<authenticate($uname,$upass,$udom)>: try to
8779: authenticate user from domain's lib servers (first use the current
8780: one). C<$upass> should be the users password.
1.191 harris41 8781:
8782: =item *
1.394 bowersj2 8783: X<homeserver()>
8784: B<homeserver($uname,$udom)>: find the server which has
8785: the user's directory and files (there must be only one), this caches
8786: the answer, and also caches if there is a borken connection.
1.191 harris41 8787:
8788: =item *
1.394 bowersj2 8789: X<idget()>
8790: B<idget($udom,@ids)>: find the usernames behind a list of IDs
8791: (IDs are a unique resource in a domain, there must be only 1 ID per
8792: username, and only 1 username per ID in a specific domain) (returns
8793: hash: id=>name,id=>name)
1.191 harris41 8794:
8795: =item *
1.394 bowersj2 8796: X<idrget()>
8797: B<idrget($udom,@unames)>: find the IDs behind a list of
8798: usernames (returns hash: name=>id,name=>id)
1.191 harris41 8799:
8800: =item *
1.394 bowersj2 8801: X<idput()>
8802: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 8803:
8804: =item *
1.394 bowersj2 8805: X<rolesinit()>
8806: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 8807:
8808: =item *
1.551 albertel 8809: X<getsection()>
8810: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 8811: course $cname, return section name/number or '' for "not in course"
8812: and '-1' for "no section"
8813:
8814: =item *
1.394 bowersj2 8815: X<userenvironment()>
8816: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 8817: passed in @what from the requested user's environment, returns a hash
8818:
1.858 raeburn 8819: =item *
8820: X<userlog_query()>
1.859 albertel 8821: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
8822: activity.log file. %filters defines filters applied when parsing the
8823: log file. These can be start or end timestamps, or the type of action
8824: - log to look for Login or Logout events, check for Checkin or
8825: Checkout, role for role selection. The response is in the form
8826: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
8827: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 8828:
1.243 albertel 8829: =back
8830:
8831: =head2 User Roles
8832:
8833: =over 4
8834:
8835: =item *
8836:
1.810 raeburn 8837: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 8838: F: full access
8839: U,I,K: authentication modes (cxx only)
8840: '': forbidden
8841: 1: user needs to choose course
8842: 2: browse allowed
1.766 albertel 8843: A: passphrase authentication needed
1.243 albertel 8844:
8845: =item *
8846:
8847: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
8848: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
8849: and course level
8850:
8851: =item *
8852:
8853: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
8854: explanation of a user role term
8855:
1.832 raeburn 8856: =item *
8857:
1.858 raeburn 8858: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
8859: All arguments are optional. Returns a hash of a roles, either for
8860: co-author/assistant author roles for a user's Construction Space
1.906 albertel 8861: (default), or if $context is 'userroles', roles for the user himself,
1.858 raeburn 8862: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
8863: and value is set to colon-separated start and end times for the role.
8864: If no username and domain are specified, will default to current
8865: user/domain. Types, roles, and roledoms are references to arrays,
8866: of role statuses (active, future or previous), roles
8867: (e.g., cc,in, st etc.) and domains of the roles which can be used
8868: to restrict the list of roles reported. If no array ref is
8869: provided for types, will default to return only active roles.
1.834 albertel 8870:
1.243 albertel 8871: =back
8872:
8873: =head2 User Modification
8874:
8875: =over 4
8876:
8877: =item *
8878:
8879: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
8880: user for the level given by URL. Optional start and end dates (leave empty
8881: string or zero for "no date")
1.191 harris41 8882:
8883: =item *
8884:
1.243 albertel 8885: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
8886: change a users, password, possible return values are: ok,
8887: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
8888: refused
1.191 harris41 8889:
8890: =item *
8891:
1.243 albertel 8892: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 8893:
8894: =item *
8895:
1.243 albertel 8896: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
8897: modify user
1.191 harris41 8898:
8899: =item *
8900:
1.286 matthew 8901: modifystudent
8902:
8903: modify a students enrollment and identification information.
8904: The course id is resolved based on the current users environment.
8905: This means the envoking user must be a course coordinator or otherwise
8906: associated with a course.
8907:
1.297 matthew 8908: This call is essentially a wrapper for lonnet::modifyuser and
8909: lonnet::modify_student_enrollment
1.286 matthew 8910:
8911: Inputs:
8912:
8913: =over 4
8914:
8915: =item B<$udom> Students loncapa domain
8916:
8917: =item B<$uname> Students loncapa login name
8918:
8919: =item B<$uid> Students id/student number
8920:
8921: =item B<$umode> Students authentication mode
8922:
8923: =item B<$upass> Students password
8924:
8925: =item B<$first> Students first name
8926:
8927: =item B<$middle> Students middle name
8928:
8929: =item B<$last> Students last name
8930:
8931: =item B<$gene> Students generation
8932:
8933: =item B<$usec> Students section in course
8934:
8935: =item B<$end> Unix time of the roles expiration
8936:
8937: =item B<$start> Unix time of the roles start date
8938:
8939: =item B<$forceid> If defined, allow $uid to be changed
8940:
8941: =item B<$desiredhome> server to use as home server for student
8942:
8943: =back
1.297 matthew 8944:
8945: =item *
8946:
8947: modify_student_enrollment
8948:
8949: Change a students enrollment status in a class. The environment variable
8950: 'role.request.course' must be defined for this function to proceed.
8951:
8952: Inputs:
8953:
8954: =over 4
8955:
8956: =item $udom, students domain
8957:
8958: =item $uname, students name
8959:
8960: =item $uid, students user id
8961:
8962: =item $first, students first name
8963:
8964: =item $middle
8965:
8966: =item $last
8967:
8968: =item $gene
8969:
8970: =item $usec
8971:
8972: =item $end
8973:
8974: =item $start
8975:
8976: =back
8977:
1.191 harris41 8978:
8979: =item *
8980:
1.243 albertel 8981: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
8982: custom role; give a custom role to a user for the level given by URL. Specify
8983: name and domain of role author, and role name
1.191 harris41 8984:
8985: =item *
8986:
1.243 albertel 8987: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 8988:
8989: =item *
8990:
1.243 albertel 8991: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
8992:
8993: =back
8994:
8995: =head2 Course Infomation
8996:
8997: =over 4
1.191 harris41 8998:
8999: =item *
9000:
1.631 albertel 9001: coursedescription($courseid) : returns a hash of information about the
9002: specified course id, including all environment settings for the
9003: course, the description of the course will be in the hash under the
9004: key 'description'
1.191 harris41 9005:
9006: =item *
9007:
1.624 albertel 9008: resdata($name,$domain,$type,@which) : request for current parameter
9009: setting for a specific $type, where $type is either 'course' or 'user',
9010: @what should be a list of parameters to ask about. This routine caches
9011: answers for 5 minutes.
1.243 albertel 9012:
1.877 foxr 9013: =item *
9014:
9015: get_courseresdata($courseid, $domain) : dump the entire course resource
9016: data base, returning a hash that is keyed by the resource name and has
9017: values that are the resource value. I believe that the timestamps and
9018: versions are also returned.
9019:
9020:
1.243 albertel 9021: =back
9022:
9023: =head2 Course Modification
9024:
9025: =over 4
1.191 harris41 9026:
9027: =item *
9028:
1.243 albertel 9029: writecoursepref($courseid,%prefs) : write preferences (environment
9030: database) for a course
1.191 harris41 9031:
9032: =item *
9033:
1.243 albertel 9034: createcourse($udom,$description,$url) : make/modify course
9035:
9036: =back
9037:
9038: =head2 Resource Subroutines
9039:
9040: =over 4
1.191 harris41 9041:
9042: =item *
9043:
1.243 albertel 9044: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 9045:
9046: =item *
9047:
1.243 albertel 9048: repcopy($filename) : subscribes to the requested file, and attempts to
9049: replicate from the owning library server, Might return
1.607 raeburn 9050: 'unavailable', 'not_found', 'forbidden', 'ok', or
9051: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 9052: resource. Expects the local filesystem pathname
9053: (/home/httpd/html/res/....)
9054:
9055: =back
9056:
9057: =head2 Resource Information
9058:
9059: =over 4
1.191 harris41 9060:
9061: =item *
9062:
1.243 albertel 9063: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
9064: a vairety of different possible values, $varname should be a request
9065: string, and the other parameters can be used to specify who and what
9066: one is asking about.
9067:
9068: Possible values for $varname are environment.lastname (or other item
9069: from the envirnment hash), user.name (or someother aspect about the
9070: user), resource.0.maxtries (or some other part and parameter of a
9071: resource)
1.204 albertel 9072:
9073: =item *
9074:
1.243 albertel 9075: directcondval($number) : get current value of a condition; reads from a state
9076: string
1.204 albertel 9077:
9078: =item *
9079:
1.243 albertel 9080: condval($condidx) : value of condition index based on state
1.204 albertel 9081:
9082: =item *
9083:
1.243 albertel 9084: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
9085: resource's metadata, $what should be either a specific key, or either
9086: 'keys' (to get a list of possible keys) or 'packages' to get a list of
9087: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
9088:
9089: this function automatically caches all requests
1.191 harris41 9090:
9091: =item *
9092:
1.243 albertel 9093: metadata_query($query,$custom,$customshow) : make a metadata query against the
9094: network of library servers; returns file handle of where SQL and regex results
9095: will be stored for query
1.191 harris41 9096:
9097: =item *
9098:
1.243 albertel 9099: symbread($filename) : return symbolic list entry (filename argument optional);
9100: returns the data handle
1.191 harris41 9101:
9102: =item *
9103:
1.243 albertel 9104: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 9105: a possible symb for the URL in $thisfn, and if is an encryypted
9106: resource that the user accessed using /enc/ returns a 1 on success, 0
9107: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 9108: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 9109:
1.191 harris41 9110:
9111: =item *
9112:
1.243 albertel 9113: symbclean($symb) : removes versions numbers from a symb, returns the
9114: cleaned symb
1.191 harris41 9115:
9116: =item *
9117:
1.243 albertel 9118: is_on_map($uri) : checks if the $uri is somewhere on the current
9119: course map, user must be in a course for it to work.
1.191 harris41 9120:
9121: =item *
9122:
1.243 albertel 9123: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 9124:
9125: =item *
9126:
1.243 albertel 9127: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
9128: a random seed, all arguments are optional, if they aren't sent it uses the
9129: environment to derive them. Note: if symb isn't sent and it can't get one
9130: from &symbread it will use the current time as its return value
1.191 harris41 9131:
9132: =item *
9133:
1.243 albertel 9134: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
9135: unfakeable, receipt
1.191 harris41 9136:
9137: =item *
9138:
1.620 albertel 9139: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 9140:
9141: =item *
9142:
1.243 albertel 9143: countacc($url) : count the number of accesses to a given URL
1.191 harris41 9144:
9145: =item *
9146:
1.243 albertel 9147: 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 9148:
9149: =item *
9150:
1.243 albertel 9151: 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 9152:
9153: =item *
9154:
1.243 albertel 9155: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 9156:
9157: =item *
9158:
1.243 albertel 9159: devalidate($symb) : devalidate temporary spreadsheet calculations,
9160: forcing spreadsheet to reevaluate the resource scores next time.
9161:
9162: =back
9163:
9164: =head2 Storing/Retreiving Data
9165:
9166: =over 4
1.191 harris41 9167:
9168: =item *
9169:
1.243 albertel 9170: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
9171: for this url; hashref needs to be given and should be a \%hashname; the
9172: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 9173: be derived from the env
1.191 harris41 9174:
9175: =item *
9176:
1.243 albertel 9177: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
9178: uses critical subroutine
1.191 harris41 9179:
9180: =item *
9181:
1.243 albertel 9182: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
9183: all args are optional
1.191 harris41 9184:
9185: =item *
9186:
1.717 albertel 9187: dumpstore($namespace,$udom,$uname,$regexp,$range) :
9188: dumps the complete (or key matching regexp) namespace into a hash
9189: ($udom, $uname, $regexp, $range are optional) for a namespace that is
9190: normally &store()ed into
9191:
9192: $range should be either an integer '100' (give me the first 100
9193: matching records)
9194: or be two integers sperated by a - with no spaces
9195: '30-50' (give me the 30th through the 50th matching
9196: records)
9197:
9198:
9199: =item *
9200:
9201: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
9202: replaces a &store() version of data with a replacement set of data
9203: for a particular resource in a namespace passed in the $storehash hash
9204: reference
9205:
9206: =item *
9207:
1.243 albertel 9208: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
9209: works very similar to store/cstore, but all data is stored in a
9210: temporary location and can be reset using tmpreset, $storehash should
9211: be a hash reference, returns nothing on success
1.191 harris41 9212:
9213: =item *
9214:
1.243 albertel 9215: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
9216: similar to restore, but all data is stored in a temporary location and
9217: can be reset using tmpreset. Returns a hash of values on success,
9218: error string otherwise.
1.191 harris41 9219:
9220: =item *
9221:
1.243 albertel 9222: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
9223: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 9224:
9225: =item *
9226:
1.243 albertel 9227: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9228: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 9229:
9230: =item *
9231:
1.243 albertel 9232: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
9233: namesp ($udom and $uname are optional)
1.191 harris41 9234:
9235: =item *
9236:
1.702 albertel 9237: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 9238: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 9239: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 9240:
1.702 albertel 9241: $range should be either an integer '100' (give me the first 100
9242: matching records)
9243: or be two integers sperated by a - with no spaces
9244: '30-50' (give me the 30th through the 50th matching
9245: records)
1.449 matthew 9246: =item *
9247:
9248: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
9249: $store can be a scalar, an array reference, or if the amount to be
9250: incremented is > 1, a hash reference.
9251:
9252: ($udom and $uname are optional)
1.191 harris41 9253:
9254: =item *
9255:
1.243 albertel 9256: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
9257: ($udom and $uname are optional)
1.191 harris41 9258:
9259: =item *
9260:
1.243 albertel 9261: cput($namespace,$storehash,$udom,$uname) : critical put
9262: ($udom and $uname are optional)
1.191 harris41 9263:
9264: =item *
9265:
1.748 albertel 9266: newput($namespace,$storehash,$udom,$uname) :
9267:
9268: Attempts to store the items in the $storehash, but only if they don't
9269: currently exist, if this succeeds you can be certain that you have
9270: successfully created a new key value pair in the $namespace db.
9271:
9272:
9273: Args:
9274: $namespace: name of database to store values to
9275: $storehash: hashref to store to the db
9276: $udom: (optional) domain of user containing the db
9277: $uname: (optional) name of user caontaining the db
9278:
9279: Returns:
9280: 'ok' -> succeeded in storing all keys of $storehash
9281: 'key_exists: <key>' -> failed to anything out of $storehash, as at
9282: least <key> already existed in the db (other
9283: requested keys may also already exist)
9284: 'error: <msg>' -> unable to tie the DB or other erorr occured
9285: 'con_lost' -> unable to contact request server
9286: 'refused' -> action was not allowed by remote machine
9287:
9288:
9289: =item *
9290:
1.243 albertel 9291: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9292: reference filled in from namesp (encrypts the return communication)
9293: ($udom and $uname are optional)
1.191 harris41 9294:
9295: =item *
9296:
1.243 albertel 9297: log($udom,$name,$home,$message) : write to permanent log for user; use
9298: critical subroutine
9299:
1.806 raeburn 9300: =item *
9301:
1.860 raeburn 9302: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
9303: array reference filled in from namespace found in domain level on either
9304: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 9305:
9306: =item *
9307:
1.860 raeburn 9308: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
9309: domain level either on specified domain server ($uhome) or primary domain
9310: server ($udom and $uhome are optional)
1.806 raeburn 9311:
1.243 albertel 9312: =back
9313:
9314: =head2 Network Status Functions
9315:
9316: =over 4
1.191 harris41 9317:
9318: =item *
9319:
9320: dirlist($uri) : return directory list based on URI
9321:
9322: =item *
9323:
1.243 albertel 9324: spareserver() : find server with least workload from spare.tab
9325:
9326: =back
9327:
9328: =head2 Apache Request
9329:
9330: =over 4
1.191 harris41 9331:
9332: =item *
9333:
1.243 albertel 9334: ssi($url,%hash) : server side include, does a complete request cycle on url to
9335: localhost, posts hash
9336:
9337: =back
9338:
9339: =head2 Data to String to Data
9340:
9341: =over 4
1.191 harris41 9342:
9343: =item *
9344:
1.243 albertel 9345: hash2str(%hash) : convert a hash into a string complete with escaping and '='
9346: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 9347:
9348: =item *
9349:
1.243 albertel 9350: hashref2str($hashref) : convert a hashref into a string complete with
9351: escaping and '=' and '&' separators, supports elements that are
9352: arrayrefs and hashrefs
1.191 harris41 9353:
9354: =item *
9355:
1.243 albertel 9356: arrayref2str($arrayref) : convert an arrayref into a string complete
9357: with escaping and '&' separators, supports elements that are arrayrefs
9358: and hashrefs
1.191 harris41 9359:
9360: =item *
9361:
1.243 albertel 9362: str2hash($string) : convert string to hash using unescaping and
9363: splitting on '=' and '&', supports elements that are arrayrefs and
9364: hashrefs
1.191 harris41 9365:
9366: =item *
9367:
1.243 albertel 9368: str2array($string) : convert string to hash using unescaping and
9369: splitting on '&', supports elements that are arrayrefs and hashrefs
9370:
9371: =back
9372:
9373: =head2 Logging Routines
9374:
9375: =over 4
9376:
9377: These routines allow one to make log messages in the lonnet.log and
9378: lonnet.perm logfiles.
1.191 harris41 9379:
9380: =item *
9381:
1.243 albertel 9382: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 9383:
9384: =item *
9385:
1.243 albertel 9386: logthis() : append message to the normal lonnet.log file, it gets
9387: preiodically rolled over and deleted.
1.191 harris41 9388:
9389: =item *
9390:
1.243 albertel 9391: logperm() : append a permanent message to lonnet.perm.log, this log
9392: file never gets deleted by any automated portion of the system, only
9393: messages of critical importance should go in here.
9394:
9395: =back
9396:
9397: =head2 General File Helper Routines
9398:
9399: =over 4
1.191 harris41 9400:
9401: =item *
9402:
1.481 raeburn 9403: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
9404: (a) files in /uploaded
9405: (i) If a local copy of the file exists -
9406: compares modification date of local copy with last-modified date for
9407: definitive version stored on home server for course. If local copy is
9408: stale, requests a new version from the home server and stores it.
9409: If the original has been removed from the home server, then local copy
9410: is unlinked.
9411: (ii) If local copy does not exist -
9412: requests the file from the home server and stores it.
9413:
9414: If $caller is 'uploadrep':
9415: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
9416: for request for files originally uploaded via DOCS.
9417: - returns 'ok' if fresh local copy now available, -1 otherwise.
9418:
9419: Otherwise:
9420: This indicates a call from the content generation phase of the request.
9421: - returns the entire contents of the file or -1.
9422:
9423: (b) files in /res
9424: - returns the entire contents of a file or -1;
9425: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 9426:
1.712 albertel 9427:
9428: =item *
9429:
9430: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
9431: reference
9432:
9433: returns either a stat() list of data about the file or an empty list
9434: if the file doesn't exist or couldn't find out about it (connection
9435: problems or user unknown)
9436:
1.191 harris41 9437: =item *
9438:
1.243 albertel 9439: filelocation($dir,$file) : returns file system location of a file
9440: based on URI; meant to be "fairly clean" absolute reference, $dir is a
9441: directory that relative $file lookups are to looked in ($dir of /a/dir
9442: and a file of ../bob will become /a/bob)
1.191 harris41 9443:
9444: =item *
9445:
9446: hreflocation($dir,$file) : returns file system location or a URL; same as
9447: filelocation except for hrefs
9448:
9449: =item *
9450:
9451: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
9452:
1.243 albertel 9453: =back
9454:
1.608 albertel 9455: =head2 Usererfile file routines (/uploaded*)
9456:
9457: =over 4
9458:
9459: =item *
9460:
9461: userfileupload(): main rotine for putting a file in a user or course's
9462: filespace, arguments are,
9463:
1.620 albertel 9464: formname - required - this is the name of the element in $env where the
1.608 albertel 9465: filename, and the contents of the file to create/modifed exist
1.620 albertel 9466: the filename is in $env{'form.'.$formname.'.filename'} and the
9467: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 9468: coursedoc - if true, store the file in the course of the active role
9469: of the current user
9470: subdir - required - subdirectory to put the file in under ../userfiles/
9471: if undefined, it will be placed in "unknown"
9472:
9473: (This routine calls clean_filename() to remove any dangerous
9474: characters from the filename, and then calls finuserfileupload() to
9475: complete the transaction)
9476:
9477: returns either the url of the uploaded file (/uploaded/....) if successful
9478: and /adm/notfound.html if unsuccessful
9479:
9480: =item *
9481:
9482: clean_filename(): routine for cleaing a filename up for storage in
9483: userfile space, argument is:
9484:
9485: filename - proposed filename
9486:
9487: returns: the new clean filename
9488:
9489: =item *
9490:
9491: finishuserfileupload(): routine that creaes and sends the file to
9492: userspace, probably shouldn't be called directly
9493:
9494: docuname: username or courseid of destination for the file
9495: docudom: domain of user/course of destination for the file
9496: formname: same as for userfileupload()
9497: fname: filename (inculding subdirectories) for the file
9498:
9499: returns either the url of the uploaded file (/uploaded/....) if successful
9500: and /adm/notfound.html if unsuccessful
9501:
9502: =item *
9503:
9504: renameuserfile(): renames an existing userfile to a new name
9505:
9506: Args:
9507: docuname: username or courseid of destination for the file
9508: docudom: domain of user/course of destination for the file
9509: old: current file name (including any subdirs under userfiles)
9510: new: desired file name (including any subdirs under userfiles)
9511:
9512: =item *
9513:
9514: mkdiruserfile(): creates a directory is a userfiles dir
9515:
9516: Args:
9517: docuname: username or courseid of destination for the file
9518: docudom: domain of user/course of destination for the file
9519: dir: dir to create (including any subdirs under userfiles)
9520:
9521: =item *
9522:
9523: removeuserfile(): removes a file that exists in userfiles
9524:
9525: Args:
9526: docuname: username or courseid of destination for the file
9527: docudom: domain of user/course of destination for the file
9528: fname: filname to delete (including any subdirs under userfiles)
9529:
9530: =item *
9531:
9532: removeuploadedurl(): convience function for removeuserfile()
9533:
9534: Args:
9535: url: a full /uploaded/... url to delete
9536:
1.747 albertel 9537: =item *
9538:
9539: get_portfile_permissions():
9540: Args:
9541: domain: domain of user or course contain the portfolio files
9542: user: name of user or num of course contain the portfolio files
9543: Returns:
9544: hashref of a dump of the proper file_permissions.db
9545:
9546:
9547: =item *
9548:
9549: get_access_controls():
9550:
9551: Args:
9552: current_permissions: the hash ref returned from get_portfile_permissions()
9553: group: (optional) the group you want the files associated with
9554: file: (optional) the file you want access info on
9555:
9556: Returns:
1.749 raeburn 9557: a hash (keys are file names) of hashes containing
9558: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
9559: values are XML containing access control settings (see below)
1.747 albertel 9560:
9561: Internal notes:
9562:
1.749 raeburn 9563: access controls are stored in file_permissions.db as key=value pairs.
9564: key -> path to file/file_name\0uniqueID:scope_end_start
9565: where scope -> public,guest,course,group,domains or users.
9566: end -> UNIX time for end of access (0 -> no end date)
9567: start -> UNIX time for start of access
9568:
9569: value -> XML description of access control
9570: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
9571: <start></start>
9572: <end></end>
9573:
9574: <password></password> for scope type = guest
9575:
9576: <domain></domain> for scope type = course or group
9577: <number></number>
9578: <roles id="">
9579: <role></role>
9580: <access></access>
9581: <section></section>
9582: <group></group>
9583: </roles>
9584:
9585: <dom></dom> for scope type = domains
9586:
9587: <users> for scope type = users
9588: <user>
9589: <uname></uname>
9590: <udom></udom>
9591: </user>
9592: </users>
9593: </scope>
9594:
9595: Access data is also aggregated for each file in an additional key=value pair:
9596: key -> path to file/file_name\0accesscontrol
9597: value -> reference to hash
9598: hash contains key = value pairs
9599: where key = uniqueID:scope_end_start
9600: value = UNIX time record was last updated
9601:
9602: Used to improve speed of look-ups of access controls for each file.
9603:
9604: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
9605:
9606: modify_access_controls():
9607:
9608: Modifies access controls for a portfolio file
9609: Args
9610: 1. file name
9611: 2. reference to hash of required changes,
9612: 3. domain
9613: 4. username
9614: where domain,username are the domain of the portfolio owner
9615: (either a user or a course)
9616:
9617: Returns:
9618: 1. result of additions or updates ('ok' or 'error', with error message).
9619: 2. result of deletions ('ok' or 'error', with error message).
9620: 3. reference to hash of any new or updated access controls.
9621: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
9622: key = integer (inbound ID)
9623: value = uniqueID
1.747 albertel 9624:
1.608 albertel 9625: =back
9626:
1.243 albertel 9627: =head2 HTTP Helper Routines
9628:
9629: =over 4
9630:
1.191 harris41 9631: =item *
9632:
9633: escape() : unpack non-word characters into CGI-compatible hex codes
9634:
9635: =item *
9636:
9637: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
9638:
1.243 albertel 9639: =back
9640:
9641: =head1 PRIVATE SUBROUTINES
9642:
9643: =head2 Underlying communication routines (Shouldn't call)
9644:
9645: =over 4
9646:
9647: =item *
9648:
9649: subreply() : tries to pass a message to lonc, returns con_lost if incapable
9650:
9651: =item *
9652:
9653: reply() : uses subreply to send a message to remote machine, logs all failures
9654:
9655: =item *
9656:
9657: critical() : passes a critical message to another server; if cannot
9658: get through then place message in connection buffer directory and
9659: returns con_delayed, if incapable of saving message, returns
9660: con_failed
9661:
9662: =item *
9663:
9664: reconlonc() : tries to reconnect lonc client processes.
9665:
9666: =back
9667:
9668: =head2 Resource Access Logging
9669:
9670: =over 4
9671:
9672: =item *
9673:
9674: flushcourselogs() : flush (save) buffer logs and access logs
9675:
9676: =item *
9677:
9678: courselog($what) : save message for course in hash
9679:
9680: =item *
9681:
9682: courseacclog($what) : save message for course using &courselog(). Perform
9683: special processing for specific resource types (problems, exams, quizzes, etc).
9684:
1.191 harris41 9685: =item *
9686:
9687: goodbye() : flush course logs and log shutting down; it is called in srm.conf
9688: as a PerlChildExitHandler
1.243 albertel 9689:
9690: =back
9691:
9692: =head2 Other
9693:
9694: =over 4
9695:
9696: =item *
9697:
9698: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 9699:
9700: =back
9701:
9702: =cut
1.877 foxr 9703:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>