Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.922
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.922 ! raeburn 4: # $Id: lonnet.pm,v 1.921 2007/10/06 04:32:40 raeburn 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: # there is a copy in lond
517: sub userload {
518: my $numusers=0;
519: {
520: opendir(LONIDS,$perlvar{'lonIDsDir'});
521: my $filename;
522: my $curtime=time;
523: while ($filename=readdir(LONIDS)) {
524: if ($filename eq '.' || $filename eq '..') {next;}
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 {
1050: my ($udom,$uname,$rules) = @_;
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')) {
1058: my $response=&unescape(&reply('instrulecheck:'.&escape($udom).':'.
1059: &escape($uname).':'.$rulestr,
1060: $homeserver));
1061: if ($response ne 'refused') {
1062: my @pairs=split(/\&/,$response);
1063: foreach my $item (@pairs) {
1064: my ($key,$value)=split(/=/,$item,2);
1065: $key = &unescape($key);
1066: next if ($key =~ /^error: 2 /);
1067: $returnhash{$key}=&thaw_unescape($value);
1068: }
1069: }
1070: }
1071: }
1072: }
1073: return %returnhash;
1074: }
1075:
1076: sub inst_userrules {
1077: my ($udom) = @_;
1078: my (%ruleshash,@ruleorder);
1079: if ($udom ne '') {
1080: my $homeserver=&domain($udom,'primary');
1081: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1082: my $response=&reply('instuserrules:'.&escape($udom),
1083: $homeserver);
1084: if (($response ne 'refused') && ($response ne 'error') &&
1085: ($response ne 'no_such_host')) {
1086: my ($hashitems,$orderitems) = split(/:/,$response);
1087: my @pairs=split(/\&/,$hashitems);
1088: foreach my $item (@pairs) {
1089: my ($key,$value)=split(/=/,$item,2);
1090: $key = &unescape($key);
1091: next if ($key =~ /^error: 2 /);
1092: $ruleshash{$key}=&thaw_unescape($value);
1093: }
1094: my @esc_order = split(/\&/,$orderitems);
1095: foreach my $item (@esc_order) {
1096: push(@ruleorder,&unescape($item));
1097: }
1098: }
1099: }
1100: }
1101: return (\%ruleshash,\@ruleorder);
1102: }
1103:
1.344 www 1104: # --------------------------------------------------- Assign a key to a student
1105:
1106: sub assign_access_key {
1.364 www 1107: #
1108: # a valid key looks like uname:udom#comments
1109: # comments are being appended
1110: #
1.498 www 1111: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1112: $kdom=
1.620 albertel 1113: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1114: $knum=
1.620 albertel 1115: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1116: $cdom=
1.620 albertel 1117: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1118: $cnum=
1.620 albertel 1119: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1120: $udom=$env{'user.name'} unless (defined($udom));
1121: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1122: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1123: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1124: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1125: # assigned to this person
1126: # - this should not happen,
1.345 www 1127: # unless something went wrong
1128: # the first time around
1129: # ready to assign
1.364 www 1130: $logentry=$1.'; '.$logentry;
1.496 www 1131: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1132: $kdom,$knum) eq 'ok') {
1.345 www 1133: # key now belongs to user
1.346 www 1134: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1135: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1136: &appenv('environment.'.$envkey => $ckey);
1137: return 'ok';
1138: } else {
1139: return
1140: 'error: Count not permanently assign key, will need to be re-entered later.';
1141: }
1142: } else {
1143: return 'error: Could not assign key, try again later.';
1144: }
1.364 www 1145: } elsif (!$existing{$ckey}) {
1.345 www 1146: # the key does not exist
1147: return 'error: The key does not exist';
1148: } else {
1149: # the key is somebody else's
1150: return 'error: The key is already in use';
1151: }
1.344 www 1152: }
1153:
1.364 www 1154: # ------------------------------------------ put an additional comment on a key
1155:
1156: sub comment_access_key {
1157: #
1158: # a valid key looks like uname:udom#comments
1159: # comments are being appended
1160: #
1161: my ($ckey,$cdom,$cnum,$logentry)=@_;
1162: $cdom=
1.620 albertel 1163: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1164: $cnum=
1.620 albertel 1165: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1166: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1167: if ($existing{$ckey}) {
1168: $existing{$ckey}.='; '.$logentry;
1169: # ready to assign
1.367 www 1170: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1171: $cdom,$cnum) eq 'ok') {
1172: return 'ok';
1173: } else {
1174: return 'error: Count not store comment.';
1175: }
1176: } else {
1177: # the key does not exist
1178: return 'error: The key does not exist';
1179: }
1180: }
1181:
1.344 www 1182: # ------------------------------------------------------ Generate a set of keys
1183:
1184: sub generate_access_keys {
1.364 www 1185: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1186: $cdom=
1.620 albertel 1187: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1188: $cnum=
1.620 albertel 1189: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1190: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1191: unless (($cdom) && ($cnum)) { return 0; }
1192: if ($number>10000) { return 0; }
1193: sleep(2); # make sure don't get same seed twice
1194: srand(time()^($$+($$<<15))); # from "Programming Perl"
1195: my $total=0;
1196: for (my $i=1;$i<=$number;$i++) {
1197: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1198: sprintf("%lx",int(100000*rand)).'-'.
1199: sprintf("%lx",int(100000*rand));
1200: $newkey=~s/1/g/g; # folks mix up 1 and l
1201: $newkey=~s/0/h/g; # and also 0 and O
1202: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1203: if ($existing{$newkey}) {
1204: $i--;
1205: } else {
1.364 www 1206: if (&put('accesskeys',
1207: { $newkey => '# generated '.localtime().
1.620 albertel 1208: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1209: '; '.$logentry },
1210: $cdom,$cnum) eq 'ok') {
1.344 www 1211: $total++;
1212: }
1213: }
1214: }
1.620 albertel 1215: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1216: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1217: return $total;
1218: }
1219:
1220: # ------------------------------------------------------- Validate an accesskey
1221:
1222: sub validate_access_key {
1223: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1224: $cdom=
1.620 albertel 1225: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1226: $cnum=
1.620 albertel 1227: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1228: $udom=$env{'user.domain'} unless (defined($udom));
1229: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1230: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1231: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1232: }
1233:
1234: # ------------------------------------- Find the section of student in a course
1.652 albertel 1235: sub devalidate_getsection_cache {
1236: my ($udom,$unam,$courseid)=@_;
1237: my $hashid="$udom:$unam:$courseid";
1238: &devalidate_cache_new('getsection',$hashid);
1239: }
1.298 matthew 1240:
1.815 albertel 1241: sub courseid_to_courseurl {
1242: my ($courseid) = @_;
1243: #already url style courseid
1244: return $courseid if ($courseid =~ m{^/});
1245:
1246: if (exists($env{'course.'.$courseid.'.num'})) {
1247: my $cnum = $env{'course.'.$courseid.'.num'};
1248: my $cdom = $env{'course.'.$courseid.'.domain'};
1249: return "/$cdom/$cnum";
1250: }
1251:
1252: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1253: if (exists($courseinfo{'num'})) {
1254: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1255: }
1256:
1257: return undef;
1258: }
1259:
1.298 matthew 1260: sub getsection {
1261: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1262: my $cachetime=1800;
1.551 albertel 1263:
1264: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1265: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1266: if (defined($cached)) { return $result; }
1267:
1.298 matthew 1268: my %Pending;
1269: my %Expired;
1270: #
1271: # Each role can either have not started yet (pending), be active,
1272: # or have expired.
1273: #
1274: # If there is an active role, we are done.
1275: #
1276: # If there is more than one role which has not started yet,
1277: # choose the one which will start sooner
1278: # If there is one role which has not started yet, return it.
1279: #
1280: # If there is more than one expired role, choose the one which ended last.
1281: # If there is a role which has expired, return it.
1282: #
1.815 albertel 1283: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1284: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1285: foreach my $key (keys(%roleshash)) {
1.479 albertel 1286: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1287: my $section=$1;
1288: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1289: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1290: my $now=time;
1.548 albertel 1291: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1292: $Expired{$end}=$section;
1293: next;
1294: }
1.548 albertel 1295: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1296: $Pending{$start}=$section;
1297: next;
1298: }
1.599 albertel 1299: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1300: }
1301: #
1302: # Presumedly there will be few matching roles from the above
1303: # loop and the sorting time will be negligible.
1304: if (scalar(keys(%Pending))) {
1305: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1306: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1307: }
1308: if (scalar(keys(%Expired))) {
1309: my @sorted = sort {$a <=> $b} keys(%Expired);
1310: my $time = pop(@sorted);
1.599 albertel 1311: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1312: }
1.599 albertel 1313: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1314: }
1.70 www 1315:
1.599 albertel 1316: sub save_cache {
1317: &purge_remembered();
1.722 albertel 1318: #&Apache::loncommon::validate_page();
1.620 albertel 1319: undef(%env);
1.780 albertel 1320: undef($env_loaded);
1.599 albertel 1321: }
1.452 albertel 1322:
1.599 albertel 1323: my $to_remember=-1;
1324: my %remembered;
1325: my %accessed;
1326: my $kicks=0;
1327: my $hits=0;
1.849 albertel 1328: sub make_key {
1329: my ($name,$id) = @_;
1.872 albertel 1330: if (length($id) > 65
1331: && length(&escape($id)) > 200) {
1332: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1333: }
1.849 albertel 1334: return &escape($name.':'.$id);
1335: }
1336:
1.599 albertel 1337: sub devalidate_cache_new {
1338: my ($name,$id,$debug) = @_;
1339: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1340: $id=&make_key($name,$id);
1.599 albertel 1341: $memcache->delete($id);
1342: delete($remembered{$id});
1343: delete($accessed{$id});
1344: }
1345:
1346: sub is_cached_new {
1347: my ($name,$id,$debug) = @_;
1.849 albertel 1348: $id=&make_key($name,$id);
1.599 albertel 1349: if (exists($remembered{$id})) {
1350: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1351: $accessed{$id}=[&gettimeofday()];
1352: $hits++;
1353: return ($remembered{$id},1);
1354: }
1355: my $value = $memcache->get($id);
1356: if (!(defined($value))) {
1357: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1358: return (undef,undef);
1.416 albertel 1359: }
1.599 albertel 1360: if ($value eq '__undef__') {
1361: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1362: $value=undef;
1363: }
1364: &make_room($id,$value,$debug);
1365: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1366: return ($value,1);
1367: }
1368:
1369: sub do_cache_new {
1370: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1371: $id=&make_key($name,$id);
1.599 albertel 1372: my $setvalue=$value;
1373: if (!defined($setvalue)) {
1374: $setvalue='__undef__';
1375: }
1.623 albertel 1376: if (!defined($time) ) {
1377: $time=600;
1378: }
1.599 albertel 1379: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1380: my $result = $memcache->set($id,$setvalue,$time);
1381: if (! $result) {
1.872 albertel 1382: &logthis("caching of id -> $id failed");
1.910 albertel 1383: $memcache->disconnect_all();
1.872 albertel 1384: }
1.600 albertel 1385: # need to make a copy of $value
1.919 albertel 1386: &make_room($id,$value,$debug);
1.599 albertel 1387: return $value;
1388: }
1389:
1390: sub make_room {
1391: my ($id,$value,$debug)=@_;
1.919 albertel 1392:
1393: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1394: : $value;
1.599 albertel 1395: if ($to_remember<0) { return; }
1396: $accessed{$id}=[&gettimeofday()];
1397: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1398: my $to_kick;
1399: my $max_time=0;
1400: foreach my $other (keys(%accessed)) {
1401: if (&tv_interval($accessed{$other}) > $max_time) {
1402: $to_kick=$other;
1403: $max_time=&tv_interval($accessed{$other});
1404: }
1405: }
1406: delete($remembered{$to_kick});
1407: delete($accessed{$to_kick});
1408: $kicks++;
1409: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1410: return;
1411: }
1412:
1.599 albertel 1413: sub purge_remembered {
1.604 albertel 1414: #&logthis("Tossing ".scalar(keys(%remembered)));
1415: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1416: undef(%remembered);
1417: undef(%accessed);
1.428 albertel 1418: }
1.70 www 1419: # ------------------------------------- Read an entry from a user's environment
1420:
1421: sub userenvironment {
1422: my ($udom,$unam,@what)=@_;
1423: my %returnhash=();
1424: my @answer=split(/\&/,
1425: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
1426: &homeserver($unam,$udom)));
1427: my $i;
1428: for ($i=0;$i<=$#what;$i++) {
1429: $returnhash{$what[$i]}=&unescape($answer[$i]);
1430: }
1431: return %returnhash;
1.1 albertel 1432: }
1433:
1.617 albertel 1434: # ---------------------------------------------------------- Get a studentphoto
1435: sub studentphoto {
1436: my ($udom,$unam,$ext) = @_;
1437: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1438: if (defined($env{'request.course.id'})) {
1.708 raeburn 1439: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1440: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1441: return(&retrievestudentphoto($udom,$unam,$ext));
1442: } else {
1443: my ($result,$perm_reqd)=
1.707 albertel 1444: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1445: if ($result eq 'ok') {
1446: if (!($perm_reqd eq 'yes')) {
1447: return(&retrievestudentphoto($udom,$unam,$ext));
1448: }
1449: }
1450: }
1451: }
1452: } else {
1453: my ($result,$perm_reqd) =
1.707 albertel 1454: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1455: if ($result eq 'ok') {
1456: if (!($perm_reqd eq 'yes')) {
1457: return(&retrievestudentphoto($udom,$unam,$ext));
1458: }
1459: }
1460: }
1461: return '/adm/lonKaputt/lonlogo_broken.gif';
1462: }
1463:
1464: sub retrievestudentphoto {
1465: my ($udom,$unam,$ext,$type) = @_;
1466: my $home=&Apache::lonnet::homeserver($unam,$udom);
1467: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1468: if ($ret eq 'ok') {
1469: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1470: if ($type eq 'thumbnail') {
1471: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1472: }
1473: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1474: return $tokenurl;
1475: } else {
1476: if ($type eq 'thumbnail') {
1477: return '/adm/lonKaputt/genericstudent_tn.gif';
1478: } else {
1479: return '/adm/lonKaputt/lonlogo_broken.gif';
1480: }
1.617 albertel 1481: }
1482: }
1483:
1.263 www 1484: # -------------------------------------------------------------------- New chat
1485:
1486: sub chatsend {
1.724 raeburn 1487: my ($newentry,$anon,$group)=@_;
1.620 albertel 1488: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1489: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1490: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1491: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1492: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1493: &escape($newentry)).':'.$group,$chome);
1.292 www 1494: }
1495:
1496: # ------------------------------------------ Find current version of a resource
1497:
1498: sub getversion {
1499: my $fname=&clutter(shift);
1500: unless ($fname=~/^\/res\//) { return -1; }
1501: return ¤tversion(&filelocation('',$fname));
1502: }
1503:
1504: sub currentversion {
1505: my $fname=shift;
1.599 albertel 1506: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1507: if (defined($cached)) { return $result; }
1.292 www 1508: my $author=$fname;
1509: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1510: my ($udom,$uname)=split(/\//,$author);
1511: my $home=homeserver($uname,$udom);
1512: if ($home eq 'no_host') {
1513: return -1;
1514: }
1515: my $answer=reply("currentversion:$fname",$home);
1516: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1517: return -1;
1518: }
1.599 albertel 1519: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1520: }
1521:
1.1 albertel 1522: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1523:
1.1 albertel 1524: sub subscribe {
1525: my $fname=shift;
1.761 raeburn 1526: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1527: $fname=~s/[\n\r]//g;
1.1 albertel 1528: my $author=$fname;
1529: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1530: my ($udom,$uname)=split(/\//,$author);
1531: my $home=homeserver($uname,$udom);
1.335 albertel 1532: if ($home eq 'no_host') {
1533: return 'not_found';
1.1 albertel 1534: }
1535: my $answer=reply("sub:$fname",$home);
1.64 www 1536: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1537: $answer.=' by '.$home;
1538: }
1.1 albertel 1539: return $answer;
1540: }
1541:
1.8 www 1542: # -------------------------------------------------------------- Replicate file
1543:
1544: sub repcopy {
1545: my $filename=shift;
1.23 www 1546: $filename=~s/\/+/\//g;
1.607 raeburn 1547: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1548: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1549: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1550: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1551: return &repcopy_userfile($filename);
1552: }
1.532 albertel 1553: $filename=~s/[\n\r]//g;
1.8 www 1554: my $transname="$filename.in.transfer";
1.828 www 1555: # FIXME: this should flock
1.607 raeburn 1556: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1557: my $remoteurl=subscribe($filename);
1.64 www 1558: if ($remoteurl =~ /^con_lost by/) {
1559: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1560: return 'unavailable';
1.8 www 1561: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1562: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1563: return 'not_found';
1.64 www 1564: } elsif ($remoteurl =~ /^rejected by/) {
1565: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1566: return 'forbidden';
1.20 www 1567: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1568: return 'ok';
1.8 www 1569: } else {
1.290 www 1570: my $author=$filename;
1571: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1572: my ($udom,$uname)=split(/\//,$author);
1573: my $home=homeserver($uname,$udom);
1574: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1575: my @parts=split(/\//,$filename);
1576: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1577: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1578: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1579: return 'bad_request';
1.8 www 1580: }
1581: my $count;
1582: for ($count=5;$count<$#parts;$count++) {
1583: $path.="/$parts[$count]";
1584: if ((-e $path)!=1) {
1585: mkdir($path,0777);
1586: }
1587: }
1588: my $ua=new LWP::UserAgent;
1589: my $request=new HTTP::Request('GET',"$remoteurl");
1590: my $response=$ua->request($request,$transname);
1591: if ($response->is_error()) {
1592: unlink($transname);
1593: my $message=$response->status_line;
1.672 albertel 1594: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1595: ." LWP get: $message: $filename</font>");
1.607 raeburn 1596: return 'unavailable';
1.8 www 1597: } else {
1.16 www 1598: if ($remoteurl!~/\.meta$/) {
1599: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1600: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1601: if ($mresponse->is_error()) {
1602: unlink($filename.'.meta');
1603: &logthis(
1.672 albertel 1604: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1605: }
1606: }
1.8 www 1607: rename($transname,$filename);
1.607 raeburn 1608: return 'ok';
1.8 www 1609: }
1.290 www 1610: }
1.8 www 1611: }
1.330 www 1612: }
1613:
1614: # ------------------------------------------------ Get server side include body
1615: sub ssi_body {
1.381 albertel 1616: my ($filelink,%form)=@_;
1.606 matthew 1617: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1618: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1619: }
1.330 www 1620: my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381 albertel 1621: &ssi($filelink,%form));
1.778 albertel 1622: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1623: $output=~s/^.*?\<body[^\>]*\>//si;
1624: $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330 www 1625: return $output;
1.8 www 1626: }
1627:
1.15 www 1628: # --------------------------------------------------------- Server Side Include
1629:
1.782 albertel 1630: sub absolute_url {
1631: my ($host_name) = @_;
1632: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1633: if ($host_name eq '') {
1634: $host_name = $ENV{'SERVER_NAME'};
1635: }
1636: return $protocol.$host_name;
1637: }
1638:
1.15 www 1639: sub ssi {
1640:
1.23 www 1641: my ($fn,%form)=@_;
1.15 www 1642:
1643: my $ua=new LWP::UserAgent;
1.23 www 1644:
1645: my $request;
1.711 albertel 1646:
1647: $form{'no_update_last_known'}=1;
1.895 albertel 1648: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 1649: if (%form) {
1.782 albertel 1650: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201 albertel 1651: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23 www 1652: } else {
1.782 albertel 1653: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1654: }
1655:
1.15 www 1656: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1657: my $response=$ua->request($request);
1658:
1.324 www 1659: return $response->content;
1660: }
1661:
1662: sub externalssi {
1663: my ($url)=@_;
1664: my $ua=new LWP::UserAgent;
1665: my $request=new HTTP::Request('GET',$url);
1666: my $response=$ua->request($request);
1.15 www 1667: return $response->content;
1668: }
1.254 www 1669:
1.492 albertel 1670: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1671:
1672: sub allowuploaded {
1673: my ($srcurl,$url)=@_;
1674: $url=&clutter(&declutter($url));
1675: my $dir=$url;
1676: $dir=~s/\/[^\/]+$//;
1677: my %httpref=();
1678: my $httpurl=&hreflocation('',$url);
1679: $httpref{'httpref.'.$httpurl}=$srcurl;
1680: &Apache::lonnet::appenv(%httpref);
1.254 www 1681: }
1.477 raeburn 1682:
1.478 albertel 1683: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1684: # input: action, courseID, current domain, intended
1.637 raeburn 1685: # path to file, source of file, instruction to parse file for objects,
1686: # ref to hash for embedded objects,
1687: # ref to hash for codebase of java objects.
1688: #
1.485 raeburn 1689: # output: url to file (if action was uploaddoc),
1690: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 1691: #
1.478 albertel 1692: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1693: # course.
1.477 raeburn 1694: #
1.478 albertel 1695: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1696: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1697: # course's home server.
1.477 raeburn 1698: #
1.478 albertel 1699: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1700: # be copied from $source (current location) to
1701: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1702: # and will then be copied to
1703: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1704: # course's home server.
1.485 raeburn 1705: #
1.481 raeburn 1706: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 1707: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 1708: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1709: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1710: # in course's home server.
1.637 raeburn 1711: #
1.477 raeburn 1712:
1713: sub process_coursefile {
1.638 albertel 1714: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 1715: my $fetchresult;
1.638 albertel 1716: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 1717: if ($action eq 'propagate') {
1.638 albertel 1718: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1719: $home);
1.481 raeburn 1720: } else {
1.477 raeburn 1721: my $fpath = '';
1722: my $fname = $file;
1.478 albertel 1723: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 1724: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 1725: my $filepath = &build_filepath($fpath);
1.481 raeburn 1726: if ($action eq 'copy') {
1727: if ($source eq '') {
1728: $fetchresult = 'no source file';
1729: return $fetchresult;
1730: } else {
1731: my $destination = $filepath.'/'.$fname;
1732: rename($source,$destination);
1733: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1734: $home);
1.481 raeburn 1735: }
1736: } elsif ($action eq 'uploaddoc') {
1737: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 1738: print $fh $env{'form.'.$source};
1.481 raeburn 1739: close($fh);
1.637 raeburn 1740: if ($parser eq 'parse') {
1741: my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
1742: unless ($parse_result eq 'ok') {
1743: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1744: }
1745: }
1.477 raeburn 1746: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1747: $home);
1.481 raeburn 1748: if ($fetchresult eq 'ok') {
1749: return '/uploaded/'.$fpath.'/'.$fname;
1750: } else {
1751: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1752: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 1753: return '/adm/notfound.html';
1754: }
1.477 raeburn 1755: }
1756: }
1.485 raeburn 1757: unless ( $fetchresult eq 'ok') {
1.477 raeburn 1758: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1759: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 1760: }
1761: return $fetchresult;
1762: }
1763:
1.637 raeburn 1764: sub build_filepath {
1765: my ($fpath) = @_;
1766: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1767: unless ($fpath eq '') {
1768: my @parts=split('/',$fpath);
1769: foreach my $part (@parts) {
1770: $filepath.= '/'.$part;
1771: if ((-e $filepath)!=1) {
1772: mkdir($filepath,0777);
1773: }
1774: }
1775: }
1776: return $filepath;
1777: }
1778:
1779: sub store_edited_file {
1.638 albertel 1780: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 1781: my $file = $primary_url;
1782: $file =~ s#^/uploaded/$docudom/$docuname/##;
1783: my $fpath = '';
1784: my $fname = $file;
1785: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1786: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1787: my $filepath = &build_filepath($fpath);
1788: open(my $fh,'>'.$filepath.'/'.$fname);
1789: print $fh $content;
1790: close($fh);
1.638 albertel 1791: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 1792: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1793: $home);
1.637 raeburn 1794: if ($$fetchresult eq 'ok') {
1795: return '/uploaded/'.$fpath.'/'.$fname;
1796: } else {
1.638 albertel 1797: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1798: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 1799: return '/adm/notfound.html';
1800: }
1801: }
1802:
1.531 albertel 1803: sub clean_filename {
1.831 albertel 1804: my ($fname,$args)=@_;
1.315 www 1805: # Replace Windows backslashes by forward slashes
1.257 www 1806: $fname=~s/\\/\//g;
1.831 albertel 1807: if (!$args->{'keep_path'}) {
1808: # Get rid of everything but the actual filename
1809: $fname=~s/^.*\/([^\/]+)$/$1/;
1810: }
1.315 www 1811: # Replace spaces by underscores
1812: $fname=~s/\s+/\_/g;
1813: # Replace all other weird characters by nothing
1.831 albertel 1814: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 1815: # Replace all .\d. sequences with _\d. so they no longer look like version
1816: # numbers
1817: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 1818: return $fname;
1819: }
1820:
1.608 albertel 1821: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 1822: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 1823: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 1824: # $coursedoc - if true up to the current course
1825: # if false
1826: # $subdir - directory in userfile to store the file into
1.858 raeburn 1827: # $parser - instruction to parse file for objects ($parser = parse)
1828: # $allfiles - reference to hash for embedded objects
1829: # $codebase - reference to hash for codebase of java objects
1830: # $desuname - username for permanent storage of uploaded file
1831: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 1832: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
1833: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858 raeburn 1834: #
1.686 albertel 1835: # output: url of file in userspace, or error: <message>
1836: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 1837:
1838:
1.531 albertel 1839: sub userfileupload {
1.860 raeburn 1840: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1841: $destudom,$thumbwidth,$thumbheight)=@_;
1.531 albertel 1842: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 1843: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 1844: $fname=&clean_filename($fname);
1.315 www 1845: # See if there is anything left
1.257 www 1846: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 1847: chop($env{'form.'.$formname});
1.523 raeburn 1848: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
1849: my $now = time;
1850: my $filepath = 'tmp/helprequests/'.$now;
1851: my @parts=split(/\//,$filepath);
1852: my $fullpath = $perlvar{'lonDaemons'};
1853: for (my $i=0;$i<@parts;$i++) {
1854: $fullpath .= '/'.$parts[$i];
1855: if ((-e $fullpath)!=1) {
1856: mkdir($fullpath,0777);
1857: }
1858: }
1859: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 1860: print $fh $env{'form.'.$formname};
1.523 raeburn 1861: close($fh);
1.741 raeburn 1862: return $fullpath.'/'.$fname;
1863: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
1864: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
1865: '_'.$env{'user.domain'}.'/pending';
1866: my @parts=split(/\//,$filepath);
1867: my $fullpath = $perlvar{'lonDaemons'};
1868: for (my $i=0;$i<@parts;$i++) {
1869: $fullpath .= '/'.$parts[$i];
1870: if ((-e $fullpath)!=1) {
1871: mkdir($fullpath,0777);
1872: }
1873: }
1874: open(my $fh,'>'.$fullpath.'/'.$fname);
1875: print $fh $env{'form.'.$formname};
1876: close($fh);
1877: return $fullpath.'/'.$fname;
1.523 raeburn 1878: }
1.719 banghart 1879:
1.258 www 1880: # Create the directory if not present
1.493 albertel 1881: $fname="$subdir/$fname";
1.259 www 1882: if ($coursedoc) {
1.638 albertel 1883: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1884: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 1885: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 1886: return &finishuserfileupload($docuname,$docudom,
1887: $formname,$fname,$parser,$allfiles,
1.860 raeburn 1888: $codebase,$thumbwidth,$thumbheight);
1.481 raeburn 1889: } else {
1.620 albertel 1890: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 1891: return &process_coursefile('uploaddoc',$docuname,$docudom,
1892: $fname,$formname,$parser,
1893: $allfiles,$codebase);
1.481 raeburn 1894: }
1.719 banghart 1895: } elsif (defined($destuname)) {
1896: my $docuname=$destuname;
1897: my $docudom=$destudom;
1.860 raeburn 1898: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
1899: $parser,$allfiles,$codebase,
1900: $thumbwidth,$thumbheight);
1.719 banghart 1901:
1.259 www 1902: } else {
1.638 albertel 1903: my $docuname=$env{'user.name'};
1904: my $docudom=$env{'user.domain'};
1.714 raeburn 1905: if (exists($env{'form.group'})) {
1906: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1907: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1908: }
1.860 raeburn 1909: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
1910: $parser,$allfiles,$codebase,
1911: $thumbwidth,$thumbheight);
1.259 www 1912: }
1.271 www 1913: }
1914:
1915: sub finishuserfileupload {
1.860 raeburn 1916: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1917: $thumbwidth,$thumbheight) = @_;
1.477 raeburn 1918: my $path=$docudom.'/'.$docuname.'/';
1.258 www 1919: my $filepath=$perlvar{'lonDocRoot'};
1.860 raeburn 1920: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 1921: $file=$fname;
1922: if ($fname=~m|/|) {
1923: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
1924: $path.=$fnamepath.'/';
1925: }
1.259 www 1926: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 1927: my $count;
1928: for ($count=4;$count<=$#parts;$count++) {
1929: $filepath.="/$parts[$count]";
1930: if ((-e $filepath)!=1) {
1931: mkdir($filepath,0777);
1932: }
1933: }
1934: # Save the file
1935: {
1.701 albertel 1936: if (!open(FH,'>'.$filepath.'/'.$file)) {
1937: &logthis('Failed to create '.$filepath.'/'.$file);
1938: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
1939: return '/adm/notfound.html';
1940: }
1941: if (!print FH ($env{'form.'.$formname})) {
1942: &logthis('Failed to write to '.$filepath.'/'.$file);
1943: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
1944: return '/adm/notfound.html';
1945: }
1.570 albertel 1946: close(FH);
1.258 www 1947: }
1.637 raeburn 1948: if ($parser eq 'parse') {
1.638 albertel 1949: my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
1950: $codebase);
1.637 raeburn 1951: unless ($parse_result eq 'ok') {
1.638 albertel 1952: &logthis('Failed to parse '.$filepath.$file.
1953: ' for embedded media: '.$parse_result);
1.637 raeburn 1954: }
1955: }
1.860 raeburn 1956: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
1957: my $input = $filepath.'/'.$file;
1958: my $output = $filepath.'/'.'tn-'.$file;
1959: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1960: system("convert -sample $thumbsize $input $output");
1961: if (-e $filepath.'/'.'tn-'.$file) {
1962: $fetchthumb = 1;
1963: }
1964: }
1.858 raeburn 1965:
1.259 www 1966: # Notify homeserver to grep it
1967: #
1.638 albertel 1968: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 1969: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 1970: if ($fetchresult eq 'ok') {
1.860 raeburn 1971: if ($fetchthumb) {
1972: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
1973: if ($thumbresult ne 'ok') {
1974: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
1975: $docuhome.': '.$thumbresult);
1976: }
1977: }
1.259 www 1978: #
1.258 www 1979: # Return the URL to it
1.494 albertel 1980: return '/uploaded/'.$path.$file;
1.263 www 1981: } else {
1.494 albertel 1982: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
1983: ': '.$fetchresult);
1.263 www 1984: return '/adm/notfound.html';
1.858 raeburn 1985: }
1.493 albertel 1986: }
1987:
1.637 raeburn 1988: sub extract_embedded_items {
1.648 raeburn 1989: my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637 raeburn 1990: my @state = ();
1991: my %javafiles = (
1992: codebase => '',
1993: code => '',
1994: archive => ''
1995: );
1996: my %mediafiles = (
1997: src => '',
1998: movie => '',
1999: );
1.648 raeburn 2000: my $p;
2001: if ($content) {
2002: $p = HTML::LCParser->new($content);
2003: } else {
2004: $p = HTML::LCParser->new($filepath.'/'.$file);
2005: }
1.641 albertel 2006: while (my $t=$p->get_token()) {
1.640 albertel 2007: if ($t->[0] eq 'S') {
2008: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2009: push(@state, $tagname);
1.648 raeburn 2010: if (lc($tagname) eq 'allow') {
2011: &add_filetype($allfiles,$attr->{'src'},'src');
2012: }
1.640 albertel 2013: if (lc($tagname) eq 'img') {
2014: &add_filetype($allfiles,$attr->{'src'},'src');
2015: }
1.886 albertel 2016: if (lc($tagname) eq 'a') {
2017: &add_filetype($allfiles,$attr->{'href'},'href');
2018: }
1.645 raeburn 2019: if (lc($tagname) eq 'script') {
2020: if ($attr->{'archive'} =~ /\.jar$/i) {
2021: &add_filetype($allfiles,$attr->{'archive'},'archive');
2022: } else {
2023: &add_filetype($allfiles,$attr->{'src'},'src');
2024: }
2025: }
2026: if (lc($tagname) eq 'link') {
2027: if (lc($attr->{'rel'}) eq 'stylesheet') {
2028: &add_filetype($allfiles,$attr->{'href'},'href');
2029: }
2030: }
1.640 albertel 2031: if (lc($tagname) eq 'object' ||
2032: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2033: foreach my $item (keys(%javafiles)) {
2034: $javafiles{$item} = '';
2035: }
2036: }
2037: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2038: my $name = lc($attr->{'name'});
2039: foreach my $item (keys(%javafiles)) {
2040: if ($name eq $item) {
2041: $javafiles{$item} = $attr->{'value'};
2042: last;
2043: }
2044: }
2045: foreach my $item (keys(%mediafiles)) {
2046: if ($name eq $item) {
2047: &add_filetype($allfiles, $attr->{'value'}, 'value');
2048: last;
2049: }
2050: }
2051: }
2052: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2053: foreach my $item (keys(%javafiles)) {
2054: if ($attr->{$item}) {
2055: $javafiles{$item} = $attr->{$item};
2056: last;
2057: }
2058: }
2059: foreach my $item (keys(%mediafiles)) {
2060: if ($attr->{$item}) {
2061: &add_filetype($allfiles,$attr->{$item},$item);
2062: last;
2063: }
2064: }
2065: }
2066: } elsif ($t->[0] eq 'E') {
2067: my ($tagname) = ($t->[1]);
2068: if ($javafiles{'codebase'} ne '') {
2069: $javafiles{'codebase'} .= '/';
2070: }
2071: if (lc($tagname) eq 'applet' ||
2072: lc($tagname) eq 'object' ||
2073: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2074: ) {
2075: foreach my $item (keys(%javafiles)) {
2076: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2077: my $file=$javafiles{'codebase'}.$javafiles{$item};
2078: &add_filetype($allfiles,$file,$item);
2079: }
2080: }
2081: }
2082: pop @state;
2083: }
2084: }
1.637 raeburn 2085: return 'ok';
2086: }
2087:
1.639 albertel 2088: sub add_filetype {
2089: my ($allfiles,$file,$type)=@_;
2090: if (exists($allfiles->{$file})) {
2091: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2092: push(@{$allfiles->{$file}}, &escape($type));
2093: }
2094: } else {
2095: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2096: }
2097: }
2098:
1.493 albertel 2099: sub removeuploadedurl {
2100: my ($url)=@_;
2101: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2102: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2103: }
2104:
2105: sub removeuserfile {
2106: my ($docuname,$docudom,$fname)=@_;
2107: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2108: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
2109: if ($result eq 'ok') {
2110: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2111: my $metafile = $fname.'.meta';
2112: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2113: my $url = "/uploaded/$docudom/$docuname/$fname";
2114: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2115: my $sqlresult =
1.823 albertel 2116: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2117: 'portfolio_metadata',$group,
2118: 'delete');
1.798 raeburn 2119: }
2120: }
2121: return $result;
1.257 www 2122: }
1.15 www 2123:
1.530 albertel 2124: sub mkdiruserfile {
2125: my ($docuname,$docudom,$dir)=@_;
2126: my $home=&homeserver($docuname,$docudom);
2127: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2128: }
2129:
1.531 albertel 2130: sub renameuserfile {
2131: my ($docuname,$docudom,$old,$new)=@_;
2132: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2133: my $result = &reply("renameuserfile:$docudom:$docuname:".
2134: &escape("$old").':'.&escape("$new"),$home);
2135: if ($result eq 'ok') {
2136: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2137: my $oldmeta = $old.'.meta';
2138: my $newmeta = $new.'.meta';
2139: my $metaresult =
2140: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2141: my $url = "/uploaded/$docudom/$docuname/$old";
2142: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2143: my $sqlresult =
1.823 albertel 2144: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2145: 'portfolio_metadata',$group,
2146: 'delete');
1.798 raeburn 2147: }
2148: }
2149: return $result;
1.531 albertel 2150: }
2151:
1.14 www 2152: # ------------------------------------------------------------------------- Log
2153:
2154: sub log {
2155: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2156: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2157: }
2158:
2159: # ------------------------------------------------------------------ Course Log
1.352 www 2160: #
2161: # This routine flushes several buffers of non-mission-critical nature
2162: #
1.157 www 2163:
2164: sub flushcourselogs {
1.352 www 2165: &logthis('Flushing log buffers');
2166: #
2167: # course logs
2168: # This is a log of all transactions in a course, which can be used
2169: # for data mining purposes
2170: #
2171: # It also collects the courseid database, which lists last transaction
2172: # times and course titles for all courseids
2173: #
2174: my %courseidbuffer=();
1.921 raeburn 2175: foreach my $crsid (keys(%courselogs)) {
1.352 www 2176: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2177: &escape($courselogs{$crsid}),
2178: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2179: delete $courselogs{$crsid};
2180: } else {
2181: &logthis('Failed to flush log buffer for '.$crsid);
2182: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2183: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2184: " exceeded maximum size, deleting.</font>");
2185: delete $courselogs{$crsid};
2186: }
1.352 www 2187: }
1.920 raeburn 2188: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.918 raeburn 2189: 'description' => &escape($coursedescrbuf{$crsid}),
1.921 raeburn 2190: 'inst_code' => &escape($courseinstcodebuf{$crsid}),
1.918 raeburn 2191: 'type' => &escape($coursetypebuf{$crsid}),
2192: 'owner' => &escape($courseownerbuf{$crsid}),
1.920 raeburn 2193: };
1.191 harris41 2194: }
1.352 www 2195: #
2196: # Write course id database (reverse lookup) to homeserver of courses
2197: # Is used in pickcourse
2198: #
1.840 albertel 2199: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2200: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2201: $courseidbuffer{$crs_home},
2202: $crs_home,'timeonly');
1.352 www 2203: }
2204: #
2205: # File accesses
2206: # Writes to the dynamic metadata of resources to get hit counts, etc.
2207: #
1.449 matthew 2208: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2209: if ($entry =~ /___count$/) {
2210: my ($dom,$name);
1.807 albertel 2211: ($dom,$name,undef)=
1.811 albertel 2212: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2213: if (! defined($dom) || $dom eq '' ||
2214: ! defined($name) || $name eq '') {
1.620 albertel 2215: my $cid = $env{'request.course.id'};
2216: $dom = $env{'request.'.$cid.'.domain'};
2217: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2218: }
1.450 matthew 2219: my $value = $accesshash{$entry};
2220: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2221: my %temphash=($url => $value);
1.449 matthew 2222: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2223: if ($result eq 'ok') {
2224: delete $accesshash{$entry};
2225: } elsif ($result eq 'unknown_cmd') {
2226: # Target server has old code running on it.
1.450 matthew 2227: my %temphash=($entry => $value);
1.449 matthew 2228: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2229: delete $accesshash{$entry};
2230: }
2231: }
2232: } else {
1.811 albertel 2233: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2234: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2235: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2236: delete $accesshash{$entry};
2237: }
1.185 www 2238: }
1.191 harris41 2239: }
1.352 www 2240: #
2241: # Roles
2242: # Reverse lookup of user roles for course faculty/staff and co-authorship
2243: #
1.800 albertel 2244: foreach my $entry (keys(%userrolehash)) {
1.351 www 2245: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2246: split(/\:/,$entry);
2247: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2248: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2249: $rudom,$runame) eq 'ok') {
2250: delete $userrolehash{$entry};
2251: }
2252: }
1.662 raeburn 2253: #
2254: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2255: #
2256: my %domrolebuffer = ();
2257: foreach my $entry (keys %domainrolehash) {
1.901 albertel 2258: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2259: if ($domrolebuffer{$rudom}) {
2260: $domrolebuffer{$rudom}.='&'.&escape($entry).
2261: '='.&escape($domainrolehash{$entry});
2262: } else {
2263: $domrolebuffer{$rudom}.=&escape($entry).
2264: '='.&escape($domainrolehash{$entry});
2265: }
2266: delete $domainrolehash{$entry};
2267: }
2268: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2269: my %servers = &get_servers($dom,'library');
2270: foreach my $tryserver (keys(%servers)) {
2271: unless (&reply('domroleput:'.$dom.':'.
2272: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2273: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2274: }
1.662 raeburn 2275: }
2276: }
1.186 www 2277: $dumpcount++;
1.157 www 2278: }
2279:
2280: sub courselog {
2281: my $what=shift;
1.158 www 2282: $what=time.':'.$what;
1.620 albertel 2283: unless ($env{'request.course.id'}) { return ''; }
2284: $coursedombuf{$env{'request.course.id'}}=
2285: $env{'course.'.$env{'request.course.id'}.'.domain'};
2286: $coursenumbuf{$env{'request.course.id'}}=
2287: $env{'course.'.$env{'request.course.id'}.'.num'};
2288: $coursehombuf{$env{'request.course.id'}}=
2289: $env{'course.'.$env{'request.course.id'}.'.home'};
2290: $coursedescrbuf{$env{'request.course.id'}}=
2291: $env{'course.'.$env{'request.course.id'}.'.description'};
2292: $courseinstcodebuf{$env{'request.course.id'}}=
2293: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2294: $courseownerbuf{$env{'request.course.id'}}=
2295: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2296: $coursetypebuf{$env{'request.course.id'}}=
2297: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2298: if (defined $courselogs{$env{'request.course.id'}}) {
2299: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2300: } else {
1.620 albertel 2301: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2302: }
1.620 albertel 2303: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2304: &flushcourselogs();
2305: }
1.158 www 2306: }
2307:
2308: sub courseacclog {
2309: my $fnsymb=shift;
1.620 albertel 2310: unless ($env{'request.course.id'}) { return ''; }
2311: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2312: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2313: $what.=':POST';
1.583 matthew 2314: # FIXME: Probably ought to escape things....
1.800 albertel 2315: foreach my $key (keys(%env)) {
2316: if ($key=~/^form\.(.*)/) {
2317: $what.=':'.$1.'='.$env{$key};
1.158 www 2318: }
1.191 harris41 2319: }
1.583 matthew 2320: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2321: # FIXME: We should not be depending on a form parameter that someone
2322: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2323: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2324: $what.= ':POST';
2325: # FIXME: Probably ought to escape things....
2326: foreach my $element ('courseexp','crsfulltext','crsrelated',
2327: 'crsdiscuss') {
1.620 albertel 2328: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2329: }
2330: }
1.158 www 2331: }
2332: &courselog($what);
1.149 www 2333: }
2334:
1.185 www 2335: sub countacc {
2336: my $url=&declutter(shift);
1.458 matthew 2337: return if (! defined($url) || $url eq '');
1.620 albertel 2338: unless ($env{'request.course.id'}) { return ''; }
2339: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2340: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2341: $accesshash{$key}++;
1.185 www 2342: }
1.349 www 2343:
1.361 www 2344: sub linklog {
2345: my ($from,$to)=@_;
2346: $from=&declutter($from);
2347: $to=&declutter($to);
2348: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2349: $accesshash{$to.'___'.$from.'___goto'}=1;
2350: }
2351:
1.349 www 2352: sub userrolelog {
2353: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2354: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2355: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2356: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2357: ($trole=~/^ta/)) {
1.350 www 2358: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2359: $userrolehash
2360: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2361: =$tend.':'.$tstart;
1.662 raeburn 2362: }
1.898 albertel 2363: if (($env{'request.role'} =~ /dc\./) &&
2364: (($trole=~/^au/) || ($trole=~/^in/) ||
2365: ($trole=~/^cc/) || ($trole=~/^ep/) ||
2366: ($trole=~/^cr/) || ($trole=~/^ta/))) {
2367: $userrolehash
2368: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2369: =$tend.':'.$tstart;
2370: }
1.662 raeburn 2371: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2372: ($trole=~/^li/) || ($trole=~/^li/) ||
2373: ($trole=~/^au/) || ($trole=~/^dg/) ||
2374: ($trole=~/^sc/)) {
2375: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2376: $domainrolehash
2377: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2378: = $tend.':'.$tstart;
2379: }
1.351 www 2380: }
2381:
2382: sub get_course_adv_roles {
2383: my $cid=shift;
1.620 albertel 2384: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2385: my %coursehash=&coursedescription($cid);
1.470 www 2386: my %nothide=();
1.800 albertel 2387: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2388: $nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470 www 2389: }
1.351 www 2390: my %returnhash=();
2391: my %dumphash=
2392: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2393: my $now=time;
1.800 albertel 2394: foreach my $entry (keys %dumphash) {
2395: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2396: if (($tstart) && ($tstart<0)) { next; }
2397: if (($tend) && ($tend<$now)) { next; }
2398: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2399: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2400: if ($username eq '' || $domain eq '') { next; }
1.470 www 2401: if ((&privileged($username,$domain)) &&
2402: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2403: if ($role eq 'cr') { next; }
1.351 www 2404: my $key=&plaintext($role);
2405: if ($section) { $key.=' (Sec/Grp '.$section.')'; }
2406: if ($returnhash{$key}) {
2407: $returnhash{$key}.=','.$username.':'.$domain;
2408: } else {
2409: $returnhash{$key}=$username.':'.$domain;
2410: }
1.400 www 2411: }
2412: return %returnhash;
2413: }
2414:
2415: sub get_my_roles {
1.858 raeburn 2416: my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620 albertel 2417: unless (defined($uname)) { $uname=$env{'user.name'}; }
2418: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858 raeburn 2419: my %dumphash;
2420: if ($context eq 'userroles') {
2421: %dumphash = &dump('roles',$udom,$uname);
2422: } else {
2423: %dumphash=
1.400 www 2424: &dump('nohist_userroles',$udom,$uname);
1.858 raeburn 2425: }
1.400 www 2426: my %returnhash=();
2427: my $now=time;
1.800 albertel 2428: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2429: my ($role,$tend,$tstart);
2430: if ($context eq 'userroles') {
2431: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2432: } else {
2433: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2434: }
1.400 www 2435: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2436: my $status = 'active';
2437: if (($tend) && ($tend<$now)) {
2438: $status = 'previous';
2439: }
2440: if (($tstart) && ($now<$tstart)) {
2441: $status = 'future';
2442: }
2443: if (ref($types) eq 'ARRAY') {
2444: if (!grep(/^\Q$status\E$/,@{$types})) {
2445: next;
2446: }
2447: } else {
2448: if ($status ne 'active') {
2449: next;
2450: }
2451: }
1.867 raeburn 2452: my ($rolecode,$username,$domain,$section,$area);
2453: if ($context eq 'userroles') {
2454: ($area,$rolecode) = split(/_/,$entry);
2455: (undef,$domain,$username,$section) = split(/\//,$area);
2456: } else {
2457: ($role,$username,$domain,$section) = split(/\:/,$entry);
2458: }
1.832 raeburn 2459: if (ref($roledoms) eq 'ARRAY') {
2460: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2461: next;
2462: }
2463: }
2464: if (ref($roles) eq 'ARRAY') {
2465: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 ! raeburn 2466: if ($role =~ /^cr\//) {
! 2467: if (!grep(/^cr$/,@{$roles})) {
! 2468: next;
! 2469: }
! 2470: } else {
! 2471: next;
! 2472: }
1.832 raeburn 2473: }
1.867 raeburn 2474: }
1.400 www 2475: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832 raeburn 2476: }
1.373 www 2477: return %returnhash;
1.399 www 2478: }
2479:
2480: # ----------------------------------------------------- Frontpage Announcements
2481: #
2482: #
2483:
2484: sub postannounce {
2485: my ($server,$text)=@_;
1.844 albertel 2486: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2487: unless ($text=~/\w/) { $text=''; }
2488: return &reply('setannounce:'.&escape($text),$server);
2489: }
2490:
2491: sub getannounce {
1.448 albertel 2492:
2493: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 2494: my $announcement='';
1.800 albertel 2495: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 2496: close($fh);
1.399 www 2497: if ($announcement=~/\w/) {
2498: return
2499: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 2500: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 2501: } else {
2502: return '';
2503: }
2504: } else {
2505: return '';
2506: }
1.351 www 2507: }
1.353 www 2508:
2509: # ---------------------------------------------------------- Course ID routines
2510: # Deal with domain's nohist_courseid.db files
2511: #
2512:
2513: sub courseidput {
1.921 raeburn 2514: my ($domain,$storehash,$coursehome,$caller) = @_;
2515: my $outcome;
2516: if ($caller eq 'timeonly') {
2517: my $cids = '';
2518: foreach my $item (keys(%$storehash)) {
2519: $cids.=&escape($item).'&';
2520: }
2521: $cids=~s/\&$//;
2522: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
2523: $coursehome);
2524: } else {
2525: my $items = '';
2526: foreach my $item (keys(%$storehash)) {
2527: $items.= &escape($item).'='.
2528: &freeze_escape($$storehash{$item}).'&';
2529: }
2530: $items=~s/\&$//;
2531: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
2532: $coursehome);
1.918 raeburn 2533: }
2534: if ($outcome eq 'unknown_cmd') {
2535: my $what;
2536: foreach my $cid (keys(%$storehash)) {
2537: $what .= &escape($cid).'=';
1.921 raeburn 2538: foreach my $item ('description','inst_code','owner','type') {
2539: $what .= &escape($storehash->{$item}).':';
1.918 raeburn 2540: }
2541: $what =~ s/\:$/&/;
2542: }
2543: $what =~ s/\&$//;
2544: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2545: } else {
2546: return $outcome;
2547: }
1.353 www 2548: }
2549:
2550: sub courseiddump {
1.921 raeburn 2551: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
2552: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.918 raeburn 2553: my $as_hash = 1;
2554: my %returnhash;
2555: if (!$domfilter) { $domfilter=''; }
1.845 albertel 2556: my %libserv = &all_library();
2557: foreach my $tryserver (keys(%libserv)) {
2558: if ( ( $hostidflag == 1
2559: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
2560: || (!defined($hostidflag)) ) {
2561:
1.918 raeburn 2562: if (($domfilter eq '') ||
2563: (&host_domain($tryserver) eq $domfilter)) {
2564: my $rep =
2565: &reply('courseiddump:'.&host_domain($tryserver).':'.
2566: $sincefilter.':'.&escape($descfilter).':'.
2567: &escape($instcodefilter).':'.&escape($ownerfilter).
2568: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.921 raeburn 2569: ':'.&escape($regexp_ok).':'.$as_hash,$tryserver);
1.918 raeburn 2570: my @pairs=split(/\&/,$rep);
2571: foreach my $item (@pairs) {
2572: my ($key,$value)=split(/\=/,$item,2);
2573: $key = &unescape($key);
2574: next if ($key =~ /^error: 2 /);
2575: my $result = &thaw_unescape($value);
2576: if (ref($result) eq 'HASH') {
2577: $returnhash{$key}=$result;
2578: } else {
1.921 raeburn 2579: my @responses = split(/:/,$value);
2580: my @items = ('description','inst_code','owner','type');
1.918 raeburn 2581: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 2582: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 2583: }
2584: }
1.353 www 2585: }
2586: }
2587: }
2588: }
2589: return %returnhash;
2590: }
2591:
1.658 raeburn 2592: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 2593:
2594: sub dcmailput {
1.685 raeburn 2595: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 2596: my $status = &Apache::lonnet::critical(
1.740 www 2597: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2598: &escape($message),$server);
1.662 raeburn 2599: return $status;
2600: }
2601:
1.658 raeburn 2602: sub dcmaildump {
2603: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 2604: my %returnhash=();
1.846 albertel 2605:
2606: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 2607: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2608: &escape($enddate).':';
2609: my @esc_senders=map { &escape($_)} @$senders;
2610: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 2611: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 2612: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 2613: if (($key) && ($value)) {
2614: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 2615: }
2616: }
2617: }
2618: return %returnhash;
2619: }
1.662 raeburn 2620: # ---------------------------------------------------------- Domain roles
2621:
2622: sub get_domain_roles {
2623: my ($dom,$roles,$startdate,$enddate)=@_;
2624: if (undef($startdate) || $startdate eq '') {
2625: $startdate = '.';
2626: }
2627: if (undef($enddate) || $enddate eq '') {
2628: $enddate = '.';
2629: }
1.922 ! raeburn 2630: my $rolelist;
! 2631: if (ref($roles) eq 'ARRAY') {
! 2632: $rolelist = join(':',@{$roles});
! 2633: }
1.662 raeburn 2634: my %personnel = ();
1.841 albertel 2635:
2636: my %servers = &get_servers($dom,'library');
2637: foreach my $tryserver (keys(%servers)) {
2638: %{$personnel{$tryserver}}=();
2639: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
2640: &escape($startdate).':'.
2641: &escape($enddate).':'.
2642: &escape($rolelist), $tryserver))) {
2643: my ($key,$value) = split(/\=/,$line,2);
2644: if (($key) && ($value)) {
2645: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2646: }
2647: }
1.662 raeburn 2648: }
2649: return %personnel;
2650: }
1.658 raeburn 2651:
1.149 www 2652: # ----------------------------------------------------------- Check out an item
2653:
1.504 albertel 2654: sub get_first_access {
2655: my ($type,$argsymb)=@_;
1.790 albertel 2656: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2657: if ($argsymb) { $symb=$argsymb; }
2658: my ($map,$id,$res)=&decode_symb($symb);
1.588 albertel 2659: if ($type eq 'map') {
2660: $res=&symbread($map);
2661: } else {
2662: $res=$symb;
2663: }
2664: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2665: return $times{"$courseid\0$res"};
1.504 albertel 2666: }
2667:
2668: sub set_first_access {
2669: my ($type)=@_;
1.790 albertel 2670: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2671: my ($map,$id,$res)=&decode_symb($symb);
1.588 albertel 2672: if ($type eq 'map') {
2673: $res=&symbread($map);
2674: } else {
2675: $res=$symb;
2676: }
2677: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 2678: if (!$firstaccess) {
1.588 albertel 2679: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 2680: }
2681: return 'already_set';
1.504 albertel 2682: }
2683:
1.149 www 2684: sub checkout {
2685: my ($symb,$tuname,$tudom,$tcrsid)=@_;
2686: my $now=time;
2687: my $lonhost=$perlvar{'lonHostID'};
2688: my $infostr=&escape(
1.234 www 2689: 'CHECKOUTTOKEN&'.
1.149 www 2690: $tuname.'&'.
2691: $tudom.'&'.
2692: $tcrsid.'&'.
2693: $symb.'&'.
2694: $now.'&'.$ENV{'REMOTE_ADDR'});
2695: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 2696: if ($token=~/^error\:/) {
1.672 albertel 2697: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2698: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
2699: "</font>");
2700: return '';
2701: }
2702:
1.149 www 2703: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
2704: $token=~tr/a-z/A-Z/;
2705:
1.153 www 2706: my %infohash=('resource.0.outtoken' => $token,
2707: 'resource.0.checkouttime' => $now,
2708: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 2709:
2710: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2711: return '';
1.151 www 2712: } else {
1.672 albertel 2713: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2714: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
2715: "</font>");
1.149 www 2716: }
2717:
2718: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2719: &escape('Checkout '.$infostr.' - '.
2720: $token)) ne 'ok') {
2721: return '';
1.151 www 2722: } else {
1.672 albertel 2723: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2724: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
2725: "</font>");
1.149 www 2726: }
1.151 www 2727: return $token;
1.149 www 2728: }
2729:
2730: # ------------------------------------------------------------ Check in an item
2731:
2732: sub checkin {
2733: my $token=shift;
1.150 www 2734: my $now=time;
2735: my ($ta,$tb,$lonhost)=split(/\*/,$token);
2736: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 2737: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 2738: $dtoken=~s/\W/\_/g;
1.234 www 2739: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 2740: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
2741:
1.154 www 2742: unless (($tuname) && ($tudom)) {
2743: &logthis('Check in '.$token.' ('.$dtoken.') failed');
2744: return '';
2745: }
2746:
2747: unless (&allowed('mgr',$tcrsid)) {
2748: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 2749: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 2750: return '';
2751: }
2752:
1.153 www 2753: my %infohash=('resource.0.intoken' => $token,
2754: 'resource.0.checkintime' => $now,
2755: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 2756:
2757: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2758: return '';
2759: }
2760:
2761: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2762: &escape('Checkin - '.$token)) ne 'ok') {
2763: return '';
2764: }
2765:
2766: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 2767: }
2768:
2769: # --------------------------------------------- Set Expire Date for Spreadsheet
2770:
2771: sub expirespread {
2772: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 2773: my $cid=$env{'request.course.id'};
1.110 www 2774: if ($cid) {
2775: my $now=time;
2776: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 2777: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
2778: $env{'course.'.$cid.'.num'}.
1.110 www 2779: ':nohist_expirationdates:'.
2780: &escape($key).'='.$now,
1.620 albertel 2781: $env{'course.'.$cid.'.home'})
1.110 www 2782: }
2783: return 'ok';
1.14 www 2784: }
2785:
1.109 www 2786: # ----------------------------------------------------- Devalidate Spreadsheets
2787:
2788: sub devalidate {
1.325 www 2789: my ($symb,$uname,$udom)=@_;
1.620 albertel 2790: my $cid=$env{'request.course.id'};
1.109 www 2791: if ($cid) {
1.391 matthew 2792: # delete the stored spreadsheets for
2793: # - the student level sheet of this user in course's homespace
2794: # - the assessment level sheet for this resource
2795: # for this user in user's homespace
1.553 albertel 2796: # - current conditional state info
1.325 www 2797: my $key=$uname.':'.$udom.':';
1.109 www 2798: my $status=
1.299 matthew 2799: &del('nohist_calculatedsheets',
1.391 matthew 2800: [$key.'studentcalc:'],
1.620 albertel 2801: $env{'course.'.$cid.'.domain'},
2802: $env{'course.'.$cid.'.num'})
1.133 albertel 2803: .' '.
2804: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 2805: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 2806: unless ($status eq 'ok ok') {
2807: &logthis('Could not devalidate spreadsheet '.
1.325 www 2808: $uname.' at '.$udom.' for '.
1.109 www 2809: $symb.': '.$status);
1.133 albertel 2810: }
1.553 albertel 2811: &delenv('user.state.'.$cid);
1.109 www 2812: }
2813: }
2814:
1.265 albertel 2815: sub get_scalar {
2816: my ($string,$end) = @_;
2817: my $value;
2818: if ($$string =~ s/^([^&]*?)($end)/$2/) {
2819: $value = $1;
2820: } elsif ($$string =~ s/^([^&]*?)&//) {
2821: $value = $1;
2822: }
2823: return &unescape($value);
2824: }
2825:
2826: sub array2str {
2827: my (@array) = @_;
2828: my $result=&arrayref2str(\@array);
2829: $result=~s/^__ARRAY_REF__//;
2830: $result=~s/__END_ARRAY_REF__$//;
2831: return $result;
2832: }
2833:
1.204 albertel 2834: sub arrayref2str {
2835: my ($arrayref) = @_;
1.265 albertel 2836: my $result='__ARRAY_REF__';
1.204 albertel 2837: foreach my $elem (@$arrayref) {
1.265 albertel 2838: if(ref($elem) eq 'ARRAY') {
2839: $result.=&arrayref2str($elem).'&';
2840: } elsif(ref($elem) eq 'HASH') {
2841: $result.=&hashref2str($elem).'&';
2842: } elsif(ref($elem)) {
2843: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 2844: } else {
2845: $result.=&escape($elem).'&';
2846: }
2847: }
2848: $result=~s/\&$//;
1.265 albertel 2849: $result .= '__END_ARRAY_REF__';
1.204 albertel 2850: return $result;
2851: }
2852:
1.168 albertel 2853: sub hash2str {
1.204 albertel 2854: my (%hash) = @_;
2855: my $result=&hashref2str(\%hash);
1.265 albertel 2856: $result=~s/^__HASH_REF__//;
2857: $result=~s/__END_HASH_REF__$//;
1.204 albertel 2858: return $result;
2859: }
2860:
2861: sub hashref2str {
2862: my ($hashref)=@_;
1.265 albertel 2863: my $result='__HASH_REF__';
1.800 albertel 2864: foreach my $key (sort(keys(%$hashref))) {
2865: if (ref($key) eq 'ARRAY') {
2866: $result.=&arrayref2str($key).'=';
2867: } elsif (ref($key) eq 'HASH') {
2868: $result.=&hashref2str($key).'=';
2869: } elsif (ref($key)) {
1.265 albertel 2870: $result.='=';
1.800 albertel 2871: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 2872: } else {
1.800 albertel 2873: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 2874: }
2875:
1.800 albertel 2876: if(ref($hashref->{$key}) eq 'ARRAY') {
2877: $result.=&arrayref2str($hashref->{$key}).'&';
2878: } elsif(ref($hashref->{$key}) eq 'HASH') {
2879: $result.=&hashref2str($hashref->{$key}).'&';
2880: } elsif(ref($hashref->{$key})) {
1.265 albertel 2881: $result.='&';
1.800 albertel 2882: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 2883: } else {
1.800 albertel 2884: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 2885: }
2886: }
1.168 albertel 2887: $result=~s/\&$//;
1.265 albertel 2888: $result .= '__END_HASH_REF__';
1.168 albertel 2889: return $result;
2890: }
2891:
2892: sub str2hash {
1.265 albertel 2893: my ($string)=@_;
2894: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
2895: return %$hash;
2896: }
2897:
2898: sub str2hashref {
1.168 albertel 2899: my ($string) = @_;
1.265 albertel 2900:
2901: my %hash;
2902:
2903: if($string !~ /^__HASH_REF__/) {
2904: if (! ($string eq '' || !defined($string))) {
2905: $hash{'error'}='Not hash reference';
2906: }
2907: return (\%hash, $string);
2908: }
2909:
2910: $string =~ s/^__HASH_REF__//;
2911:
2912: while($string !~ /^__END_HASH_REF__/) {
2913: #key
2914: my $key='';
2915: if($string =~ /^__HASH_REF__/) {
2916: ($key, $string)=&str2hashref($string);
2917: if(defined($key->{'error'})) {
2918: $hash{'error'}='Bad data';
2919: return (\%hash, $string);
2920: }
2921: } elsif($string =~ /^__ARRAY_REF__/) {
2922: ($key, $string)=&str2arrayref($string);
2923: if($key->[0] eq 'Array reference error') {
2924: $hash{'error'}='Bad data';
2925: return (\%hash, $string);
2926: }
2927: } else {
2928: $string =~ s/^(.*?)=//;
1.267 albertel 2929: $key=&unescape($1);
1.265 albertel 2930: }
2931: $string =~ s/^=//;
2932:
2933: #value
2934: my $value='';
2935: if($string =~ /^__HASH_REF__/) {
2936: ($value, $string)=&str2hashref($string);
2937: if(defined($value->{'error'})) {
2938: $hash{'error'}='Bad data';
2939: return (\%hash, $string);
2940: }
2941: } elsif($string =~ /^__ARRAY_REF__/) {
2942: ($value, $string)=&str2arrayref($string);
2943: if($value->[0] eq 'Array reference error') {
2944: $hash{'error'}='Bad data';
2945: return (\%hash, $string);
2946: }
2947: } else {
2948: $value=&get_scalar(\$string,'__END_HASH_REF__');
2949: }
2950: $string =~ s/^&//;
2951:
2952: $hash{$key}=$value;
1.204 albertel 2953: }
1.265 albertel 2954:
2955: $string =~ s/^__END_HASH_REF__//;
2956:
2957: return (\%hash, $string);
1.204 albertel 2958: }
2959:
2960: sub str2array {
1.265 albertel 2961: my ($string)=@_;
2962: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
2963: return @$array;
2964: }
2965:
2966: sub str2arrayref {
1.204 albertel 2967: my ($string) = @_;
1.265 albertel 2968: my @array;
2969:
2970: if($string !~ /^__ARRAY_REF__/) {
2971: if (! ($string eq '' || !defined($string))) {
2972: $array[0]='Array reference error';
2973: }
2974: return (\@array, $string);
2975: }
2976:
2977: $string =~ s/^__ARRAY_REF__//;
2978:
2979: while($string !~ /^__END_ARRAY_REF__/) {
2980: my $value='';
2981: if($string =~ /^__HASH_REF__/) {
2982: ($value, $string)=&str2hashref($string);
2983: if(defined($value->{'error'})) {
2984: $array[0] ='Array reference error';
2985: return (\@array, $string);
2986: }
2987: } elsif($string =~ /^__ARRAY_REF__/) {
2988: ($value, $string)=&str2arrayref($string);
2989: if($value->[0] eq 'Array reference error') {
2990: $array[0] ='Array reference error';
2991: return (\@array, $string);
2992: }
2993: } else {
2994: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
2995: }
2996: $string =~ s/^&//;
2997:
2998: push(@array, $value);
1.191 harris41 2999: }
1.265 albertel 3000:
3001: $string =~ s/^__END_ARRAY_REF__//;
3002:
3003: return (\@array, $string);
1.168 albertel 3004: }
3005:
1.167 albertel 3006: # -------------------------------------------------------------------Temp Store
3007:
1.168 albertel 3008: sub tmpreset {
3009: my ($symb,$namespace,$domain,$stuname) = @_;
3010: if (!$symb) {
3011: $symb=&symbread();
1.620 albertel 3012: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3013: }
3014: $symb=escape($symb);
3015:
1.620 albertel 3016: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3017: $namespace=~s/\//\_/g;
3018: $namespace=~s/\W//g;
3019:
1.620 albertel 3020: if (!$domain) { $domain=$env{'user.domain'}; }
3021: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3022: if ($domain eq 'public' && $stuname eq 'public') {
3023: $stuname=$ENV{'REMOTE_ADDR'};
3024: }
1.168 albertel 3025: my $path=$perlvar{'lonDaemons'}.'/tmp';
3026: my %hash;
3027: if (tie(%hash,'GDBM_File',
3028: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3029: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3030: foreach my $key (keys %hash) {
1.180 albertel 3031: if ($key=~ /:$symb/) {
1.168 albertel 3032: delete($hash{$key});
3033: }
3034: }
3035: }
3036: }
3037:
1.167 albertel 3038: sub tmpstore {
1.168 albertel 3039: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3040:
3041: if (!$symb) {
3042: $symb=&symbread();
1.620 albertel 3043: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3044: }
3045: $symb=escape($symb);
3046:
3047: if (!$namespace) {
3048: # I don't think we would ever want to store this for a course.
3049: # it seems this will only be used if we don't have a course.
1.620 albertel 3050: #$namespace=$env{'request.course.id'};
1.168 albertel 3051: #if (!$namespace) {
1.620 albertel 3052: $namespace=$env{'request.state'};
1.168 albertel 3053: #}
3054: }
3055: $namespace=~s/\//\_/g;
3056: $namespace=~s/\W//g;
1.620 albertel 3057: if (!$domain) { $domain=$env{'user.domain'}; }
3058: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3059: if ($domain eq 'public' && $stuname eq 'public') {
3060: $stuname=$ENV{'REMOTE_ADDR'};
3061: }
1.168 albertel 3062: my $now=time;
3063: my %hash;
3064: my $path=$perlvar{'lonDaemons'}.'/tmp';
3065: if (tie(%hash,'GDBM_File',
3066: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3067: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3068: $hash{"version:$symb"}++;
3069: my $version=$hash{"version:$symb"};
3070: my $allkeys='';
3071: foreach my $key (keys(%$storehash)) {
3072: $allkeys.=$key.':';
1.591 albertel 3073: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3074: }
3075: $hash{"$version:$symb:timestamp"}=$now;
3076: $allkeys.='timestamp';
3077: $hash{"$version:keys:$symb"}=$allkeys;
3078: if (untie(%hash)) {
3079: return 'ok';
3080: } else {
3081: return "error:$!";
3082: }
3083: } else {
3084: return "error:$!";
3085: }
3086: }
1.167 albertel 3087:
1.168 albertel 3088: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3089:
1.168 albertel 3090: sub tmprestore {
3091: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3092:
1.168 albertel 3093: if (!$symb) {
3094: $symb=&symbread();
1.620 albertel 3095: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3096: }
3097: $symb=escape($symb);
3098:
1.620 albertel 3099: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3100:
1.620 albertel 3101: if (!$domain) { $domain=$env{'user.domain'}; }
3102: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3103: if ($domain eq 'public' && $stuname eq 'public') {
3104: $stuname=$ENV{'REMOTE_ADDR'};
3105: }
1.168 albertel 3106: my %returnhash;
3107: $namespace=~s/\//\_/g;
3108: $namespace=~s/\W//g;
3109: my %hash;
3110: my $path=$perlvar{'lonDaemons'}.'/tmp';
3111: if (tie(%hash,'GDBM_File',
3112: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3113: &GDBM_READER(),0640)) {
1.168 albertel 3114: my $version=$hash{"version:$symb"};
3115: $returnhash{'version'}=$version;
3116: my $scope;
3117: for ($scope=1;$scope<=$version;$scope++) {
3118: my $vkeys=$hash{"$scope:keys:$symb"};
3119: my @keys=split(/:/,$vkeys);
3120: my $key;
3121: $returnhash{"$scope:keys"}=$vkeys;
3122: foreach $key (@keys) {
1.591 albertel 3123: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3124: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3125: }
3126: }
1.168 albertel 3127: if (!(untie(%hash))) {
3128: return "error:$!";
3129: }
3130: } else {
3131: return "error:$!";
3132: }
3133: return %returnhash;
1.167 albertel 3134: }
3135:
1.9 www 3136: # ----------------------------------------------------------------------- Store
3137:
3138: sub store {
1.124 www 3139: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3140: my $home='';
3141:
1.168 albertel 3142: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3143:
1.213 www 3144: $symb=&symbclean($symb);
1.122 albertel 3145: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3146:
1.620 albertel 3147: if (!$domain) { $domain=$env{'user.domain'}; }
3148: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3149:
3150: &devalidate($symb,$stuname,$domain);
1.109 www 3151:
3152: $symb=escape($symb);
1.187 www 3153: if (!$namespace) {
1.620 albertel 3154: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3155: return '';
3156: }
3157: }
1.620 albertel 3158: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3159:
3160: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3161: $$storehash{'host'}=$perlvar{'lonHostID'};
3162:
1.12 www 3163: my $namevalue='';
1.800 albertel 3164: foreach my $key (keys(%$storehash)) {
3165: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3166: }
1.12 www 3167: $namevalue=~s/\&$//;
1.187 www 3168: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3169: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3170: }
3171:
1.47 www 3172: # -------------------------------------------------------------- Critical Store
3173:
3174: sub cstore {
1.124 www 3175: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3176: my $home='';
3177:
1.168 albertel 3178: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3179:
1.213 www 3180: $symb=&symbclean($symb);
1.122 albertel 3181: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3182:
1.620 albertel 3183: if (!$domain) { $domain=$env{'user.domain'}; }
3184: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3185:
3186: &devalidate($symb,$stuname,$domain);
1.109 www 3187:
3188: $symb=escape($symb);
1.187 www 3189: if (!$namespace) {
1.620 albertel 3190: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3191: return '';
3192: }
3193: }
1.620 albertel 3194: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3195:
3196: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3197: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3198:
1.47 www 3199: my $namevalue='';
1.800 albertel 3200: foreach my $key (keys(%$storehash)) {
3201: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3202: }
1.47 www 3203: $namevalue=~s/\&$//;
1.187 www 3204: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3205: return critical
3206: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3207: }
3208:
1.9 www 3209: # --------------------------------------------------------------------- Restore
3210:
3211: sub restore {
1.124 www 3212: my ($symb,$namespace,$domain,$stuname) = @_;
3213: my $home='';
3214:
1.168 albertel 3215: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3216:
1.122 albertel 3217: if (!$symb) {
3218: unless ($symb=escape(&symbread())) { return ''; }
3219: } else {
1.213 www 3220: $symb=&escape(&symbclean($symb));
1.122 albertel 3221: }
1.188 www 3222: if (!$namespace) {
1.620 albertel 3223: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3224: return '';
3225: }
3226: }
1.620 albertel 3227: if (!$domain) { $domain=$env{'user.domain'}; }
3228: if (!$stuname) { $stuname=$env{'user.name'}; }
3229: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3230: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3231:
1.12 www 3232: my %returnhash=();
1.800 albertel 3233: foreach my $line (split(/\&/,$answer)) {
3234: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3235: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3236: }
1.75 www 3237: my $version;
3238: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3239: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3240: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3241: }
1.75 www 3242: }
1.13 www 3243: return %returnhash;
1.34 www 3244: }
3245:
3246: # ---------------------------------------------------------- Course Description
3247:
3248: sub coursedescription {
1.731 albertel 3249: my ($courseid,$args)=@_;
1.34 www 3250: $courseid=~s/^\///;
1.49 www 3251: $courseid=~s/\_/\//g;
1.34 www 3252: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3253: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3254: my $normalid=$cdomain.'_'.$cnum;
3255: # need to always cache even if we get errors otherwise we keep
3256: # trying and trying and trying to get the course description.
3257: my %envhash=();
3258: my %returnhash=();
1.731 albertel 3259:
3260: my $expiretime=600;
3261: if ($env{'request.course.id'} eq $normalid) {
3262: $expiretime=120;
3263: }
3264:
3265: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3266: if (!$args->{'freshen_cache'}
3267: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3268: foreach my $key (keys(%env)) {
3269: next if ($key !~ /^\Q$prefix\E(.*)/);
3270: my ($setting) = $1;
3271: $returnhash{$setting} = $env{$key};
3272: }
3273: return %returnhash;
3274: }
3275:
3276: # get the data agin
3277: if (!$args->{'one_time'}) {
3278: $envhash{'course.'.$normalid.'.last_cache'}=time;
3279: }
1.811 albertel 3280:
1.34 www 3281: if ($chome ne 'no_host') {
1.302 albertel 3282: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3283: if (!exists($returnhash{'con_lost'})) {
3284: $returnhash{'home'}= $chome;
3285: $returnhash{'domain'} = $cdomain;
3286: $returnhash{'num'} = $cnum;
1.741 raeburn 3287: if (!defined($returnhash{'type'})) {
3288: $returnhash{'type'} = 'Course';
3289: }
1.130 albertel 3290: while (my ($name,$value) = each %returnhash) {
1.53 www 3291: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3292: }
1.270 www 3293: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3294: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3295: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3296: $envhash{'course.'.$normalid.'.home'}=$chome;
3297: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3298: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3299: }
3300: }
1.731 albertel 3301: if (!$args->{'one_time'}) {
3302: &appenv(%envhash);
3303: }
1.302 albertel 3304: return %returnhash;
1.461 www 3305: }
3306:
3307: # -------------------------------------------------See if a user is privileged
3308:
3309: sub privileged {
3310: my ($username,$domain)=@_;
3311: my $rolesdump=&reply("dump:$domain:$username:roles",
3312: &homeserver($username,$domain));
3313: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
3314: my $now=time;
3315: if ($rolesdump ne '') {
1.800 albertel 3316: foreach my $entry (split(/&/,$rolesdump)) {
3317: if ($entry!~/^rolesdef_/) {
3318: my ($area,$role)=split(/=/,$entry);
1.461 www 3319: $area=~s/\_\w\w$//;
3320: my ($trole,$tend,$tstart)=split(/_/,$role);
3321: if (($trole eq 'dc') || ($trole eq 'su')) {
3322: my $active=1;
3323: if ($tend) {
3324: if ($tend<$now) { $active=0; }
3325: }
3326: if ($tstart) {
3327: if ($tstart>$now) { $active=0; }
3328: }
3329: if ($active) { return 1; }
3330: }
3331: }
3332: }
3333: }
3334: return 0;
1.9 www 3335: }
1.1 albertel 3336:
1.103 harris41 3337: # -------------------------------------------------------- Get user privileges
1.11 www 3338:
3339: sub rolesinit {
3340: my ($domain,$username,$authhost)=@_;
3341: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12 www 3342: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11 www 3343: my %allroles=();
1.678 raeburn 3344: my %allgroups=();
1.11 www 3345: my $now=time;
1.743 albertel 3346: my %userroles = ('user.login.time' => $now);
1.678 raeburn 3347: my $group_privs;
1.11 www 3348:
3349: if ($rolesdump ne '') {
1.800 albertel 3350: foreach my $entry (split(/&/,$rolesdump)) {
3351: if ($entry!~/^rolesdef_/) {
3352: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3353: $area=~s/\_\w\w$//;
1.678 raeburn 3354: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3355: if ($role=~/^cr/) {
1.807 albertel 3356: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3357: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3358: ($tend,$tstart)=split('_',$trest);
3359: } else {
3360: $trole=$role;
3361: }
1.678 raeburn 3362: } elsif ($role =~ m|^gr/|) {
3363: ($trole,$tend,$tstart) = split(/_/,$role);
3364: ($trole,$group_privs) = split(/\//,$trole);
3365: $group_privs = &unescape($group_privs);
1.587 albertel 3366: } else {
3367: ($trole,$tend,$tstart)=split(/_/,$role);
3368: }
1.743 albertel 3369: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3370: $username);
3371: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3372: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3373: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3374: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3375: my $spec=$trole.'.'.$area;
3376: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3377: if ($trole =~ /^cr\//) {
1.567 raeburn 3378: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3379: } elsif ($trole eq 'gr') {
3380: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3381: } else {
1.567 raeburn 3382: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3383: }
1.12 www 3384: }
1.662 raeburn 3385: }
1.191 harris41 3386: }
1.743 albertel 3387: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3388: $userroles{'user.adv'} = $adv;
3389: $userroles{'user.author'} = $author;
1.620 albertel 3390: $env{'user.adv'}=$adv;
1.11 www 3391: }
1.743 albertel 3392: return \%userroles;
1.11 www 3393: }
3394:
1.567 raeburn 3395: sub set_arearole {
3396: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3397: # log the associated role with the area
3398: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3399: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3400: }
3401:
3402: sub custom_roleprivs {
3403: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3404: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3405: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3406: if (&hostname($homsvr) ne '') {
1.567 raeburn 3407: my ($rdummy,$roledef)=
3408: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3409: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3410: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3411: if (defined($syspriv)) {
3412: $$allroles{'cm./'}.=':'.$syspriv;
3413: $$allroles{$spec.'./'}.=':'.$syspriv;
3414: }
3415: if ($tdomain ne '') {
3416: if (defined($dompriv)) {
3417: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3418: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3419: }
3420: if (($trest ne '') && (defined($coursepriv))) {
3421: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3422: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3423: }
3424: }
3425: }
3426: }
3427: }
3428:
1.678 raeburn 3429: sub group_roleprivs {
3430: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3431: my $access = 1;
3432: my $now = time;
3433: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3434: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3435: if ($access) {
1.811 albertel 3436: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3437: $$allgroups{$course}{$group} .=':'.$group_privs;
3438: }
3439: }
1.567 raeburn 3440:
3441: sub standard_roleprivs {
3442: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3443: if (defined($pr{$trole.':s'})) {
3444: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3445: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3446: }
3447: if ($tdomain ne '') {
3448: if (defined($pr{$trole.':d'})) {
3449: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3450: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3451: }
3452: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3453: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3454: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3455: }
3456: }
3457: }
3458:
3459: sub set_userprivs {
1.678 raeburn 3460: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 3461: my $author=0;
3462: my $adv=0;
1.678 raeburn 3463: my %grouproles = ();
3464: if (keys(%{$allgroups}) > 0) {
3465: foreach my $role (keys %{$allroles}) {
1.681 raeburn 3466: my ($trole,$area,$sec,$extendedarea);
1.881 raeburn 3467: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678 raeburn 3468: $trole = $1;
3469: $area = $2;
1.681 raeburn 3470: $sec = $3;
3471: $extendedarea = $area.$sec;
3472: if (exists($$allgroups{$area})) {
3473: foreach my $group (keys(%{$$allgroups{$area}})) {
3474: my $spec = $trole.'.'.$extendedarea;
3475: $grouproles{$spec.'.'.$area.'/'.$group} =
3476: $$allgroups{$area}{$group};
1.678 raeburn 3477: }
3478: }
3479: }
3480: }
3481: }
1.800 albertel 3482: foreach my $group (keys(%grouproles)) {
3483: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3484: }
1.800 albertel 3485: foreach my $role (keys(%{$allroles})) {
3486: my %thesepriv;
3487: if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
3488: foreach my $item (split(/:/,$$allroles{$role})) {
3489: if ($item ne '') {
3490: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3491: if ($restrictions eq '') {
3492: $thesepriv{$privilege}='F';
3493: } elsif ($thesepriv{$privilege} ne 'F') {
3494: $thesepriv{$privilege}.=$restrictions;
3495: }
3496: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3497: }
3498: }
3499: my $thesestr='';
1.800 albertel 3500: foreach my $priv (keys(%thesepriv)) {
3501: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3502: }
3503: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3504: }
3505: return ($author,$adv);
3506: }
3507:
1.12 www 3508: # --------------------------------------------------------------- get interface
3509:
3510: sub get {
1.131 albertel 3511: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3512: my $items='';
1.800 albertel 3513: foreach my $item (@$storearr) {
3514: $items.=&escape($item).'&';
1.191 harris41 3515: }
1.12 www 3516: $items=~s/\&$//;
1.620 albertel 3517: if (!$udomain) { $udomain=$env{'user.domain'}; }
3518: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 3519: my $uhome=&homeserver($uname,$udomain);
3520:
1.133 albertel 3521: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3522: my @pairs=split(/\&/,$rep);
1.273 albertel 3523: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
3524: return @pairs;
3525: }
1.15 www 3526: my %returnhash=();
1.42 www 3527: my $i=0;
1.800 albertel 3528: foreach my $item (@$storearr) {
3529: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3530: $i++;
1.191 harris41 3531: }
1.15 www 3532: return %returnhash;
1.27 www 3533: }
3534:
3535: # --------------------------------------------------------------- del interface
3536:
3537: sub del {
1.133 albertel 3538: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 3539: my $items='';
1.800 albertel 3540: foreach my $item (@$storearr) {
3541: $items.=&escape($item).'&';
1.191 harris41 3542: }
1.27 www 3543: $items=~s/\&$//;
1.620 albertel 3544: if (!$udomain) { $udomain=$env{'user.domain'}; }
3545: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3546: my $uhome=&homeserver($uname,$udomain);
3547:
3548: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3549: }
3550:
3551: # -------------------------------------------------------------- dump interface
3552:
3553: sub dump {
1.755 albertel 3554: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3555: if (!$udomain) { $udomain=$env{'user.domain'}; }
3556: if (!$uname) { $uname=$env{'user.name'}; }
3557: my $uhome=&homeserver($uname,$udomain);
3558: if ($regexp) {
3559: $regexp=&escape($regexp);
3560: } else {
3561: $regexp='.';
3562: }
3563: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3564: my @pairs=split(/\&/,$rep);
3565: my %returnhash=();
3566: foreach my $item (@pairs) {
3567: my ($key,$value)=split(/=/,$item,2);
3568: $key = &unescape($key);
3569: next if ($key =~ /^error: 2 /);
3570: $returnhash{$key}=&thaw_unescape($value);
3571: }
3572: return %returnhash;
1.407 www 3573: }
3574:
1.717 albertel 3575: # --------------------------------------------------------- dumpstore interface
3576:
3577: sub dumpstore {
3578: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 3579: if (!$udomain) { $udomain=$env{'user.domain'}; }
3580: if (!$uname) { $uname=$env{'user.name'}; }
3581: my $uhome=&homeserver($uname,$udomain);
3582: if ($regexp) {
3583: $regexp=&escape($regexp);
3584: } else {
3585: $regexp='.';
3586: }
3587: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3588: my @pairs=split(/\&/,$rep);
3589: my %returnhash=();
3590: foreach my $item (@pairs) {
3591: my ($key,$value)=split(/=/,$item,2);
3592: next if ($key =~ /^error: 2 /);
3593: $returnhash{$key}=&thaw_unescape($value);
3594: }
3595: return %returnhash;
1.717 albertel 3596: }
3597:
1.407 www 3598: # -------------------------------------------------------------- keys interface
3599:
3600: sub getkeys {
3601: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 3602: if (!$udomain) { $udomain=$env{'user.domain'}; }
3603: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 3604: my $uhome=&homeserver($uname,$udomain);
3605: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3606: my @keyarray=();
1.800 albertel 3607: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 3608: next if ($key =~ /^error: 2 /);
1.800 albertel 3609: push(@keyarray,&unescape($key));
1.407 www 3610: }
3611: return @keyarray;
1.318 matthew 3612: }
3613:
1.319 matthew 3614: # --------------------------------------------------------------- currentdump
3615: sub currentdump {
1.328 matthew 3616: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 3617: $courseid = $env{'request.course.id'} if (! defined($courseid));
3618: $sdom = $env{'user.domain'} if (! defined($sdom));
3619: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 3620: my $uhome = &homeserver($sname,$sdom);
3621: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 3622: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 3623: #
1.318 matthew 3624: my %returnhash=();
1.319 matthew 3625: #
3626: if ($rep eq "unknown_cmd") {
3627: # an old lond will not know currentdump
3628: # Do a dump and make it look like a currentdump
1.822 albertel 3629: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 3630: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3631: my %hash = @tmp;
3632: @tmp=();
1.424 matthew 3633: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 3634: } else {
3635: my @pairs=split(/\&/,$rep);
1.800 albertel 3636: foreach my $pair (@pairs) {
3637: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 3638: my ($symb,$param) = split(/:/,$key);
3639: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 3640: &thaw_unescape($value);
1.319 matthew 3641: }
1.191 harris41 3642: }
1.12 www 3643: return %returnhash;
1.424 matthew 3644: }
3645:
3646: sub convert_dump_to_currentdump{
3647: my %hash = %{shift()};
3648: my %returnhash;
3649: # Code ripped from lond, essentially. The only difference
3650: # here is the unescaping done by lonnet::dump(). Conceivably
3651: # we might run in to problems with parameter names =~ /^v\./
3652: while (my ($key,$value) = each(%hash)) {
3653: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 3654: $symb = &unescape($symb);
3655: $param = &unescape($param);
1.424 matthew 3656: next if ($v eq 'version' || $symb eq 'keys');
3657: next if (exists($returnhash{$symb}) &&
3658: exists($returnhash{$symb}->{$param}) &&
3659: $returnhash{$symb}->{'v.'.$param} > $v);
3660: $returnhash{$symb}->{$param}=$value;
3661: $returnhash{$symb}->{'v.'.$param}=$v;
3662: }
3663: #
3664: # Remove all of the keys in the hashes which keep track of
3665: # the version of the parameter.
3666: while (my ($symb,$param_hash) = each(%returnhash)) {
3667: # use a foreach because we are going to delete from the hash.
3668: foreach my $key (keys(%$param_hash)) {
3669: delete($param_hash->{$key}) if ($key =~ /^v\./);
3670: }
3671: }
3672: return \%returnhash;
1.12 www 3673: }
3674:
1.627 albertel 3675: # ------------------------------------------------------ critical inc interface
3676:
3677: sub cinc {
3678: return &inc(@_,'critical');
3679: }
3680:
1.449 matthew 3681: # --------------------------------------------------------------- inc interface
3682:
3683: sub inc {
1.627 albertel 3684: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 3685: if (!$udomain) { $udomain=$env{'user.domain'}; }
3686: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 3687: my $uhome=&homeserver($uname,$udomain);
3688: my $items='';
3689: if (! ref($store)) {
3690: # got a single value, so use that instead
3691: $items = &escape($store).'=&';
3692: } elsif (ref($store) eq 'SCALAR') {
3693: $items = &escape($$store).'=&';
3694: } elsif (ref($store) eq 'ARRAY') {
3695: $items = join('=&',map {&escape($_);} @{$store});
3696: } elsif (ref($store) eq 'HASH') {
3697: while (my($key,$value) = each(%{$store})) {
3698: $items.= &escape($key).'='.&escape($value).'&';
3699: }
3700: }
3701: $items=~s/\&$//;
1.627 albertel 3702: if ($critical) {
3703: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
3704: } else {
3705: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
3706: }
1.449 matthew 3707: }
3708:
1.12 www 3709: # --------------------------------------------------------------- put interface
3710:
3711: sub put {
1.134 albertel 3712: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3713: if (!$udomain) { $udomain=$env{'user.domain'}; }
3714: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3715: my $uhome=&homeserver($uname,$udomain);
1.12 www 3716: my $items='';
1.800 albertel 3717: foreach my $item (keys(%$storehash)) {
3718: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3719: }
1.12 www 3720: $items=~s/\&$//;
1.134 albertel 3721: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 3722: }
3723:
1.631 albertel 3724: # ------------------------------------------------------------ newput interface
3725:
3726: sub newput {
3727: my ($namespace,$storehash,$udomain,$uname)=@_;
3728: if (!$udomain) { $udomain=$env{'user.domain'}; }
3729: if (!$uname) { $uname=$env{'user.name'}; }
3730: my $uhome=&homeserver($uname,$udomain);
3731: my $items='';
3732: foreach my $key (keys(%$storehash)) {
3733: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3734: }
3735: $items=~s/\&$//;
3736: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
3737: }
3738:
3739: # --------------------------------------------------------- putstore interface
3740:
1.524 raeburn 3741: sub putstore {
1.715 albertel 3742: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 3743: if (!$udomain) { $udomain=$env{'user.domain'}; }
3744: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 3745: my $uhome=&homeserver($uname,$udomain);
3746: my $items='';
1.715 albertel 3747: foreach my $key (keys(%$storehash)) {
3748: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 3749: }
1.715 albertel 3750: $items=~s/\&$//;
1.716 albertel 3751: my $esc_symb=&escape($symb);
3752: my $esc_v=&escape($version);
1.715 albertel 3753: my $reply =
1.716 albertel 3754: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 3755: $uhome);
3756: if ($reply eq 'unknown_cmd') {
1.716 albertel 3757: # gfall back to way things use to be done
1.715 albertel 3758: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
3759: $uname);
1.524 raeburn 3760: }
1.715 albertel 3761: return $reply;
3762: }
3763:
3764: sub old_putstore {
1.716 albertel 3765: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3766: if (!$udomain) { $udomain=$env{'user.domain'}; }
3767: if (!$uname) { $uname=$env{'user.name'}; }
3768: my $uhome=&homeserver($uname,$udomain);
3769: my %newstorehash;
1.800 albertel 3770: foreach my $item (keys(%$storehash)) {
3771: my $key = $version.':'.&escape($symb).':'.$item;
3772: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 3773: }
3774: my $items='';
3775: my %allitems = ();
1.800 albertel 3776: foreach my $item (keys(%newstorehash)) {
3777: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 3778: my $key = $1.':keys:'.$2;
3779: $allitems{$key} .= $3.':';
3780: }
1.800 albertel 3781: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 3782: }
1.800 albertel 3783: foreach my $item (keys(%allitems)) {
3784: $allitems{$item} =~ s/\:$//;
3785: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 3786: }
3787: $items=~s/\&$//;
3788: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 3789: }
3790:
1.47 www 3791: # ------------------------------------------------------ critical put interface
3792:
3793: sub cput {
1.134 albertel 3794: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3795: if (!$udomain) { $udomain=$env{'user.domain'}; }
3796: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3797: my $uhome=&homeserver($uname,$udomain);
1.47 www 3798: my $items='';
1.800 albertel 3799: foreach my $item (keys(%$storehash)) {
3800: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3801: }
1.47 www 3802: $items=~s/\&$//;
1.134 albertel 3803: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3804: }
3805:
3806: # -------------------------------------------------------------- eget interface
3807:
3808: sub eget {
1.133 albertel 3809: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3810: my $items='';
1.800 albertel 3811: foreach my $item (@$storearr) {
3812: $items.=&escape($item).'&';
1.191 harris41 3813: }
1.12 www 3814: $items=~s/\&$//;
1.620 albertel 3815: if (!$udomain) { $udomain=$env{'user.domain'}; }
3816: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3817: my $uhome=&homeserver($uname,$udomain);
3818: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3819: my @pairs=split(/\&/,$rep);
3820: my %returnhash=();
1.42 www 3821: my $i=0;
1.800 albertel 3822: foreach my $item (@$storearr) {
3823: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3824: $i++;
1.191 harris41 3825: }
1.12 www 3826: return %returnhash;
3827: }
3828:
1.667 albertel 3829: # ------------------------------------------------------------ tmpput interface
3830: sub tmpput {
1.802 raeburn 3831: my ($storehash,$server,$context)=@_;
1.667 albertel 3832: my $items='';
1.800 albertel 3833: foreach my $item (keys(%$storehash)) {
3834: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 3835: }
3836: $items=~s/\&$//;
1.802 raeburn 3837: if (defined($context)) {
3838: $items .= ':'.&escape($context);
3839: }
1.667 albertel 3840: return &reply("tmpput:$items",$server);
3841: }
3842:
3843: # ------------------------------------------------------------ tmpget interface
3844: sub tmpget {
1.688 albertel 3845: my ($token,$server)=@_;
3846: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3847: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 3848: my %returnhash;
3849: foreach my $item (split(/\&/,$rep)) {
3850: my ($key,$value)=split(/=/,$item);
3851: $returnhash{&unescape($key)}=&thaw_unescape($value);
3852: }
3853: return %returnhash;
3854: }
3855:
1.688 albertel 3856: # ------------------------------------------------------------ tmpget interface
3857: sub tmpdel {
3858: my ($token,$server)=@_;
3859: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3860: return &reply("tmpdel:$token",$server);
3861: }
3862:
1.765 albertel 3863: # -------------------------------------------------- portfolio access checking
3864:
3865: sub portfolio_access {
1.766 albertel 3866: my ($requrl) = @_;
1.765 albertel 3867: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
3868: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 3869: if ($result) {
3870: my %setters;
3871: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3872: my ($startblock,$endblock) =
3873: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
3874: if ($startblock && $endblock) {
3875: return 'B';
3876: }
3877: } else {
3878: my ($startblock,$endblock) =
3879: &Apache::loncommon::blockcheck(\%setters,'port');
3880: if ($startblock && $endblock) {
3881: return 'B';
3882: }
3883: }
3884: }
1.765 albertel 3885: if ($result eq 'ok') {
1.766 albertel 3886: return 'F';
1.765 albertel 3887: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 3888: return 'A';
1.765 albertel 3889: }
1.766 albertel 3890: return '';
1.765 albertel 3891: }
3892:
3893: sub get_portfolio_access {
1.767 albertel 3894: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
3895:
3896: if (!ref($access_hash)) {
3897: my $current_perms = &get_portfile_permissions($udom,$unum);
3898: my %access_controls = &get_access_controls($current_perms,$group,
3899: $file_name);
3900: $access_hash = $access_controls{$file_name};
3901: }
3902:
1.765 albertel 3903: my ($public,$guest,@domains,@users,@courses,@groups);
3904: my $now = time;
3905: if (ref($access_hash) eq 'HASH') {
3906: foreach my $key (keys(%{$access_hash})) {
3907: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
3908: if ($start > $now) {
3909: next;
3910: }
3911: if ($end && $end<$now) {
3912: next;
3913: }
3914: if ($scope eq 'public') {
3915: $public = $key;
3916: last;
3917: } elsif ($scope eq 'guest') {
3918: $guest = $key;
3919: } elsif ($scope eq 'domains') {
3920: push(@domains,$key);
3921: } elsif ($scope eq 'users') {
3922: push(@users,$key);
3923: } elsif ($scope eq 'course') {
3924: push(@courses,$key);
3925: } elsif ($scope eq 'group') {
3926: push(@groups,$key);
3927: }
3928: }
3929: if ($public) {
3930: return 'ok';
3931: }
3932: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3933: if ($guest) {
3934: return $guest;
3935: }
3936: } else {
3937: if (@domains > 0) {
3938: foreach my $domkey (@domains) {
3939: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
3940: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
3941: return 'ok';
3942: }
3943: }
3944: }
3945: }
3946: if (@users > 0) {
3947: foreach my $userkey (@users) {
1.865 raeburn 3948: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
3949: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
3950: if (ref($item) eq 'HASH') {
3951: if (($item->{'uname'} eq $env{'user.name'}) &&
3952: ($item->{'udom'} eq $env{'user.domain'})) {
3953: return 'ok';
3954: }
3955: }
3956: }
3957: }
1.765 albertel 3958: }
3959: }
3960: my %roleshash;
3961: my @courses_and_groups = @courses;
3962: push(@courses_and_groups,@groups);
3963: if (@courses_and_groups > 0) {
3964: my (%allgroups,%allroles);
3965: my ($start,$end,$role,$sec,$group);
3966: foreach my $envkey (%env) {
1.811 albertel 3967: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 3968: my $cid = $2.'_'.$3;
3969: if ($1 eq 'gr') {
3970: $group = $4;
3971: $allgroups{$cid}{$group} = $env{$envkey};
3972: } else {
3973: if ($4 eq '') {
3974: $sec = 'none';
3975: } else {
3976: $sec = $4;
3977: }
3978: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3979: }
1.811 albertel 3980: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 3981: my $cid = $2.'_'.$3;
3982: if ($4 eq '') {
3983: $sec = 'none';
3984: } else {
3985: $sec = $4;
3986: }
3987: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3988: }
3989: }
3990: if (keys(%allroles) == 0) {
3991: return;
3992: }
3993: foreach my $key (@courses_and_groups) {
3994: my %content = %{$$access_hash{$key}};
3995: my $cnum = $content{'number'};
3996: my $cdom = $content{'domain'};
3997: my $cid = $cdom.'_'.$cnum;
3998: if (!exists($allroles{$cid})) {
3999: next;
4000: }
4001: foreach my $role_id (keys(%{$content{'roles'}})) {
4002: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4003: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4004: my @status = @{$content{'roles'}{$role_id}{'access'}};
4005: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4006: foreach my $role (keys(%{$allroles{$cid}})) {
4007: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4008: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4009: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4010: if (grep/^all$/,@sections) {
4011: return 'ok';
4012: } else {
4013: if (grep/^$sec$/,@sections) {
4014: return 'ok';
4015: }
4016: }
4017: }
4018: }
4019: if (keys(%{$allgroups{$cid}}) == 0) {
4020: if (grep/^none$/,@groups) {
4021: return 'ok';
4022: }
4023: } else {
4024: if (grep/^all$/,@groups) {
4025: return 'ok';
4026: }
4027: foreach my $group (keys(%{$allgroups{$cid}})) {
4028: if (grep/^$group$/,@groups) {
4029: return 'ok';
4030: }
4031: }
4032: }
4033: }
4034: }
4035: }
4036: }
4037: }
4038: if ($guest) {
4039: return $guest;
4040: }
4041: }
4042: }
4043: return;
4044: }
4045:
4046: sub course_group_datechecker {
4047: my ($dates,$now,$status) = @_;
4048: my ($start,$end) = split(/\./,$dates);
4049: if (!$start && !$end) {
4050: return 'ok';
4051: }
4052: if (grep/^active$/,@{$status}) {
4053: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4054: return 'ok';
4055: }
4056: }
4057: if (grep/^previous$/,@{$status}) {
4058: if ($end > $now ) {
4059: return 'ok';
4060: }
4061: }
4062: if (grep/^future$/,@{$status}) {
4063: if ($start > $now) {
4064: return 'ok';
4065: }
4066: }
4067: return;
4068: }
4069:
4070: sub parse_portfolio_url {
4071: my ($url) = @_;
4072:
4073: my ($type,$udom,$unum,$group,$file_name);
4074:
1.823 albertel 4075: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4076: $type = 1;
4077: $udom = $1;
4078: $unum = $2;
4079: $file_name = $3;
1.823 albertel 4080: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4081: $type = 2;
4082: $udom = $1;
4083: $unum = $2;
4084: $group = $3;
4085: $file_name = $3.'/'.$4;
4086: }
4087: if (wantarray) {
4088: return ($type,$udom,$unum,$file_name,$group);
4089: }
4090: return $type;
4091: }
4092:
4093: sub is_portfolio_url {
4094: my ($url) = @_;
4095: return scalar(&parse_portfolio_url($url));
4096: }
4097:
1.798 raeburn 4098: sub is_portfolio_file {
4099: my ($file) = @_;
1.820 raeburn 4100: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4101: return 1;
4102: }
4103: return;
4104: }
4105:
4106:
1.341 www 4107: # ---------------------------------------------- Custom access rule evaluation
4108:
4109: sub customaccess {
4110: my ($priv,$uri)=@_;
1.807 albertel 4111: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 4112: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 4113: $udom = &LONCAPA::clean_domain($udom);
4114: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 4115: my $access=0;
1.800 albertel 4116: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 4117: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4118: if ($type eq 'user') {
4119: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 4120: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 4121: if ($tdom) {
4122: if ($tdom ne $env{'user.domain'}) { next; }
4123: }
1.896 albertel 4124: if ($tuname) {
4125: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 4126: }
4127: $access=($effect eq 'allow');
4128: last;
4129: }
4130: } else {
4131: if ($role) {
4132: if ($role ne $urole) { next; }
4133: }
4134: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4135: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4136: if ($tdom) {
4137: if ($tdom ne $udom) { next; }
4138: }
4139: if ($tcrs) {
4140: if ($tcrs ne $ucrs) { next; }
4141: }
4142: if ($tsec) {
4143: if ($tsec ne $usec) { next; }
4144: }
4145: $access=($effect eq 'allow');
4146: last;
4147: }
4148: if ($realm eq '' && $role eq '') {
4149: $access=($effect eq 'allow');
4150: }
1.402 bowersj2 4151: }
1.341 www 4152: }
4153: return $access;
4154: }
4155:
1.103 harris41 4156: # ------------------------------------------------- Check for a user privilege
1.12 www 4157:
4158: sub allowed {
1.810 raeburn 4159: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 4160: my $ver_orguri=$uri;
1.439 www 4161: $uri=&deversion($uri);
1.152 www 4162: my $orguri=$uri;
1.52 www 4163: $uri=&declutter($uri);
1.809 raeburn 4164:
1.810 raeburn 4165: if ($priv eq 'evb') {
4166: # Evade communication block restrictions for specified role in a course
4167: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4168: return $1;
4169: } else {
4170: return;
4171: }
4172: }
4173:
1.620 albertel 4174: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 4175: # Free bre access to adm and meta resources
1.775 albertel 4176: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 4177: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4178: && ($priv eq 'bre')) {
1.14 www 4179: return 'F';
1.159 www 4180: }
4181:
1.545 banghart 4182: # Free bre access to user's own portfolio contents
1.714 raeburn 4183: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 4184: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 4185: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 4186: my %setters;
4187: my ($startblock,$endblock) =
4188: &Apache::loncommon::blockcheck(\%setters,'port');
4189: if ($startblock && $endblock) {
4190: return 'B';
4191: } else {
4192: return 'F';
4193: }
1.545 banghart 4194: }
4195:
1.762 raeburn 4196: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 4197: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
4198: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
4199: if (exists($env{'request.course.id'})) {
4200: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4201: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4202: if (($domain eq $cdom) && ($name eq $cnum)) {
4203: my $courseprivid=$env{'request.course.id'};
4204: $courseprivid=~s/\_/\//;
4205: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
4206: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
4207: return $1;
1.762 raeburn 4208: } else {
4209: if ($env{'request.course.sec'}) {
4210: $courseprivid.='/'.$env{'request.course.sec'};
4211: }
4212: if ($env{'user.priv.'.$env{'request.role'}.'./'.
4213: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
4214: return $2;
4215: }
1.714 raeburn 4216: }
4217: }
4218: }
4219: }
4220:
1.159 www 4221: # Free bre to public access
4222:
4223: if ($priv eq 'bre') {
1.238 www 4224: my $copyright=&metadata($uri,'copyright');
1.620 albertel 4225: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 4226: return 'F';
4227: }
1.238 www 4228: if ($copyright eq 'priv') {
4229: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4230: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 4231: return '';
4232: }
4233: }
4234: if ($copyright eq 'domain') {
4235: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4236: unless (($env{'user.domain'} eq $1) ||
4237: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 4238: return '';
4239: }
1.262 matthew 4240: }
1.620 albertel 4241: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 4242: # Library role, so allow browsing of resources in this domain.
4243: return 'F';
1.238 www 4244: }
1.341 www 4245: if ($copyright eq 'custom') {
4246: unless (&customaccess($priv,$uri)) { return ''; }
4247: }
1.14 www 4248: }
1.264 matthew 4249: # Domain coordinator is trying to create a course
1.620 albertel 4250: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 4251: # uri is the requested domain in this case.
4252: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 4253: # a role of dc for the domain in question.
1.620 albertel 4254: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 4255: }
1.29 www 4256:
1.52 www 4257: my $thisallowed='';
4258: my $statecond=0;
4259: my $courseprivid='';
4260:
4261: # Course
4262:
1.620 albertel 4263: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4264: $thisallowed.=$1;
4265: }
1.29 www 4266:
1.52 www 4267: # Domain
4268:
1.620 albertel 4269: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 4270: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4271: $thisallowed.=$1;
4272: }
1.52 www 4273:
4274: # Course: uri itself is a course
1.66 www 4275: my $courseuri=$uri;
4276: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 4277: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 4278:
1.620 albertel 4279: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 4280: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4281: $thisallowed.=$1;
4282: }
1.29 www 4283:
1.665 albertel 4284: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 4285: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 4286: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 4287: $thisallowed='';
1.671 raeburn 4288: my ($match)=&is_on_map($uri);
4289: if ($match) {
4290: if ($env{'user.priv.'.$env{'request.role'}.'./'}
4291: =~/\Q$priv\E\&([^\:]*)/) {
4292: $thisallowed.=$1;
4293: }
4294: } else {
1.705 albertel 4295: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 4296: if ($refuri) {
4297: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 4298: $thisallowed='F';
1.671 raeburn 4299: } else {
4300: $refuri=&declutter($refuri);
4301: my ($match) = &is_on_map($refuri);
4302: if ($match) {
4303: $thisallowed='F';
4304: }
1.669 raeburn 4305: }
1.671 raeburn 4306: }
4307: }
1.314 www 4308: }
1.492 albertel 4309:
1.766 albertel 4310: if ($priv eq 'bre'
4311: && $thisallowed ne 'F'
4312: && $thisallowed ne '2'
4313: && &is_portfolio_url($uri)) {
4314: $thisallowed = &portfolio_access($uri);
4315: }
4316:
1.52 www 4317: # Full access at system, domain or course-wide level? Exit.
1.29 www 4318:
4319: if ($thisallowed=~/F/) {
4320: return 'F';
4321: }
4322:
1.52 www 4323: # If this is generating or modifying users, exit with special codes
1.29 www 4324:
1.643 www 4325: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
4326: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 4327: my ($audom,$auname)=split('/',$uri);
1.643 www 4328: # no author name given, so this just checks on the general right to make a co-author in this domain
4329: unless ($auname) { return $thisallowed; }
4330: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 4331: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
4332: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
4333: ($audom ne $env{'request.role.domain'}))) { return ''; }
4334: }
1.52 www 4335: return $thisallowed;
4336: }
4337: #
1.103 harris41 4338: # Gathered so far: system, domain and course wide privileges
1.52 www 4339: #
4340: # Course: See if uri or referer is an individual resource that is part of
4341: # the course
4342:
1.620 albertel 4343: if ($env{'request.course.id'}) {
1.232 www 4344:
1.620 albertel 4345: $courseprivid=$env{'request.course.id'};
4346: if ($env{'request.course.sec'}) {
4347: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 4348: }
4349: $courseprivid=~s/\_/\//;
4350: my $checkreferer=1;
1.232 www 4351: my ($match,$cond)=&is_on_map($uri);
4352: if ($match) {
4353: $statecond=$cond;
1.620 albertel 4354: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4355: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4356: $thisallowed.=$1;
4357: $checkreferer=0;
4358: }
1.29 www 4359: }
1.83 www 4360:
1.148 www 4361: if ($checkreferer) {
1.620 albertel 4362: my $refuri=$env{'httpref.'.$orguri};
1.148 www 4363: unless ($refuri) {
1.800 albertel 4364: foreach my $key (keys(%env)) {
4365: if ($key=~/^httpref\..*\*/) {
4366: my $pattern=$key;
1.156 www 4367: $pattern=~s/^httpref\.\/res\///;
1.148 www 4368: $pattern=~s/\*/\[\^\/\]\+/g;
4369: $pattern=~s/\//\\\//g;
1.152 www 4370: if ($orguri=~/$pattern/) {
1.800 albertel 4371: $refuri=$env{$key};
1.148 www 4372: }
4373: }
1.191 harris41 4374: }
1.148 www 4375: }
1.232 www 4376:
1.148 www 4377: if ($refuri) {
1.152 www 4378: $refuri=&declutter($refuri);
1.232 www 4379: my ($match,$cond)=&is_on_map($refuri);
4380: if ($match) {
4381: my $refstatecond=$cond;
1.620 albertel 4382: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4383: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4384: $thisallowed.=$1;
1.53 www 4385: $uri=$refuri;
4386: $statecond=$refstatecond;
1.52 www 4387: }
4388: }
1.148 www 4389: }
1.29 www 4390: }
1.52 www 4391: }
1.29 www 4392:
1.52 www 4393: #
1.103 harris41 4394: # Gathered now: all privileges that could apply, and condition number
1.52 www 4395: #
4396: #
4397: # Full or no access?
4398: #
1.29 www 4399:
1.52 www 4400: if ($thisallowed=~/F/) {
4401: return 'F';
4402: }
1.29 www 4403:
1.52 www 4404: unless ($thisallowed) {
4405: return '';
4406: }
1.29 www 4407:
1.52 www 4408: # Restrictions exist, deal with them
4409: #
4410: # C:according to course preferences
4411: # R:according to resource settings
4412: # L:unless locked
4413: # X:according to user session state
4414: #
4415:
4416: # Possibly locked functionality, check all courses
1.54 www 4417: # Locks might take effect only after 10 minutes cache expiration for other
4418: # courses, and 2 minutes for current course
1.52 www 4419:
4420: my $envkey;
4421: if ($thisallowed=~/L/) {
1.620 albertel 4422: foreach $envkey (keys %env) {
1.54 www 4423: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
4424: my $courseid=$2;
4425: my $roleid=$1.'.'.$2;
1.92 www 4426: $courseid=~s/^\///;
1.54 www 4427: my $expiretime=600;
1.620 albertel 4428: if ($env{'request.role'} eq $roleid) {
1.54 www 4429: $expiretime=120;
4430: }
4431: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
4432: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 4433: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 4434: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 4435: }
1.620 albertel 4436: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
4437: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
4438: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
4439: &log($env{'user.domain'},$env{'user.name'},
4440: $env{'user.home'},
1.57 www 4441: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 4442: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4443: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4444: return '';
4445: }
4446: }
1.620 albertel 4447: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
4448: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
4449: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
4450: &log($env{'user.domain'},$env{'user.name'},
4451: $env{'user.home'},
1.57 www 4452: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 4453: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4454: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4455: return '';
4456: }
4457: }
4458: }
1.29 www 4459: }
1.52 www 4460: }
4461:
4462: #
4463: # Rest of the restrictions depend on selected course
4464: #
4465:
1.620 albertel 4466: unless ($env{'request.course.id'}) {
1.766 albertel 4467: if ($thisallowed eq 'A') {
4468: return 'A';
1.814 raeburn 4469: } elsif ($thisallowed eq 'B') {
4470: return 'B';
1.766 albertel 4471: } else {
4472: return '1';
4473: }
1.52 www 4474: }
1.29 www 4475:
1.52 www 4476: #
4477: # Now user is definitely in a course
4478: #
1.53 www 4479:
4480:
4481: # Course preferences
4482:
4483: if ($thisallowed=~/C/) {
1.620 albertel 4484: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4485: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
4486: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 4487: =~/\Q$rolecode\E/) {
1.689 albertel 4488: if ($priv ne 'pch') {
4489: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4490: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
4491: $env{'request.course.id'});
4492: }
1.237 www 4493: return '';
4494: }
4495:
1.620 albertel 4496: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 4497: =~/\Q$unamedom\E/) {
1.689 albertel 4498: if ($priv ne 'pch') {
4499: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
4500: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
4501: $env{'request.course.id'});
4502: }
1.54 www 4503: return '';
4504: }
1.53 www 4505: }
4506:
4507: # Resource preferences
4508:
4509: if ($thisallowed=~/R/) {
1.620 albertel 4510: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 4511: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 4512: if ($priv ne 'pch') {
4513: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4514: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
4515: }
4516: return '';
1.54 www 4517: }
1.53 www 4518: }
1.30 www 4519:
1.246 www 4520: # Restricted by state or randomout?
1.30 www 4521:
1.52 www 4522: if ($thisallowed=~/X/) {
1.620 albertel 4523: if ($env{'acc.randomout'}) {
1.579 albertel 4524: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 4525: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 4526: return '';
4527: }
1.247 www 4528: }
4529: if (&condval($statecond)) {
1.52 www 4530: return '2';
4531: } else {
4532: return '';
4533: }
4534: }
1.30 www 4535:
1.766 albertel 4536: if ($thisallowed eq 'A') {
4537: return 'A';
1.814 raeburn 4538: } elsif ($thisallowed eq 'B') {
4539: return 'B';
1.766 albertel 4540: }
1.52 www 4541: return 'F';
1.232 www 4542: }
4543:
1.710 albertel 4544: sub split_uri_for_cond {
4545: my $uri=&deversion(&declutter(shift));
4546: my @uriparts=split(/\//,$uri);
4547: my $filename=pop(@uriparts);
4548: my $pathname=join('/',@uriparts);
4549: return ($pathname,$filename);
4550: }
1.232 www 4551: # --------------------------------------------------- Is a resource on the map?
4552:
4553: sub is_on_map {
1.710 albertel 4554: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 4555: #Trying to find the conditional for the file
1.620 albertel 4556: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 4557: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 4558: if ($match) {
1.289 bowersj2 4559: return (1,$1);
4560: } else {
1.434 www 4561: return (0,0);
1.289 bowersj2 4562: }
1.12 www 4563: }
4564:
1.427 www 4565: # --------------------------------------------------------- Get symb from alias
4566:
4567: sub get_symb_from_alias {
4568: my $symb=shift;
4569: my ($map,$resid,$url)=&decode_symb($symb);
4570: # Already is a symb
4571: if ($url) { return $symb; }
4572: # Must be an alias
4573: my $aliassymb='';
4574: my %bighash;
1.620 albertel 4575: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 4576: &GDBM_READER(),0640)) {
4577: my $rid=$bighash{'mapalias_'.$symb};
4578: if ($rid) {
4579: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 4580: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
4581: $resid,$bighash{'src_'.$rid});
1.427 www 4582: }
4583: untie %bighash;
4584: }
4585: return $aliassymb;
4586: }
4587:
1.12 www 4588: # ----------------------------------------------------------------- Define Role
4589:
4590: sub definerole {
4591: if (allowed('mcr','/')) {
4592: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 4593: foreach my $role (split(':',$sysrole)) {
4594: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4595: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
4596: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
4597: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4598: return "refused:s:$crole&$cqual";
4599: }
4600: }
1.191 harris41 4601: }
1.800 albertel 4602: foreach my $role (split(':',$domrole)) {
4603: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4604: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
4605: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
4606: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 4607: return "refused:d:$crole&$cqual";
4608: }
4609: }
1.191 harris41 4610: }
1.800 albertel 4611: foreach my $role (split(':',$courole)) {
4612: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4613: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
4614: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
4615: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4616: return "refused:c:$crole&$cqual";
4617: }
4618: }
1.191 harris41 4619: }
1.620 albertel 4620: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4621: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 4622: "rolesdef_$rolename=".
4623: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 4624: return reply($command,$env{'user.home'});
1.12 www 4625: } else {
4626: return 'refused';
4627: }
1.105 harris41 4628: }
4629:
4630: # ---------------- Make a metadata query against the network of library servers
4631:
4632: sub metadata_query {
1.244 matthew 4633: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 4634: my %rhash;
1.845 albertel 4635: my %libserv = &all_library();
1.244 matthew 4636: my @server_list = (defined($server_array) ? @$server_array
4637: : keys(%libserv) );
4638: for my $server (@server_list) {
1.118 harris41 4639: unless ($custom or $customshow) {
4640: my $reply=&reply("querysend:".&escape($query),$server);
4641: $rhash{$server}=$reply;
4642: }
4643: else {
4644: my $reply=&reply("querysend:".&escape($query).':'.
4645: &escape($custom).':'.&escape($customshow),
4646: $server);
4647: $rhash{$server}=$reply;
4648: }
1.112 harris41 4649: }
1.118 harris41 4650: return \%rhash;
1.240 www 4651: }
4652:
4653: # ----------------------------------------- Send log queries and wait for reply
4654:
4655: sub log_query {
4656: my ($uname,$udom,$query,%filters)=@_;
4657: my $uhome=&homeserver($uname,$udom);
4658: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 4659: my $uhost=&hostname($uhome);
1.800 albertel 4660: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 4661: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
4662: $uhome);
1.479 albertel 4663: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 4664: return get_query_reply($queryid);
4665: }
4666:
1.818 raeburn 4667: # -------------------------- Update MySQL table for portfolio file
4668:
4669: sub update_portfolio_table {
1.821 raeburn 4670: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818 raeburn 4671: my $homeserver = &homeserver($uname,$udom);
4672: my $queryid=
1.821 raeburn 4673: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
4674: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 4675: my $reply = &get_query_reply($queryid);
4676: return $reply;
4677: }
4678:
1.899 raeburn 4679: # -------------------------- Update MySQL allusers table
4680:
4681: sub update_allusers_table {
4682: my ($uname,$udom,$names) = @_;
4683: my $homeserver = &homeserver($uname,$udom);
4684: my $queryid=
4685: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
4686: 'lastname='.&escape($names->{'lastname'}).'%%'.
4687: 'firstname='.&escape($names->{'firstname'}).'%%'.
4688: 'middlename='.&escape($names->{'middlename'}).'%%'.
4689: 'generation='.&escape($names->{'generation'}).'%%'.
4690: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
4691: 'id='.&escape($names->{'id'}),$homeserver);
4692: my $reply = &get_query_reply($queryid);
4693: return $reply;
4694: }
4695:
1.508 raeburn 4696: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 4697:
4698: sub fetch_enrollment_query {
1.511 raeburn 4699: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 4700: my $homeserver;
1.547 raeburn 4701: my $maxtries = 1;
1.508 raeburn 4702: if ($context eq 'automated') {
4703: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 4704: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 4705: } else {
4706: $homeserver = &homeserver($cnum,$dom);
4707: }
1.838 albertel 4708: my $host=&hostname($homeserver);
1.506 raeburn 4709: my $cmd = '';
1.800 albertel 4710: foreach my $affiliate (keys %{$affiliatesref}) {
4711: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 4712: }
4713: $cmd =~ s/%%$//;
4714: $cmd = &escape($cmd);
4715: my $query = 'fetchenrollment';
1.620 albertel 4716: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 4717: unless ($queryid=~/^\Q$host\E\_/) {
4718: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
4719: return 'error: '.$queryid;
4720: }
1.506 raeburn 4721: my $reply = &get_query_reply($queryid);
1.547 raeburn 4722: my $tries = 1;
4723: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4724: $reply = &get_query_reply($queryid);
4725: $tries ++;
4726: }
1.526 raeburn 4727: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 4728: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 4729: } else {
1.901 albertel 4730: my @responses = split(/:/,$reply);
1.515 raeburn 4731: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 4732: foreach my $line (@responses) {
4733: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 4734: $$replyref{$key} = $value;
4735: }
4736: } else {
1.506 raeburn 4737: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 4738: foreach my $line (@responses) {
4739: my ($key,$value) = split(/=/,$line);
1.506 raeburn 4740: $$replyref{$key} = $value;
4741: if ($value > 0) {
1.800 albertel 4742: foreach my $item (@{$$affiliatesref{$key}}) {
4743: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 4744: my $destname = $pathname.'/'.$filename;
4745: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 4746: if ($xml_classlist =~ /^error/) {
4747: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
4748: } else {
1.506 raeburn 4749: if ( open(FILE,">$destname") ) {
4750: print FILE &unescape($xml_classlist);
4751: close(FILE);
1.526 raeburn 4752: } else {
4753: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 4754: }
4755: }
4756: }
4757: }
4758: }
4759: }
4760: return 'ok';
4761: }
4762: return 'error';
4763: }
4764:
1.242 www 4765: sub get_query_reply {
4766: my $queryid=shift;
1.240 www 4767: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
4768: my $reply='';
4769: for (1..100) {
4770: sleep 2;
4771: if (-e $replyfile.'.end') {
1.448 albertel 4772: if (open(my $fh,$replyfile)) {
1.904 albertel 4773: $reply = join('',<$fh>);
4774: close($fh);
1.240 www 4775: } else { return 'error: reply_file_error'; }
1.242 www 4776: return &unescape($reply);
4777: }
1.240 www 4778: }
1.242 www 4779: return 'timeout:'.$queryid;
1.240 www 4780: }
4781:
4782: sub courselog_query {
1.241 www 4783: #
4784: # possible filters:
4785: # url: url or symb
4786: # username
4787: # domain
4788: # action: view, submit, grade
4789: # start: timestamp
4790: # end: timestamp
4791: #
1.240 www 4792: my (%filters)=@_;
1.620 albertel 4793: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 4794: if ($filters{'url'}) {
4795: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
4796: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
4797: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
4798: }
1.620 albertel 4799: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4800: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 4801: return &log_query($cname,$cdom,'courselog',%filters);
4802: }
4803:
4804: sub userlog_query {
1.858 raeburn 4805: #
4806: # possible filters:
4807: # action: log check role
4808: # start: timestamp
4809: # end: timestamp
4810: #
1.240 www 4811: my ($uname,$udom,%filters)=@_;
4812: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 4813: }
4814:
1.506 raeburn 4815: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
4816:
4817: sub auto_run {
1.508 raeburn 4818: my ($cnum,$cdom) = @_;
1.876 raeburn 4819: my $response = 0;
4820: my $settings;
4821: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
4822: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
4823: $settings = $domconfig{'autoenroll'};
4824: if ($settings->{'run'} eq '1') {
4825: $response = 1;
4826: }
4827: } else {
4828: my $homeserver = &homeserver($cnum,$cdom);
4829: $response = &reply('autorun:'.$cdom,$homeserver);
4830: }
1.506 raeburn 4831: return $response;
4832: }
1.776 albertel 4833:
1.506 raeburn 4834: sub auto_get_sections {
1.508 raeburn 4835: my ($cnum,$cdom,$inst_coursecode) = @_;
4836: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 4837: my @secs = ();
1.511 raeburn 4838: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 4839: unless ($response eq 'refused') {
1.901 albertel 4840: @secs = split(/:/,$response);
1.506 raeburn 4841: }
4842: return @secs;
4843: }
1.776 albertel 4844:
1.506 raeburn 4845: sub auto_new_course {
1.508 raeburn 4846: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
4847: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 4848: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 4849: return $response;
4850: }
1.776 albertel 4851:
1.506 raeburn 4852: sub auto_validate_courseID {
1.508 raeburn 4853: my ($cnum,$cdom,$inst_course_id) = @_;
4854: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 4855: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 4856: return $response;
4857: }
1.776 albertel 4858:
1.506 raeburn 4859: sub auto_create_password {
1.873 raeburn 4860: my ($cnum,$cdom,$authparam,$udom) = @_;
4861: my ($homeserver,$response);
1.506 raeburn 4862: my $create_passwd = 0;
4863: my $authchk = '';
1.873 raeburn 4864: if ($udom =~ /^$match_domain$/) {
4865: $homeserver = &domain($udom,'primary');
4866: }
4867: if ($homeserver eq '') {
4868: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
4869: $homeserver = &homeserver($cnum,$cdom);
4870: }
4871: }
4872: if ($homeserver eq '') {
4873: $authchk = 'nodomain';
1.506 raeburn 4874: } else {
1.873 raeburn 4875: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
4876: if ($response eq 'refused') {
4877: $authchk = 'refused';
4878: } else {
1.901 albertel 4879: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 4880: }
1.506 raeburn 4881: }
4882: return ($authparam,$create_passwd,$authchk);
4883: }
4884:
1.706 raeburn 4885: sub auto_photo_permission {
4886: my ($cnum,$cdom,$students) = @_;
4887: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 4888: my ($outcome,$perm_reqd,$conditions) =
4889: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 4890: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4891: return (undef,undef);
4892: }
1.706 raeburn 4893: return ($outcome,$perm_reqd,$conditions);
4894: }
4895:
4896: sub auto_checkphotos {
4897: my ($uname,$udom,$pid) = @_;
4898: my $homeserver = &homeserver($uname,$udom);
4899: my ($result,$resulttype);
4900: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 4901: &escape($uname).':'.&escape($pid),
4902: $homeserver));
1.709 albertel 4903: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4904: return (undef,undef);
4905: }
1.706 raeburn 4906: if ($outcome) {
4907: ($result,$resulttype) = split(/:/,$outcome);
4908: }
4909: return ($result,$resulttype);
4910: }
4911:
4912: sub auto_photochoice {
4913: my ($cnum,$cdom) = @_;
4914: my $homeserver = &homeserver($cnum,$cdom);
4915: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 4916: &escape($cdom),
4917: $homeserver)));
1.709 albertel 4918: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4919: return (undef,undef);
4920: }
1.706 raeburn 4921: return ($update,$comment);
4922: }
4923:
4924: sub auto_photoupdate {
4925: my ($affiliatesref,$dom,$cnum,$photo) = @_;
4926: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 4927: my $host=&hostname($homeserver);
1.706 raeburn 4928: my $cmd = '';
4929: my $maxtries = 1;
1.800 albertel 4930: foreach my $affiliate (keys(%{$affiliatesref})) {
4931: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 4932: }
4933: $cmd =~ s/%%$//;
4934: $cmd = &escape($cmd);
4935: my $query = 'institutionalphotos';
4936: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
4937: unless ($queryid=~/^\Q$host\E\_/) {
4938: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
4939: return 'error: '.$queryid;
4940: }
4941: my $reply = &get_query_reply($queryid);
4942: my $tries = 1;
4943: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4944: $reply = &get_query_reply($queryid);
4945: $tries ++;
4946: }
4947: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
4948: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
4949: } else {
4950: my @responses = split(/:/,$reply);
4951: my $outcome = shift(@responses);
4952: foreach my $item (@responses) {
4953: my ($key,$value) = split(/=/,$item);
4954: $$photo{$key} = $value;
4955: }
4956: return $outcome;
4957: }
4958: return 'error';
4959: }
4960:
1.521 raeburn 4961: sub auto_instcode_format {
1.793 albertel 4962: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
4963: $cat_order) = @_;
1.521 raeburn 4964: my $courses = '';
1.772 raeburn 4965: my @homeservers;
1.521 raeburn 4966: if ($caller eq 'global') {
1.841 albertel 4967: my %servers = &get_servers($codedom,'library');
4968: foreach my $tryserver (keys(%servers)) {
4969: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4970: push(@homeservers,$tryserver);
4971: }
1.584 raeburn 4972: }
1.521 raeburn 4973: } else {
1.772 raeburn 4974: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 4975: }
1.793 albertel 4976: foreach my $code (keys(%{$instcodes})) {
4977: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 4978: }
4979: chop($courses);
1.772 raeburn 4980: my $ok_response = 0;
4981: my $response;
4982: while (@homeservers > 0 && $ok_response == 0) {
4983: my $server = shift(@homeservers);
4984: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
4985: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
4986: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 4987: split(/:/,$response);
1.772 raeburn 4988: %{$codes} = (%{$codes},&str2hash($codes_str));
4989: push(@{$codetitles},&str2array($codetitles_str));
4990: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
4991: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
4992: $ok_response = 1;
4993: }
4994: }
4995: if ($ok_response) {
1.521 raeburn 4996: return 'ok';
1.772 raeburn 4997: } else {
4998: return $response;
1.521 raeburn 4999: }
5000: }
5001:
1.792 raeburn 5002: sub auto_instcode_defaults {
5003: my ($domain,$returnhash,$code_order) = @_;
5004: my @homeservers;
1.841 albertel 5005:
5006: my %servers = &get_servers($domain,'library');
5007: foreach my $tryserver (keys(%servers)) {
5008: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5009: push(@homeservers,$tryserver);
5010: }
1.792 raeburn 5011: }
1.841 albertel 5012:
1.792 raeburn 5013: my $response;
1.841 albertel 5014: foreach my $server (@homeservers) {
1.792 raeburn 5015: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 5016: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5017:
5018: foreach my $pair (split(/\&/,$response)) {
5019: my ($name,$value)=split(/\=/,$pair);
5020: if ($name eq 'code_order') {
5021: @{$code_order} = split(/\&/,&unescape($value));
5022: } else {
5023: $returnhash->{&unescape($name)}=&unescape($value);
5024: }
5025: }
5026: return 'ok';
1.792 raeburn 5027: }
1.841 albertel 5028:
5029: return $response;
1.792 raeburn 5030: }
5031:
1.777 albertel 5032: sub auto_validate_class_sec {
1.918 raeburn 5033: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 5034: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 5035: my $ownerlist;
5036: if (ref($owners) eq 'ARRAY') {
5037: $ownerlist = join(',',@{$owners});
5038: } else {
5039: $ownerlist = $owners;
5040: }
1.773 raeburn 5041: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 5042: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 5043: return $response;
5044: }
5045:
1.679 raeburn 5046: # ------------------------------------------------------- Course Group routines
5047:
5048: sub get_coursegroups {
1.809 raeburn 5049: my ($cdom,$cnum,$group,$namespace) = @_;
5050: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 5051: }
5052:
1.679 raeburn 5053: sub modify_coursegroup {
5054: my ($cdom,$cnum,$groupsettings) = @_;
5055: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
5056: }
5057:
1.809 raeburn 5058: sub toggle_coursegroup_status {
5059: my ($cdom,$cnum,$group,$action) = @_;
5060: my ($from_namespace,$to_namespace);
5061: if ($action eq 'delete') {
5062: $from_namespace = 'coursegroups';
5063: $to_namespace = 'deleted_groups';
5064: } else {
5065: $from_namespace = 'deleted_groups';
5066: $to_namespace = 'coursegroups';
5067: }
5068: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 5069: if (my $tmp = &error(%curr_group)) {
5070: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
5071: return ('read error',$tmp);
5072: } else {
5073: my %savedsettings = %curr_group;
1.809 raeburn 5074: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 5075: my $deloutcome;
5076: if ($result eq 'ok') {
1.809 raeburn 5077: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 5078: } else {
5079: return ('write error',$result);
5080: }
5081: if ($deloutcome eq 'ok') {
5082: return 'ok';
5083: } else {
5084: return ('delete error',$deloutcome);
5085: }
5086: }
5087: }
5088:
1.679 raeburn 5089: sub modify_group_roles {
5090: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
5091: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
5092: my $role = 'gr/'.&escape($userprivs);
5093: my ($uname,$udom) = split(/:/,$user);
5094: my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684 raeburn 5095: if ($result eq 'ok') {
5096: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
5097: }
1.679 raeburn 5098: return $result;
5099: }
5100:
5101: sub modify_coursegroup_membership {
5102: my ($cdom,$cnum,$membership) = @_;
5103: my $result = &put('groupmembership',$membership,$cdom,$cnum);
5104: return $result;
5105: }
5106:
1.682 raeburn 5107: sub get_active_groups {
5108: my ($udom,$uname,$cdom,$cnum) = @_;
5109: my $now = time;
5110: my %groups = ();
5111: foreach my $key (keys(%env)) {
1.811 albertel 5112: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 5113: my ($start,$end) = split(/\./,$env{$key});
5114: if (($end!=0) && ($end<$now)) { next; }
5115: if (($start!=0) && ($start>$now)) { next; }
5116: if ($1 eq $cdom && $2 eq $cnum) {
5117: $groups{$3} = $env{$key} ;
5118: }
5119: }
5120: }
5121: return %groups;
5122: }
5123:
1.683 raeburn 5124: sub get_group_membership {
5125: my ($cdom,$cnum,$group) = @_;
5126: return(&dump('groupmembership',$cdom,$cnum,$group));
5127: }
5128:
5129: sub get_users_groups {
5130: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 5131: my @usersgroups;
1.683 raeburn 5132: my $cachetime=1800;
5133:
5134: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 5135: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
5136: if (defined($cached)) {
1.734 albertel 5137: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 5138: } else {
5139: $grouplist = '';
1.816 raeburn 5140: my $courseurl = &courseid_to_courseurl($courseid);
5141: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 5142: my $access_end = $env{'course.'.$courseid.
5143: '.default_enrollment_end_date'};
5144: my $now = time;
5145: foreach my $key (keys(%roleshash)) {
5146: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
5147: my $group = $1;
5148: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
5149: my $start = $2;
5150: my $end = $1;
5151: if ($start == -1) { next; } # deleted from group
5152: if (($start!=0) && ($start>$now)) { next; }
5153: if (($end!=0) && ($end<$now)) {
5154: if ($access_end && $access_end < $now) {
5155: if ($access_end - $end < 86400) {
5156: push(@usersgroups,$group);
1.733 raeburn 5157: }
5158: }
1.817 raeburn 5159: next;
1.733 raeburn 5160: }
1.817 raeburn 5161: push(@usersgroups,$group);
1.683 raeburn 5162: }
5163: }
5164: }
1.817 raeburn 5165: @usersgroups = &sort_course_groups($courseid,@usersgroups);
5166: $grouplist = join(':',@usersgroups);
5167: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 5168: }
1.733 raeburn 5169: return @usersgroups;
1.683 raeburn 5170: }
5171:
5172: sub devalidate_getgroups_cache {
5173: my ($udom,$uname,$cdom,$cnum)=@_;
5174: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 5175:
1.683 raeburn 5176: my $hashid="$udom:$uname:$courseid";
5177: &devalidate_cache_new('getgroups',$hashid);
5178: }
5179:
1.12 www 5180: # ------------------------------------------------------------------ Plain Text
5181:
5182: sub plaintext {
1.742 raeburn 5183: my ($short,$type,$cid) = @_;
1.758 albertel 5184: if ($short =~ /^cr/) {
5185: return (split('/',$short))[-1];
5186: }
1.742 raeburn 5187: if (!defined($cid)) {
5188: $cid = $env{'request.course.id'};
5189: }
5190: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
5191: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
5192: '.plaintext'});
5193: }
5194: my %rolenames = (
5195: Course => 'std',
5196: Group => 'alt1',
5197: );
5198: if (defined($type) &&
5199: defined($rolenames{$type}) &&
5200: defined($prp{$short}{$rolenames{$type}})) {
5201: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
5202: } else {
5203: return &Apache::lonlocal::mt($prp{$short}{'std'});
5204: }
1.12 www 5205: }
5206:
5207: # ----------------------------------------------------------------- Assign Role
5208:
5209: sub assignrole {
1.357 www 5210: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21 www 5211: my $mrole;
5212: if ($role =~ /^cr\//) {
1.393 www 5213: my $cwosec=$url;
1.811 albertel 5214: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 5215: unless (&allowed('ccr',$cwosec)) {
1.104 www 5216: &logthis('Refused custom assignrole: '.
5217: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 5218: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 5219: return 'refused';
5220: }
1.21 www 5221: $mrole='cr';
1.678 raeburn 5222: } elsif ($role =~ /^gr\//) {
5223: my $cwogrp=$url;
1.811 albertel 5224: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 5225: unless (&allowed('mdg',$cwogrp)) {
5226: &logthis('Refused group assignrole: '.
5227: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
5228: $env{'user.name'}.' at '.$env{'user.domain'});
5229: return 'refused';
5230: }
5231: $mrole='gr';
1.21 www 5232: } else {
1.82 www 5233: my $cwosec=$url;
1.811 albertel 5234: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373 www 5235: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
1.104 www 5236: &logthis('Refused assignrole: '.
5237: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 5238: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 5239: return 'refused';
5240: }
1.21 www 5241: $mrole=$role;
5242: }
1.620 albertel 5243: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5244: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 5245: if ($end) { $command.='_'.$end; }
1.21 www 5246: if ($start) {
5247: if ($end) {
1.81 www 5248: $command.='_'.$start;
1.21 www 5249: } else {
1.81 www 5250: $command.='_0_'.$start;
1.21 www 5251: }
5252: }
1.739 raeburn 5253: my $origstart = $start;
5254: my $origend = $end;
1.357 www 5255: # actually delete
5256: if ($deleteflag) {
1.373 www 5257: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 5258: # modify command to delete the role
1.620 albertel 5259: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 5260: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 5261: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 5262: # set start and finish to negative values for userrolelog
5263: $start=-1;
5264: $end=-1;
5265: }
5266: }
5267: # send command
1.349 www 5268: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 5269: # log new user role if status is ok
1.349 www 5270: if ($answer eq 'ok') {
1.663 raeburn 5271: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 5272: # for course roles, perform group memberships changes triggered by role change.
5273: unless ($role =~ /^gr/) {
5274: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
5275: $origstart);
5276: }
1.349 www 5277: }
5278: return $answer;
1.169 harris41 5279: }
5280:
5281: # -------------------------------------------------- Modify user authentication
1.197 www 5282: # Overrides without validation
5283:
1.169 harris41 5284: sub modifyuserauth {
5285: my ($udom,$uname,$umode,$upass)=@_;
5286: my $uhome=&homeserver($uname,$udom);
1.197 www 5287: unless (&allowed('mau',$udom)) { return 'refused'; }
5288: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 5289: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5290: ' in domain '.$env{'request.role.domain'});
1.169 harris41 5291: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
5292: &escape($upass),$uhome);
1.620 albertel 5293: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 5294: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
5295: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
5296: &log($udom,,$uname,$uhome,
1.620 albertel 5297: 'Authentication changed by '.$env{'user.domain'}.', '.
5298: $env{'user.name'}.', '.$umode.
1.197 www 5299: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 5300: unless ($reply eq 'ok') {
1.197 www 5301: &logthis('Authentication mode error: '.$reply);
1.169 harris41 5302: return 'error: '.$reply;
5303: }
1.170 harris41 5304: return 'ok';
1.80 www 5305: }
5306:
1.81 www 5307: # --------------------------------------------------------------- Modify a user
1.80 www 5308:
1.81 www 5309: sub modifyuser {
1.206 matthew 5310: my ($udom, $uname, $uid,
5311: $umode, $upass, $first,
5312: $middle, $last, $gene,
1.387 www 5313: $forceid, $desiredhome, $email)=@_;
1.807 albertel 5314: $udom= &LONCAPA::clean_domain($udom);
5315: $uname=&LONCAPA::clean_username($uname);
1.81 www 5316: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 5317: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 5318: $last.', '.$gene.'(forceid: '.$forceid.')'.
5319: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
5320: ' desiredhome not specified').
1.620 albertel 5321: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5322: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 5323: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 5324: # ----------------------------------------------------------------- Create User
1.406 albertel 5325: if (($uhome eq 'no_host') &&
5326: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 5327: my $unhome='';
1.844 albertel 5328: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 5329: $unhome = $desiredhome;
1.620 albertel 5330: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
5331: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 5332: } else { # load balancing routine for determining $unhome
1.81 www 5333: my $loadm=10000000;
1.841 albertel 5334: my %servers = &get_servers($udom,'library');
5335: foreach my $tryserver (keys(%servers)) {
5336: my $answer=reply('load',$tryserver);
5337: if (($answer=~/\d+/) && ($answer<$loadm)) {
5338: $loadm=$answer;
5339: $unhome=$tryserver;
5340: }
1.80 www 5341: }
5342: }
5343: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 5344: return 'error: unable to find a home server for '.$uname.
5345: ' in domain '.$udom;
1.80 www 5346: }
5347: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
5348: &escape($upass),$unhome);
5349: unless ($reply eq 'ok') {
5350: return 'error: '.$reply;
5351: }
1.230 stredwic 5352: $uhome=&homeserver($uname,$udom,'true');
1.80 www 5353: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 5354: return 'error: unable verify users home machine.';
1.80 www 5355: }
1.209 matthew 5356: } # End of creation of new user
1.80 www 5357: # ---------------------------------------------------------------------- Add ID
5358: if ($uid) {
5359: $uid=~tr/A-Z/a-z/;
5360: my %uidhash=&idrget($udom,$uname);
1.196 www 5361: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
5362: && (!$forceid)) {
1.80 www 5363: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 5364: return 'error: user id "'.$uid.'" does not match '.
5365: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 5366: }
5367: } else {
5368: &idput($udom,($uname => $uid));
5369: }
5370: }
5371: # -------------------------------------------------------------- Add names, etc
1.313 matthew 5372: my @tmp=&get('environment',
1.899 raeburn 5373: ['firstname','middlename','lastname','generation','id',
5374: 'permanentemail'],
1.134 albertel 5375: $udom,$uname);
1.313 matthew 5376: my %names;
5377: if ($tmp[0] =~ m/^error:.*/) {
5378: %names=();
5379: } else {
5380: %names = @tmp;
5381: }
1.388 www 5382: #
5383: # Make sure to not trash student environment if instructor does not bother
5384: # to supply name and email information
5385: #
5386: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 5387: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 5388: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 5389: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 5390: if ($email) {
5391: $email=~s/[^\w\@\.\-\,]//gs;
5392: if ($email=~/\@/) { $names{'notification'} = $email;
5393: $names{'critnotification'} = $email;
5394: $names{'permanentemail'} = $email; }
5395: }
1.899 raeburn 5396: if ($uid) { $names{'id'} = $uid; }
1.134 albertel 5397: my $reply = &put('environment', \%names, $udom,$uname);
5398: if ($reply ne 'ok') { return 'error: '.$reply; }
1.899 raeburn 5399: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680 www 5400: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81 www 5401: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 5402: $umode.', '.$first.', '.$middle.', '.
5403: $last.', '.$gene.' by '.
1.620 albertel 5404: $env{'user.name'}.' at '.$env{'user.domain'});
1.134 albertel 5405: return 'ok';
1.80 www 5406: }
5407:
1.81 www 5408: # -------------------------------------------------------------- Modify student
1.80 www 5409:
1.81 www 5410: sub modifystudent {
5411: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515 raeburn 5412: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455 albertel 5413: if (!$cid) {
1.620 albertel 5414: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5415: return 'not_in_class';
5416: }
1.80 www 5417: }
5418: # --------------------------------------------------------------- Make the user
1.81 www 5419: my $reply=&modifyuser
1.209 matthew 5420: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 5421: $desiredhome,$email);
1.80 www 5422: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 5423: # This will cause &modify_student_enrollment to get the uid from the
5424: # students environment
5425: $uid = undef if (!$forceid);
1.455 albertel 5426: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515 raeburn 5427: $gene,$usec,$end,$start,$type,$locktype,$cid);
1.297 matthew 5428: return $reply;
5429: }
5430:
5431: sub modify_student_enrollment {
1.515 raeburn 5432: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455 albertel 5433: my ($cdom,$cnum,$chome);
5434: if (!$cid) {
1.620 albertel 5435: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5436: return 'not_in_class';
5437: }
1.620 albertel 5438: $cdom=$env{'course.'.$cid.'.domain'};
5439: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 5440: } else {
5441: ($cdom,$cnum)=split(/_/,$cid);
5442: }
1.620 albertel 5443: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 5444: if (!$chome) {
1.457 raeburn 5445: $chome=&homeserver($cnum,$cdom);
1.297 matthew 5446: }
1.455 albertel 5447: if (!$chome) { return 'unknown_course'; }
1.297 matthew 5448: # Make sure the user exists
1.81 www 5449: my $uhome=&homeserver($uname,$udom);
5450: if (($uhome eq '') || ($uhome eq 'no_host')) {
5451: return 'error: no such user';
5452: }
1.297 matthew 5453: # Get student data if we were not given enough information
5454: if (!defined($first) || $first eq '' ||
5455: !defined($last) || $last eq '' ||
5456: !defined($uid) || $uid eq '' ||
5457: !defined($middle) || $middle eq '' ||
5458: !defined($gene) || $gene eq '') {
1.294 matthew 5459: # They did not supply us with enough data to enroll the student, so
5460: # we need to pick up more information.
1.297 matthew 5461: my %tmp = &get('environment',
1.294 matthew 5462: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 5463: ,$udom,$uname);
5464:
1.800 albertel 5465: #foreach my $key (keys(%tmp)) {
5466: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 5467: #}
1.294 matthew 5468: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
5469: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
5470: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 5471: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 5472: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
5473: }
1.556 albertel 5474: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 5475: my $reply=cput('classlist',
5476: {"$uname:$udom" =>
1.515 raeburn 5477: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 5478: $cdom,$cnum);
1.81 www 5479: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
5480: return 'error: '.$reply;
1.652 albertel 5481: } else {
5482: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 5483: }
1.297 matthew 5484: # Add student role to user
1.83 www 5485: my $uurl='/'.$cid;
1.81 www 5486: $uurl=~s/\_/\//g;
5487: if ($usec) {
5488: $uurl.='/'.$usec;
5489: }
5490: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21 www 5491: }
5492:
1.556 albertel 5493: sub format_name {
5494: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
5495: my $name;
5496: if ($first ne 'lastname') {
5497: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
5498: } else {
5499: if ($lastname=~/\S/) {
5500: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
5501: $name=~s/\s+,/,/;
5502: } else {
5503: $name.= $firstname.' '.$middlename.' '.$generation;
5504: }
5505: }
5506: $name=~s/^\s+//;
5507: $name=~s/\s+$//;
5508: $name=~s/\s+/ /g;
5509: return $name;
5510: }
5511:
1.84 www 5512: # ------------------------------------------------- Write to course preferences
5513:
5514: sub writecoursepref {
5515: my ($courseid,%prefs)=@_;
5516: $courseid=~s/^\///;
5517: $courseid=~s/\_/\//g;
5518: my ($cdomain,$cnum)=split(/\//,$courseid);
5519: my $chome=homeserver($cnum,$cdomain);
5520: if (($chome eq '') || ($chome eq 'no_host')) {
5521: return 'error: no such course';
5522: }
5523: my $cstring='';
1.800 albertel 5524: foreach my $pref (keys(%prefs)) {
5525: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 5526: }
1.84 www 5527: $cstring=~s/\&$//;
5528: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
5529: }
5530:
5531: # ---------------------------------------------------------- Make/modify course
5532:
5533: sub createcourse {
1.741 raeburn 5534: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
5535: $course_owner,$crstype)=@_;
1.84 www 5536: $url=&declutter($url);
5537: my $cid='';
1.264 matthew 5538: unless (&allowed('ccc',$udom)) {
1.84 www 5539: return 'refused';
5540: }
5541: # ------------------------------------------------------------------- Create ID
1.674 www 5542: my $uname=int(1+rand(9)).
5543: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
5544: substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84 www 5545: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
5546: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 5547: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 5548: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5549: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
5550: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 5551: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5552: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5553: return 'error: unable to generate unique course-ID';
5554: }
5555: }
1.264 matthew 5556: # ------------------------------------------------ Check supplied server name
1.620 albertel 5557: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845 albertel 5558: if (! &is_library($course_server)) {
1.264 matthew 5559: return 'error:bad server name '.$course_server;
5560: }
1.84 www 5561: # ------------------------------------------------------------- Make the course
5562: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 5563: $course_server);
1.84 www 5564: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 5565: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5566: if (($uhome eq '') || ($uhome eq 'no_host')) {
5567: return 'error: no such course';
5568: }
1.271 www 5569: # ----------------------------------------------------------------- Course made
1.516 raeburn 5570: # log existence
1.918 raeburn 5571: my $newcourse = {
5572: $udom.'_'.$uname => {
1.921 raeburn 5573: description => $description,
5574: inst_code => $inst_code,
5575: owner => $course_owner,
5576: type => $crstype,
1.918 raeburn 5577: },
5578: };
1.921 raeburn 5579: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 5580: # set toplevel url
1.271 www 5581: my $topurl=$url;
5582: unless ($nonstandard) {
5583: # ------------------------------------------ For standard courses, make top url
5584: my $mapurl=&clutter($url);
1.278 www 5585: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 5586: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 5587: <map>
5588: <resource id="1" type="start"></resource>
5589: <resource id="2" src="$mapurl"></resource>
5590: <resource id="3" type="finish"></resource>
5591: <link index="1" from="1" to="2"></link>
5592: <link index="2" from="2" to="3"></link>
5593: </map>
5594: ENDINITMAP
5595: $topurl=&declutter(
1.638 albertel 5596: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 5597: );
5598: }
5599: # ----------------------------------------------------------- Write preferences
1.84 www 5600: &writecoursepref($udom.'_'.$uname,
5601: ('description' => $description,
1.271 www 5602: 'url' => $topurl));
1.84 www 5603: return '/'.$udom.'/'.$uname;
5604: }
5605:
1.813 albertel 5606: sub is_course {
5607: my ($cdom,$cnum) = @_;
5608: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.918 raeburn 5609: undef,'.',undef,1);
1.813 albertel 5610: if (exists($courses{$cdom.'_'.$cnum})) {
5611: return 1;
5612: }
5613: return 0;
5614: }
5615:
1.21 www 5616: # ---------------------------------------------------------- Assign Custom Role
5617:
5618: sub assigncustomrole {
1.357 www 5619: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21 www 5620: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357 www 5621: $end,$start,$deleteflag);
1.21 www 5622: }
5623:
5624: # ----------------------------------------------------------------- Revoke Role
5625:
5626: sub revokerole {
1.357 www 5627: my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21 www 5628: my $now=time;
1.357 www 5629: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21 www 5630: }
5631:
5632: # ---------------------------------------------------------- Revoke Custom Role
5633:
5634: sub revokecustomrole {
1.357 www 5635: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21 www 5636: my $now=time;
1.357 www 5637: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
5638: $deleteflag);
1.17 www 5639: }
5640:
1.533 banghart 5641: # ------------------------------------------------------------ Disk usage
1.535 albertel 5642: sub diskusage {
1.533 banghart 5643: my ($udom,$uname,$directoryRoot)=@_;
5644: $directoryRoot =~ s/\/$//;
1.535 albertel 5645: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514 albertel 5646: return $listing;
1.512 banghart 5647: }
5648:
1.566 banghart 5649: sub is_locked {
5650: my ($file_name, $domain, $user) = @_;
5651: my @check;
5652: my $is_locked;
5653: push @check, $file_name;
1.613 albertel 5654: my %locked = &get('file_permissions',\@check,
1.620 albertel 5655: $env{'user.domain'},$env{'user.name'});
1.615 albertel 5656: my ($tmp)=keys(%locked);
5657: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 5658:
1.566 banghart 5659: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 5660: $is_locked = 'false';
5661: foreach my $entry (@{$locked{$file_name}}) {
5662: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 5663: $is_locked = 'true';
5664: last;
1.745 raeburn 5665: }
5666: }
1.566 banghart 5667: } else {
5668: $is_locked = 'false';
5669: }
5670: }
5671:
1.759 albertel 5672: sub declutter_portfile {
5673: my ($file) = @_;
1.833 albertel 5674: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 5675: return $file;
5676: }
5677:
1.559 banghart 5678: # ------------------------------------------------------------- Mark as Read Only
5679:
5680: sub mark_as_readonly {
5681: my ($domain,$user,$files,$what) = @_;
1.613 albertel 5682: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5683: my ($tmp)=keys(%current_permissions);
5684: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 5685: foreach my $file (@{$files}) {
1.759 albertel 5686: $file = &declutter_portfile($file);
1.561 banghart 5687: push(@{$current_permissions{$file}},$what);
1.559 banghart 5688: }
1.613 albertel 5689: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 5690: return;
5691: }
5692:
1.572 banghart 5693: # ------------------------------------------------------------Save Selected Files
5694:
5695: sub save_selected_files {
5696: my ($user, $path, @files) = @_;
5697: my $filename = $user."savedfiles";
1.573 banghart 5698: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 5699: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 5700: foreach my $file (@files) {
1.620 albertel 5701: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 5702: }
5703: foreach my $file (@other_files) {
1.574 banghart 5704: print (OUT $file."\n");
1.572 banghart 5705: }
1.574 banghart 5706: close (OUT);
1.572 banghart 5707: return 'ok';
5708: }
5709:
1.574 banghart 5710: sub clear_selected_files {
5711: my ($user) = @_;
5712: my $filename = $user."savedfiles";
5713: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5714: print (OUT undef);
5715: close (OUT);
5716: return ("ok");
5717: }
5718:
1.572 banghart 5719: sub files_in_path {
5720: my ($user, $path) = @_;
5721: my $filename = $user."savedfiles";
5722: my %return_files;
1.574 banghart 5723: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 5724: while (my $line_in = <IN>) {
1.574 banghart 5725: chomp ($line_in);
5726: my @paths_and_file = split (m!/!, $line_in);
5727: my $file_part = pop (@paths_and_file);
5728: my $path_part = join ('/', @paths_and_file);
1.573 banghart 5729: $path_part.='/';
5730: my $path_and_file = $path_part.$file_part;
5731: if ($path_part eq $path) {
5732: $return_files{$file_part}= 'selected';
5733: }
5734: }
1.574 banghart 5735: close (IN);
5736: return (\%return_files);
1.572 banghart 5737: }
5738:
5739: # called in portfolio select mode, to show files selected NOT in current directory
5740: sub files_not_in_path {
5741: my ($user, $path) = @_;
5742: my $filename = $user."savedfiles";
5743: my @return_files;
5744: my $path_part;
1.800 albertel 5745: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5746: while (my $line = <IN>) {
1.572 banghart 5747: #ok, I know it's clunky, but I want it to work
1.800 albertel 5748: my @paths_and_file = split(m|/|, $line);
5749: my $file_part = pop(@paths_and_file);
5750: chomp($file_part);
5751: my $path_part = join('/', @paths_and_file);
1.572 banghart 5752: $path_part .= '/';
5753: my $path_and_file = $path_part.$file_part;
5754: if ($path_part ne $path) {
1.800 albertel 5755: push(@return_files, ($path_and_file));
1.572 banghart 5756: }
5757: }
1.800 albertel 5758: close(OUT);
1.574 banghart 5759: return (@return_files);
1.572 banghart 5760: }
5761:
1.745 raeburn 5762: #----------------------------------------------Get portfolio file permissions
1.629 banghart 5763:
1.745 raeburn 5764: sub get_portfile_permissions {
5765: my ($domain,$user) = @_;
1.613 albertel 5766: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5767: my ($tmp)=keys(%current_permissions);
5768: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 5769: return \%current_permissions;
5770: }
5771:
5772: #---------------------------------------------Get portfolio file access controls
5773:
1.749 raeburn 5774: sub get_access_controls {
1.745 raeburn 5775: my ($current_permissions,$group,$file) = @_;
1.769 albertel 5776: my %access;
5777: my $real_file = $file;
5778: $file =~ s/\.meta$//;
1.745 raeburn 5779: if (defined($file)) {
1.749 raeburn 5780: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
5781: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 5782: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 5783: }
5784: }
1.745 raeburn 5785: } else {
1.749 raeburn 5786: foreach my $key (keys(%{$current_permissions})) {
5787: if ($key =~ /\0accesscontrol$/) {
5788: if (defined($group)) {
5789: if ($key !~ m-^\Q$group\E/-) {
5790: next;
5791: }
5792: }
5793: my ($fullpath) = split(/\0/,$key);
5794: if (ref($$current_permissions{$key}) eq 'HASH') {
5795: foreach my $control (keys(%{$$current_permissions{$key}})) {
5796: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
5797: }
5798: }
5799: }
5800: }
5801: }
5802: return %access;
5803: }
5804:
5805: sub modify_access_controls {
5806: my ($file_name,$changes,$domain,$user)=@_;
5807: my ($outcome,$deloutcome);
5808: my %store_permissions;
5809: my %new_values;
5810: my %new_control;
5811: my %translation;
5812: my @deletions = ();
5813: my $now = time;
5814: if (exists($$changes{'activate'})) {
5815: if (ref($$changes{'activate'}) eq 'HASH') {
5816: my @newitems = sort(keys(%{$$changes{'activate'}}));
5817: my $numnew = scalar(@newitems);
5818: for (my $i=0; $i<$numnew; $i++) {
5819: my $newkey = $newitems[$i];
5820: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 5821: if ($newkey =~ /^\d+:/) {
5822: $newkey =~ s/^(\d+)/$newid/;
5823: $translation{$1} = $newid;
5824: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
5825: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
5826: $translation{$1} = $newid;
5827: }
1.749 raeburn 5828: $new_values{$file_name."\0".$newkey} =
5829: $$changes{'activate'}{$newitems[$i]};
5830: $new_control{$newkey} = $now;
5831: }
5832: }
5833: }
5834: my %todelete;
5835: my %changed_items;
5836: foreach my $action ('delete','update') {
5837: if (exists($$changes{$action})) {
5838: if (ref($$changes{$action}) eq 'HASH') {
5839: foreach my $key (keys(%{$$changes{$action}})) {
5840: my ($itemnum) = ($key =~ /^([^:]+):/);
5841: if ($action eq 'delete') {
5842: $todelete{$itemnum} = 1;
5843: } else {
5844: $changed_items{$itemnum} = $key;
5845: }
5846: }
1.745 raeburn 5847: }
5848: }
1.749 raeburn 5849: }
5850: # get lock on access controls for file.
5851: my $lockhash = {
5852: $file_name."\0".'locked_access_records' => $env{'user.name'}.
5853: ':'.$env{'user.domain'},
5854: };
5855: my $tries = 0;
5856: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5857:
5858: while (($gotlock ne 'ok') && $tries <3) {
5859: $tries ++;
5860: sleep 1;
5861: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5862: }
5863: if ($gotlock eq 'ok') {
5864: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
5865: my ($tmp)=keys(%curr_permissions);
5866: if ($tmp=~/^error:/) { undef(%curr_permissions); }
5867: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
5868: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
5869: if (ref($curr_controls) eq 'HASH') {
5870: foreach my $control_item (keys(%{$curr_controls})) {
5871: my ($itemnum) = ($control_item =~ /^([^:]+):/);
5872: if (defined($todelete{$itemnum})) {
5873: push(@deletions,$file_name."\0".$control_item);
5874: } else {
5875: if (defined($changed_items{$itemnum})) {
5876: $new_control{$changed_items{$itemnum}} = $now;
5877: push(@deletions,$file_name."\0".$control_item);
5878: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
5879: } else {
5880: $new_control{$control_item} = $$curr_controls{$control_item};
5881: }
5882: }
1.745 raeburn 5883: }
5884: }
5885: }
1.749 raeburn 5886: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
5887: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
5888: $outcome = &put('file_permissions',\%new_values,$domain,$user);
5889: # remove lock
5890: my @del_lock = ($file_name."\0".'locked_access_records');
5891: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 5892: my ($file,$group);
5893: if (&is_course($domain,$user)) {
5894: ($group,$file) = split(/\//,$file_name,2);
5895: } else {
5896: $file = $file_name;
5897: }
5898: my $sqlresult =
5899: &update_portfolio_table($user,$domain,$file,'portfolio_access',
5900: $group);
1.749 raeburn 5901: } else {
5902: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 5903: }
1.749 raeburn 5904: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 5905: }
5906:
1.827 raeburn 5907: sub make_public_indefinitely {
5908: my ($requrl) = @_;
5909: my $now = time;
5910: my $action = 'activate';
5911: my $aclnum = 0;
5912: if (&is_portfolio_url($requrl)) {
5913: my (undef,$udom,$unum,$file_name,$group) =
5914: &parse_portfolio_url($requrl);
5915: my $current_perms = &get_portfile_permissions($udom,$unum);
5916: my %access_controls = &get_access_controls($current_perms,
5917: $group,$file_name);
5918: foreach my $key (keys(%{$access_controls{$file_name}})) {
5919: my ($num,$scope,$end,$start) =
5920: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5921: if ($scope eq 'public') {
5922: if ($start <= $now && $end == 0) {
5923: $action = 'none';
5924: } else {
5925: $action = 'update';
5926: $aclnum = $num;
5927: }
5928: last;
5929: }
5930: }
5931: if ($action eq 'none') {
5932: return 'ok';
5933: } else {
5934: my %changes;
5935: my $newend = 0;
5936: my $newstart = $now;
5937: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
5938: $changes{$action}{$newkey} = {
5939: type => 'public',
5940: time => {
5941: start => $newstart,
5942: end => $newend,
5943: },
5944: };
5945: my ($outcome,$deloutcome,$new_values,$translation) =
5946: &modify_access_controls($file_name,\%changes,$udom,$unum);
5947: return $outcome;
5948: }
5949: } else {
5950: return 'invalid';
5951: }
5952: }
5953:
1.745 raeburn 5954: #------------------------------------------------------Get Marked as Read Only
5955:
5956: sub get_marked_as_readonly {
5957: my ($domain,$user,$what,$group) = @_;
5958: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 5959: my @readonly_files;
1.629 banghart 5960: my $cmp1=$what;
5961: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 5962: while (my ($file_name,$value) = each(%{$current_permissions})) {
5963: if (defined($group)) {
5964: if ($file_name !~ m-^\Q$group\E/-) {
5965: next;
5966: }
5967: }
1.561 banghart 5968: if (ref($value) eq "ARRAY"){
5969: foreach my $stored_what (@{$value}) {
1.629 banghart 5970: my $cmp2=$stored_what;
1.759 albertel 5971: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 5972: $cmp2=join('',@{$stored_what});
1.745 raeburn 5973: }
1.629 banghart 5974: if ($cmp1 eq $cmp2) {
1.561 banghart 5975: push(@readonly_files, $file_name);
1.745 raeburn 5976: last;
1.563 banghart 5977: } elsif (!defined($what)) {
5978: push(@readonly_files, $file_name);
1.745 raeburn 5979: last;
1.561 banghart 5980: }
5981: }
1.745 raeburn 5982: }
1.561 banghart 5983: }
5984: return @readonly_files;
5985: }
1.577 banghart 5986: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 5987:
1.577 banghart 5988: sub get_marked_as_readonly_hash {
1.745 raeburn 5989: my ($current_permissions,$group,$what) = @_;
1.577 banghart 5990: my %readonly_files;
1.745 raeburn 5991: while (my ($file_name,$value) = each(%{$current_permissions})) {
5992: if (defined($group)) {
5993: if ($file_name !~ m-^\Q$group\E/-) {
5994: next;
5995: }
5996: }
1.577 banghart 5997: if (ref($value) eq "ARRAY"){
5998: foreach my $stored_what (@{$value}) {
1.745 raeburn 5999: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 6000: foreach my $lock_descriptor(@{$stored_what}) {
6001: if ($lock_descriptor eq 'graded') {
6002: $readonly_files{$file_name} = 'graded';
6003: } elsif ($lock_descriptor eq 'handback') {
6004: $readonly_files{$file_name} = 'handback';
6005: } else {
6006: if (!exists($readonly_files{$file_name})) {
6007: $readonly_files{$file_name} = 'locked';
6008: }
6009: }
1.745 raeburn 6010: }
1.750 banghart 6011: }
1.577 banghart 6012: }
6013: }
6014: }
6015: return %readonly_files;
6016: }
1.559 banghart 6017: # ------------------------------------------------------------ Unmark as Read Only
6018:
6019: sub unmark_as_readonly {
1.629 banghart 6020: # unmarks $file_name (if $file_name is defined), or all files locked by $what
6021: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 6022: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 6023: $file_name = &declutter_portfile($file_name);
1.634 albertel 6024: my $symb_crs = $what;
6025: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 6026: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 6027: my ($tmp)=keys(%current_permissions);
6028: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6029: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 6030: foreach my $file (@readonly_files) {
1.759 albertel 6031: my $clean_file = &declutter_portfile($file);
6032: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 6033: my $current_locks = $current_permissions{$file};
1.563 banghart 6034: my @new_locks;
6035: my @del_keys;
6036: if (ref($current_locks) eq "ARRAY"){
6037: foreach my $locker (@{$current_locks}) {
1.632 albertel 6038: my $compare=$locker;
1.749 raeburn 6039: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 6040: $compare=join('',@{$locker});
1.746 raeburn 6041: if ($compare ne $symb_crs) {
6042: push(@new_locks, $locker);
6043: }
1.563 banghart 6044: }
6045: }
1.650 albertel 6046: if (scalar(@new_locks) > 0) {
1.563 banghart 6047: $current_permissions{$file} = \@new_locks;
6048: } else {
6049: push(@del_keys, $file);
1.613 albertel 6050: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 6051: delete($current_permissions{$file});
1.563 banghart 6052: }
6053: }
1.561 banghart 6054: }
1.613 albertel 6055: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6056: return;
6057: }
1.512 banghart 6058:
1.17 www 6059: # ------------------------------------------------------------ Directory lister
6060:
6061: sub dirlist {
1.253 stredwic 6062: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
6063:
1.18 www 6064: $uri=~s/^\///;
6065: $uri=~s/\/$//;
1.253 stredwic 6066: my ($udom, $uname);
6067: (undef,$udom,$uname)=split(/\//,$uri);
6068: if(defined($userdomain)) {
6069: $udom = $userdomain;
6070: }
6071: if(defined($username)) {
6072: $uname = $username;
6073: }
6074:
6075: my $dirRoot = $perlvar{'lonDocRoot'};
6076: if(defined($alternateDirectoryRoot)) {
6077: $dirRoot = $alternateDirectoryRoot;
6078: $dirRoot =~ s/\/$//;
1.751 banghart 6079: }
1.253 stredwic 6080:
6081: if($udom) {
6082: if($uname) {
1.800 albertel 6083: my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
6084: &homeserver($uname,$udom));
1.605 matthew 6085: my @listing_results;
6086: if ($listing eq 'unknown_cmd') {
1.800 albertel 6087: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
6088: &homeserver($uname,$udom));
1.605 matthew 6089: @listing_results = split(/:/,$listing);
6090: } else {
6091: @listing_results = map { &unescape($_); } split(/:/,$listing);
6092: }
6093: return @listing_results;
1.253 stredwic 6094: } elsif(!defined($alternateDirectoryRoot)) {
1.800 albertel 6095: my %allusers;
1.841 albertel 6096: my %servers = &get_servers($udom,'library');
6097: foreach my $tryserver (keys(%servers)) {
6098: my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
6099: $udom, $tryserver);
6100: my @listing_results;
6101: if ($listing eq 'unknown_cmd') {
6102: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
6103: $udom, $tryserver);
6104: @listing_results = split(/:/,$listing);
6105: } else {
6106: @listing_results =
6107: map { &unescape($_); } split(/:/,$listing);
6108: }
6109: if ($listing_results[0] ne 'no_such_dir' &&
6110: $listing_results[0] ne 'empty' &&
6111: $listing_results[0] ne 'con_lost') {
6112: foreach my $line (@listing_results) {
6113: my ($entry) = split(/&/,$line,2);
6114: $allusers{$entry} = 1;
6115: }
6116: }
1.253 stredwic 6117: }
6118: my $alluserstr='';
1.800 albertel 6119: foreach my $user (sort(keys(%allusers))) {
6120: $alluserstr.=$user.'&user:';
1.253 stredwic 6121: }
6122: $alluserstr=~s/:$//;
6123: return split(/:/,$alluserstr);
6124: } else {
1.800 albertel 6125: return ('missing user name');
1.253 stredwic 6126: }
6127: } elsif(!defined($alternateDirectoryRoot)) {
1.841 albertel 6128: my @all_domains = sort(&all_domains());
6129: foreach my $domain (@all_domains) {
6130: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
6131: }
6132: return @all_domains;
6133: } else {
1.800 albertel 6134: return ('missing domain');
1.275 stredwic 6135: }
6136: }
6137:
6138: # --------------------------------------------- GetFileTimestamp
6139: # This function utilizes dirlist and returns the date stamp for
6140: # when it was last modified. It will also return an error of -1
6141: # if an error occurs
6142:
1.410 matthew 6143: ##
6144: ## FIXME: This subroutine assumes its caller knows something about the
6145: ## directory structure of the home server for the student ($root).
6146: ## Not a good assumption to make. Since this is for looking up files
6147: ## in user directories, the full path should be constructed by lond, not
6148: ## whatever machine we request data from.
6149: ##
1.275 stredwic 6150: sub GetFileTimestamp {
6151: my ($studentDomain,$studentName,$filename,$root)=@_;
1.807 albertel 6152: $studentDomain = &LONCAPA::clean_domain($studentDomain);
6153: $studentName = &LONCAPA::clean_username($studentName);
1.275 stredwic 6154: my $subdir=$studentName.'__';
6155: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
6156: my $proname="$studentDomain/$subdir/$studentName";
6157: $proname .= '/'.$filename;
1.375 matthew 6158: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
6159: $studentName, $root);
1.275 stredwic 6160: my @stats = split('&', $fileStat);
6161: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 6162: # @stats contains first the filename, then the stat output
6163: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 6164: } else {
6165: return -1;
1.253 stredwic 6166: }
1.26 www 6167: }
6168:
1.712 albertel 6169: sub stat_file {
6170: my ($uri) = @_;
1.787 albertel 6171: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 6172:
1.712 albertel 6173: my ($udom,$uname,$file,$dir);
6174: if ($uri =~ m-^/(uploaded|editupload)/-) {
6175: ($udom,$uname,$file) =
1.811 albertel 6176: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 6177: $file = 'userfiles/'.$file;
1.740 www 6178: $dir = &propath($udom,$uname);
1.712 albertel 6179: }
6180: if ($uri =~ m-^/res/-) {
6181: ($udom,$uname) =
1.807 albertel 6182: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 6183: $file = $uri;
6184: }
6185:
6186: if (!$udom || !$uname || !$file) {
6187: # unable to handle the uri
6188: return ();
6189: }
6190:
6191: my ($result) = &dirlist($file,$udom,$uname,$dir);
6192: my @stats = split('&', $result);
1.721 banghart 6193:
1.712 albertel 6194: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
6195: shift(@stats); #filename is first
6196: return @stats;
6197: }
6198: return ();
6199: }
6200:
1.26 www 6201: # -------------------------------------------------------- Value of a Condition
6202:
1.713 albertel 6203: # gets the value of a specific preevaluated condition
6204: # stored in the string $env{user.state.<cid>}
6205: # or looks up a condition reference in the bighash and if if hasn't
6206: # already been evaluated recurses into docondval to get the value of
6207: # the condition, then memoizing it to
6208: # $env{user.state.<cid>.<condition>}
1.40 www 6209: sub directcondval {
6210: my $number=shift;
1.620 albertel 6211: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 6212: &Apache::lonuserstate::evalstate();
6213: }
1.713 albertel 6214: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
6215: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
6216: } elsif ($number =~ /^_/) {
6217: my $sub_condition;
6218: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6219: &GDBM_READER(),0640)) {
6220: $sub_condition=$bighash{'conditions'.$number};
6221: untie(%bighash);
6222: }
6223: my $value = &docondval($sub_condition);
6224: &appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
6225: return $value;
6226: }
1.620 albertel 6227: if ($env{'user.state.'.$env{'request.course.id'}}) {
6228: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 6229: } else {
6230: return 2;
6231: }
6232: }
6233:
1.713 albertel 6234: # get the collection of conditions for this resource
1.26 www 6235: sub condval {
6236: my $condidx=shift;
1.54 www 6237: my $allpathcond='';
1.713 albertel 6238: foreach my $cond (split(/\|/,$condidx)) {
6239: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
6240: $allpathcond.=
6241: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
6242: }
1.191 harris41 6243: }
1.54 www 6244: $allpathcond=~s/\|$//;
1.713 albertel 6245: return &docondval($allpathcond);
6246: }
6247:
6248: #evaluates an expression of conditions
6249: sub docondval {
6250: my ($allpathcond) = @_;
6251: my $result=0;
6252: if ($env{'request.course.id'}
6253: && defined($allpathcond)) {
6254: my $operand='|';
6255: my @stack;
6256: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
6257: if ($chunk eq '(') {
6258: push @stack,($operand,$result);
6259: } elsif ($chunk eq ')') {
6260: my $before=pop @stack;
6261: if (pop @stack eq '&') {
6262: $result=$result>$before?$before:$result;
6263: } else {
6264: $result=$result>$before?$result:$before;
6265: }
6266: } elsif (($chunk eq '&') || ($chunk eq '|')) {
6267: $operand=$chunk;
6268: } else {
6269: my $new=directcondval($chunk);
6270: if ($operand eq '&') {
6271: $result=$result>$new?$new:$result;
6272: } else {
6273: $result=$result>$new?$result:$new;
6274: }
6275: }
6276: }
1.26 www 6277: }
6278: return $result;
1.421 albertel 6279: }
6280:
6281: # ---------------------------------------------------- Devalidate courseresdata
6282:
6283: sub devalidatecourseresdata {
6284: my ($coursenum,$coursedomain)=@_;
6285: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6286: &devalidate_cache_new('courseres',$hashid);
1.28 www 6287: }
6288:
1.763 www 6289:
1.200 www 6290: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 6291: #
6292: # Parameters:
6293: # $coursenum - Number of the course.
6294: # $coursedomain - Domain at which the course was created.
6295: # Returns:
6296: # A hash of the course parameters along (I think) with timestamps
6297: # and version info.
1.877 foxr 6298:
1.624 albertel 6299: sub get_courseresdata {
6300: my ($coursenum,$coursedomain)=@_;
1.200 www 6301: my $coursehom=&homeserver($coursenum,$coursedomain);
6302: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6303: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 6304: my %dumpreply;
1.417 albertel 6305: unless (defined($cached)) {
1.624 albertel 6306: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 6307: $result=\%dumpreply;
1.251 albertel 6308: my ($tmp) = keys(%dumpreply);
6309: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 6310: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 6311: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
6312: return $tmp;
1.416 albertel 6313: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 6314: $result=undef;
1.599 albertel 6315: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 6316: }
6317: }
1.624 albertel 6318: return $result;
6319: }
6320:
1.633 albertel 6321: sub devalidateuserresdata {
6322: my ($uname,$udom)=@_;
6323: my $hashid="$udom:$uname";
6324: &devalidate_cache_new('userres',$hashid);
6325: }
6326:
1.624 albertel 6327: sub get_userresdata {
6328: my ($uname,$udom)=@_;
6329: #most student don\'t have any data set, check if there is some data
6330: if (&EXT_cache_status($udom,$uname)) { return undef; }
6331:
6332: my $hashid="$udom:$uname";
6333: my ($result,$cached)=&is_cached_new('userres',$hashid);
6334: if (!defined($cached)) {
6335: my %resourcedata=&dump('resourcedata',$udom,$uname);
6336: $result=\%resourcedata;
6337: &do_cache_new('userres',$hashid,$result,600);
6338: }
6339: my ($tmp)=keys(%$result);
6340: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
6341: return $result;
6342: }
6343: #error 2 occurs when the .db doesn't exist
6344: if ($tmp!~/error: 2 /) {
1.672 albertel 6345: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 6346: " Trying to get resource data for ".
6347: $uname." at ".$udom.": ".
6348: $tmp."</font>");
6349: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 6350: #&EXT_cache_set($udom,$uname);
6351: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 6352: undef($tmp); # not really an error so don't send it back
1.624 albertel 6353: }
6354: return $tmp;
6355: }
1.879 foxr 6356: #----------------------------------------------- resdata - return resource data
6357: # Purpose:
6358: # Return resource data for either users or for a course.
6359: # Parameters:
6360: # $name - Course/user name.
6361: # $domain - Name of the domain the user/course is registered on.
6362: # $type - Type of thing $name is (must be 'course' or 'user'
6363: # @which - Array of names of resources desired.
6364: # Returns:
6365: # The value of the first reasource in @which that is found in the
6366: # resource hash.
6367: # Exceptional Conditions:
6368: # If the $type passed in is not valid (not the string 'course' or
6369: # 'user', an undefined reference is returned.
6370: # If none of the resources are found, an undef is returned
1.624 albertel 6371: sub resdata {
6372: my ($name,$domain,$type,@which)=@_;
6373: my $result;
6374: if ($type eq 'course') {
6375: $result=&get_courseresdata($name,$domain);
6376: } elsif ($type eq 'user') {
6377: $result=&get_userresdata($name,$domain);
6378: }
6379: if (!ref($result)) { return $result; }
1.251 albertel 6380: foreach my $item (@which) {
1.417 albertel 6381: if (defined($result->{$item})) {
6382: return $result->{$item};
1.251 albertel 6383: }
1.250 albertel 6384: }
1.291 albertel 6385: return undef;
1.200 www 6386: }
6387:
1.379 matthew 6388: #
6389: # EXT resource caching routines
6390: #
6391:
6392: sub clear_EXT_cache_status {
1.383 albertel 6393: &delenv('cache.EXT.');
1.379 matthew 6394: }
6395:
6396: sub EXT_cache_status {
6397: my ($target_domain,$target_user) = @_;
1.383 albertel 6398: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 6399: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 6400: # We know already the user has no data
6401: return 1;
6402: } else {
6403: return 0;
6404: }
6405: }
6406:
6407: sub EXT_cache_set {
6408: my ($target_domain,$target_user) = @_;
1.383 albertel 6409: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633 albertel 6410: #&appenv($cachename => time);
1.379 matthew 6411: }
6412:
1.28 www 6413: # --------------------------------------------------------- Value of a Variable
1.58 www 6414: sub EXT {
1.715 albertel 6415:
1.395 albertel 6416: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 6417: unless ($varname) { return ''; }
1.218 albertel 6418: #get real user name/domain, courseid and symb
6419: my $courseid;
1.359 albertel 6420: my $publicuser;
1.427 www 6421: if ($symbparm) {
6422: $symbparm=&get_symb_from_alias($symbparm);
6423: }
1.218 albertel 6424: if (!($uname && $udom)) {
1.790 albertel 6425: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 6426: if (!$symbparm) { $symbparm=$cursymb; }
6427: } else {
1.620 albertel 6428: $courseid=$env{'request.course.id'};
1.218 albertel 6429: }
1.48 www 6430: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
6431: my $rest;
1.320 albertel 6432: if (defined($therest[0])) {
1.48 www 6433: $rest=join('.',@therest);
6434: } else {
6435: $rest='';
6436: }
1.320 albertel 6437:
1.57 www 6438: my $qualifierrest=$qualifier;
6439: if ($rest) { $qualifierrest.='.'.$rest; }
6440: my $spacequalifierrest=$space;
6441: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 6442: if ($realm eq 'user') {
1.48 www 6443: # --------------------------------------------------------------- user.resource
6444: if ($space eq 'resource') {
1.651 albertel 6445: if ( (defined($Apache::lonhomework::parsing_a_problem)
6446: || defined($Apache::lonhomework::parsing_a_task))
6447: &&
1.744 albertel 6448: ($symbparm eq &symbread()) ) {
6449: # if we are in the middle of processing the resource the
6450: # get the value we are planning on committing
6451: if (defined($Apache::lonhomework::results{$qualifierrest})) {
6452: return $Apache::lonhomework::results{$qualifierrest};
6453: } else {
6454: return $Apache::lonhomework::history{$qualifierrest};
6455: }
1.335 albertel 6456: } else {
1.359 albertel 6457: my %restored;
1.620 albertel 6458: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 6459: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
6460: } else {
6461: %restored=&restore($symbparm,$courseid,$udom,$uname);
6462: }
1.335 albertel 6463: return $restored{$qualifierrest};
6464: }
1.48 www 6465: # ----------------------------------------------------------------- user.access
6466: } elsif ($space eq 'access') {
1.218 albertel 6467: # FIXME - not supporting calls for a specific user
1.48 www 6468: return &allowed($qualifier,$rest);
6469: # ------------------------------------------ user.preferences, user.environment
6470: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 6471: if (($uname eq $env{'user.name'}) &&
6472: ($udom eq $env{'user.domain'})) {
6473: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 6474: } else {
1.359 albertel 6475: my %returnhash;
6476: if (!$publicuser) {
6477: %returnhash=&userenvironment($udom,$uname,
6478: $qualifierrest);
6479: }
1.218 albertel 6480: return $returnhash{$qualifierrest};
6481: }
1.48 www 6482: # ----------------------------------------------------------------- user.course
6483: } elsif ($space eq 'course') {
1.218 albertel 6484: # FIXME - not supporting calls for a specific user
1.620 albertel 6485: return $env{join('.',('request.course',$qualifier))};
1.48 www 6486: # ------------------------------------------------------------------- user.role
6487: } elsif ($space eq 'role') {
1.218 albertel 6488: # FIXME - not supporting calls for a specific user
1.620 albertel 6489: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 6490: if ($qualifier eq 'value') {
6491: return $role;
6492: } elsif ($qualifier eq 'extent') {
6493: return $where;
6494: }
6495: # ----------------------------------------------------------------- user.domain
6496: } elsif ($space eq 'domain') {
1.218 albertel 6497: return $udom;
1.48 www 6498: # ------------------------------------------------------------------- user.name
6499: } elsif ($space eq 'name') {
1.218 albertel 6500: return $uname;
1.48 www 6501: # ---------------------------------------------------- Any other user namespace
1.29 www 6502: } else {
1.359 albertel 6503: my %reply;
6504: if (!$publicuser) {
6505: %reply=&get($space,[$qualifierrest],$udom,$uname);
6506: }
6507: return $reply{$qualifierrest};
1.48 www 6508: }
1.236 www 6509: } elsif ($realm eq 'query') {
6510: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 6511: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
6512: [$spacequalifierrest]);
1.620 albertel 6513: return $env{'form.'.$spacequalifierrest};
1.236 www 6514: } elsif ($realm eq 'request') {
1.48 www 6515: # ------------------------------------------------------------- request.browser
6516: if ($space eq 'browser') {
1.430 www 6517: if ($qualifier eq 'textremote') {
1.676 albertel 6518: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 6519: return 1;
6520: } else {
6521: return 0;
6522: }
6523: } else {
1.620 albertel 6524: return $env{'browser.'.$qualifier};
1.430 www 6525: }
1.57 www 6526: # ------------------------------------------------------------ request.filename
6527: } else {
1.620 albertel 6528: return $env{'request.'.$spacequalifierrest};
1.29 www 6529: }
1.28 www 6530: } elsif ($realm eq 'course') {
1.48 www 6531: # ---------------------------------------------------------- course.description
1.620 albertel 6532: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 6533: } elsif ($realm eq 'resource') {
1.165 www 6534:
1.620 albertel 6535: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 6536: if (!$symbparm) { $symbparm=&symbread(); }
6537: }
1.693 albertel 6538:
6539: if ($space eq 'title') {
6540: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
6541: return &gettitle($symbparm);
6542: }
6543:
6544: if ($space eq 'map') {
6545: my ($map) = &decode_symb($symbparm);
6546: return &symbread($map);
6547: }
1.905 albertel 6548: if ($space eq 'filename') {
6549: if ($symbparm) {
6550: return &clutter((&decode_symb($symbparm))[2]);
6551: }
6552: return &hreflocation('',$env{'request.filename'});
6553: }
1.693 albertel 6554:
6555: my ($section, $group, @groups);
1.593 albertel 6556: my ($courselevelm,$courselevel);
1.539 albertel 6557: if ($symbparm && defined($courseid) &&
1.620 albertel 6558: $courseid eq $env{'request.course.id'}) {
1.165 www 6559:
1.218 albertel 6560: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 6561:
1.60 www 6562: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 6563: my $symbp=$symbparm;
1.735 albertel 6564: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 6565:
6566: my $symbparm=$symbp.'.'.$spacequalifierrest;
6567: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
6568:
1.620 albertel 6569: if (($env{'user.name'} eq $uname) &&
6570: ($env{'user.domain'} eq $udom)) {
6571: $section=$env{'request.course.sec'};
1.733 raeburn 6572: @groups = split(/:/,$env{'request.course.groups'});
6573: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 6574: } else {
1.539 albertel 6575: if (! defined($usection)) {
1.551 albertel 6576: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 6577: } else {
6578: $section = $usection;
6579: }
1.733 raeburn 6580: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 6581: }
6582:
6583: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
6584: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
6585: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
6586:
1.593 albertel 6587: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 6588: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 6589: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 6590:
1.60 www 6591: # ----------------------------------------------------------- first, check user
1.624 albertel 6592:
6593: my $userreply=&resdata($uname,$udom,'user',
6594: ($courselevelr,$courselevelm,
6595: $courselevel));
6596: if (defined($userreply)) { return $userreply; }
1.95 www 6597:
1.594 albertel 6598: # ------------------------------------------------ second, check some of course
1.684 raeburn 6599: my $coursereply;
1.691 raeburn 6600: if (@groups > 0) {
6601: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
6602: $mapparm,$spacequalifierrest);
1.684 raeburn 6603: if (defined($coursereply)) { return $coursereply; }
6604: }
1.96 www 6605:
1.684 raeburn 6606: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624 albertel 6607: $env{'course.'.$courseid.'.domain'},
6608: 'course',
6609: ($seclevelr,$seclevelm,$seclevel,
6610: $courselevelr));
1.287 albertel 6611: if (defined($coursereply)) { return $coursereply; }
1.200 www 6612:
1.60 www 6613: # ------------------------------------------------------ third, check map parms
1.218 albertel 6614: my %parmhash=();
6615: my $thisparm='';
6616: if (tie(%parmhash,'GDBM_File',
1.620 albertel 6617: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 6618: &GDBM_READER(),0640)) {
1.218 albertel 6619: $thisparm=$parmhash{$symbparm};
6620: untie(%parmhash);
6621: }
6622: if ($thisparm) { return $thisparm; }
6623: }
1.594 albertel 6624: # ------------------------------------------ fourth, look in resource metadata
1.71 www 6625:
1.218 albertel 6626: $spacequalifierrest=~s/\./\_/;
1.282 albertel 6627: my $filename;
6628: if (!$symbparm) { $symbparm=&symbread(); }
6629: if ($symbparm) {
1.409 www 6630: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 6631: } else {
1.620 albertel 6632: $filename=$env{'request.filename'};
1.282 albertel 6633: }
6634: my $metadata=&metadata($filename,$spacequalifierrest);
1.288 albertel 6635: if (defined($metadata)) { return $metadata; }
1.282 albertel 6636: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288 albertel 6637: if (defined($metadata)) { return $metadata; }
1.142 www 6638:
1.594 albertel 6639: # ---------------------------------------------- fourth, look in rest pf course
1.593 albertel 6640: if ($symbparm && defined($courseid) &&
1.620 albertel 6641: $courseid eq $env{'request.course.id'}) {
1.624 albertel 6642: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
6643: $env{'course.'.$courseid.'.domain'},
6644: 'course',
6645: ($courselevelm,$courselevel));
1.593 albertel 6646: if (defined($coursereply)) { return $coursereply; }
6647: }
1.145 www 6648: # ------------------------------------------------------------------ Cascade up
1.218 albertel 6649: unless ($space eq '0') {
1.336 albertel 6650: my @parts=split(/_/,$space);
6651: my $id=pop(@parts);
6652: my $part=join('_',@parts);
6653: if ($part eq '') { $part='0'; }
6654: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 6655: $symbparm,$udom,$uname,$section,1);
1.337 albertel 6656: if (defined($partgeneral)) { return $partgeneral; }
1.218 albertel 6657: }
1.395 albertel 6658: if ($recurse) { return undef; }
6659: my $pack_def=&packages_tab_default($filename,$varname);
6660: if (defined($pack_def)) { return $pack_def; }
1.71 www 6661:
1.48 www 6662: # ---------------------------------------------------- Any other user namespace
6663: } elsif ($realm eq 'environment') {
6664: # ----------------------------------------------------------------- environment
1.620 albertel 6665: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
6666: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 6667: } else {
1.770 albertel 6668: if ($uname eq 'anonymous' && $udom eq '') {
6669: return '';
6670: }
1.219 albertel 6671: my %returnhash=&userenvironment($udom,$uname,
6672: $spacequalifierrest);
6673: return $returnhash{$spacequalifierrest};
6674: }
1.28 www 6675: } elsif ($realm eq 'system') {
1.48 www 6676: # ----------------------------------------------------------------- system.time
6677: if ($space eq 'time') {
6678: return time;
6679: }
1.696 albertel 6680: } elsif ($realm eq 'server') {
6681: # ----------------------------------------------------------------- system.time
6682: if ($space eq 'name') {
6683: return $ENV{'SERVER_NAME'};
6684: }
1.28 www 6685: }
1.48 www 6686: return '';
1.61 www 6687: }
6688:
1.691 raeburn 6689: sub check_group_parms {
6690: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
6691: my @groupitems = ();
6692: my $resultitem;
6693: my @levels = ($symbparm,$mapparm,$what);
6694: foreach my $group (@{$groups}) {
6695: foreach my $level (@levels) {
6696: my $item = $courseid.'.['.$group.'].'.$level;
6697: push(@groupitems,$item);
6698: }
6699: }
6700: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
6701: $env{'course.'.$courseid.'.domain'},
6702: 'course',@groupitems);
6703: return $coursereply;
6704: }
6705:
6706: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 6707: my ($courseid,@groups) = @_;
6708: @groups = sort(@groups);
1.691 raeburn 6709: return @groups;
6710: }
6711:
1.395 albertel 6712: sub packages_tab_default {
6713: my ($uri,$varname)=@_;
6714: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 6715:
6716: my (@extension,@specifics,$do_default);
6717: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 6718: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 6719: if ($pack_type eq 'default') {
6720: $do_default=1;
6721: } elsif ($pack_type eq 'extension') {
6722: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 6723: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 6724: # only look at packages defaults for packages that this id is
1.738 albertel 6725: push(@specifics,[$package,$pack_type,$pack_part]);
6726: }
6727: }
6728: # first look for a package that matches the requested part id
6729: foreach my $package (@specifics) {
6730: my (undef,$pack_type,$pack_part)=@{$package};
6731: next if ($pack_part ne $part);
6732: if (defined($packagetab{"$pack_type&$name&default"})) {
6733: return $packagetab{"$pack_type&$name&default"};
6734: }
6735: }
6736: # look for any possible matching non extension_ package
6737: foreach my $package (@specifics) {
6738: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 6739: if (defined($packagetab{"$pack_type&$name&default"})) {
6740: return $packagetab{"$pack_type&$name&default"};
6741: }
1.585 albertel 6742: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 6743: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
6744: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 6745: }
6746: }
1.738 albertel 6747: # look for any posible extension_ match
6748: foreach my $package (@extension) {
6749: my ($package,$pack_type)=@{$package};
6750: if (defined($packagetab{"$pack_type&$name&default"})) {
6751: return $packagetab{"$pack_type&$name&default"};
6752: }
6753: if (defined($packagetab{$package."&$name&default"})) {
6754: return $packagetab{$package."&$name&default"};
6755: }
6756: }
6757: # look for a global default setting
6758: if ($do_default && defined($packagetab{"default&$name&default"})) {
6759: return $packagetab{"default&$name&default"};
6760: }
1.395 albertel 6761: return undef;
6762: }
6763:
1.334 albertel 6764: sub add_prefix_and_part {
6765: my ($prefix,$part)=@_;
6766: my $keyroot;
6767: if (defined($prefix) && $prefix !~ /^__/) {
6768: # prefix that has a part already
6769: $keyroot=$prefix;
6770: } elsif (defined($prefix)) {
6771: # prefix that is missing a part
6772: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
6773: } else {
6774: # no prefix at all
6775: if (defined($part)) { $keyroot='_'.$part; }
6776: }
6777: return $keyroot;
6778: }
6779:
1.71 www 6780: # ---------------------------------------------------------------- Get metadata
6781:
1.599 albertel 6782: my %metaentry;
1.71 www 6783: sub metadata {
1.176 www 6784: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 6785: $uri=&declutter($uri);
1.288 albertel 6786: # if it is a non metadata possible uri return quickly
1.529 albertel 6787: if (($uri eq '') ||
6788: (($uri =~ m|^/*adm/|) &&
1.698 albertel 6789: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423 albertel 6790: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807 albertel 6791: ($uri =~ m|home/$match_username/public_html/|)) {
1.468 albertel 6792: return undef;
1.288 albertel 6793: }
1.73 www 6794: my $filename=$uri;
6795: $uri=~s/\.meta$//;
1.172 www 6796: #
6797: # Is the metadata already cached?
1.177 www 6798: # Look at timestamp of caching
1.172 www 6799: # Everything is cached by the main uri, libraries are never directly cached
6800: #
1.428 albertel 6801: if (!defined($liburi)) {
1.599 albertel 6802: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 6803: if (defined($cached)) { return $result->{':'.$what}; }
6804: }
6805: {
1.172 www 6806: #
6807: # Is this a recursive call for a library?
6808: #
1.599 albertel 6809: # if (! exists($metacache{$uri})) {
6810: # $metacache{$uri}={};
6811: # }
1.171 www 6812: if ($liburi) {
6813: $liburi=&declutter($liburi);
6814: $filename=$liburi;
1.401 bowersj2 6815: } else {
1.599 albertel 6816: &devalidate_cache_new('meta',$uri);
6817: undef(%metaentry);
1.401 bowersj2 6818: }
1.140 www 6819: my %metathesekeys=();
1.73 www 6820: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 6821: my $metastring;
1.768 albertel 6822: if ($uri !~ m -^(editupload)/-) {
1.543 albertel 6823: my $file=&filelocation('',&clutter($filename));
1.599 albertel 6824: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 6825: $metastring=&getfile($file);
1.489 albertel 6826: }
1.208 albertel 6827: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 6828: my $token;
1.140 www 6829: undef %metathesekeys;
1.71 www 6830: while ($token=$parser->get_token) {
1.339 albertel 6831: if ($token->[0] eq 'S') {
6832: if (defined($token->[2]->{'package'})) {
1.172 www 6833: #
6834: # This is a package - get package info
6835: #
1.339 albertel 6836: my $package=$token->[2]->{'package'};
6837: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6838: if (defined($token->[2]->{'id'})) {
6839: $keyroot.='_'.$token->[2]->{'id'};
6840: }
1.599 albertel 6841: if ($metaentry{':packages'}) {
6842: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 6843: } else {
1.599 albertel 6844: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 6845: }
1.736 albertel 6846: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 6847: my $part=$keyroot;
6848: $part=~s/^\_//;
1.736 albertel 6849: if ($pack_entry=~/^\Q$package\E\&/ ||
6850: $pack_entry=~/^\Q$package\E_0\&/) {
6851: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 6852: # ignore package.tab specified default values
6853: # here &package_tab_default() will fetch those
6854: if ($subp eq 'default') { next; }
1.736 albertel 6855: my $value=$packagetab{$pack_entry};
1.432 albertel 6856: my $unikey;
6857: if ($pack =~ /_0$/) {
6858: $unikey='parameter_0_'.$name;
6859: $part=0;
6860: } else {
6861: $unikey='parameter'.$keyroot.'_'.$name;
6862: }
1.339 albertel 6863: if ($subp eq 'display') {
6864: $value.=' [Part: '.$part.']';
6865: }
1.599 albertel 6866: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 6867: $metathesekeys{$unikey}=1;
1.599 albertel 6868: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6869: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 6870: }
1.599 albertel 6871: if (defined($metaentry{':'.$unikey.'.default'})) {
6872: $metaentry{':'.$unikey}=
6873: $metaentry{':'.$unikey.'.default'};
1.356 albertel 6874: }
1.339 albertel 6875: }
6876: }
6877: } else {
1.172 www 6878: #
6879: # This is not a package - some other kind of start tag
1.339 albertel 6880: #
6881: my $entry=$token->[1];
6882: my $unikey;
6883: if ($entry eq 'import') {
6884: $unikey='';
6885: } else {
6886: $unikey=$entry;
6887: }
6888: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6889:
6890: if (defined($token->[2]->{'id'})) {
6891: $unikey.='_'.$token->[2]->{'id'};
6892: }
1.175 www 6893:
1.339 albertel 6894: if ($entry eq 'import') {
1.175 www 6895: #
6896: # Importing a library here
1.339 albertel 6897: #
6898: if ($depthcount<20) {
6899: my $location=$parser->get_text('/import');
6900: my $dir=$filename;
6901: $dir=~s|[^/]*$||;
6902: $location=&filelocation($dir,$location);
1.736 albertel 6903: my $metadata =
6904: &metadata($uri,'keys', $location,$unikey,
6905: $depthcount+1);
6906: foreach my $meta (split(',',$metadata)) {
6907: $metaentry{':'.$meta}=$metaentry{':'.$meta};
6908: $metathesekeys{$meta}=1;
1.339 albertel 6909: }
6910: }
6911: } else {
6912:
6913: if (defined($token->[2]->{'name'})) {
6914: $unikey.='_'.$token->[2]->{'name'};
6915: }
6916: $metathesekeys{$unikey}=1;
1.736 albertel 6917: foreach my $param (@{$token->[3]}) {
6918: $metaentry{':'.$unikey.'.'.$param} =
6919: $token->[2]->{$param};
1.339 albertel 6920: }
6921: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 6922: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 6923: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
6924: # only ws inside the tag, and not in default, so use default
6925: # as value
1.599 albertel 6926: $metaentry{':'.$unikey}=$default;
1.908 albertel 6927: } elsif ( $internaltext =~ /\S/ ) {
6928: # something interesting inside the tag
6929: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 6930: } else {
1.908 albertel 6931: # no interesting values, don't set a default
1.339 albertel 6932: }
1.172 www 6933: # end of not-a-package not-a-library import
1.339 albertel 6934: }
1.172 www 6935: # end of not-a-package start tag
1.339 albertel 6936: }
1.172 www 6937: # the next is the end of "start tag"
1.339 albertel 6938: }
6939: }
1.483 albertel 6940: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 6941: $extension = lc($extension);
6942: if ($extension eq 'htm') { $extension='html'; }
6943:
1.737 albertel 6944: foreach my $key (keys(%packagetab)) {
1.483 albertel 6945: #no specific packages #how's our extension
6946: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 6947: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 6948: \%metathesekeys);
6949: }
1.883 albertel 6950:
6951: if (!exists($metaentry{':packages'})
6952: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 6953: foreach my $key (keys(%packagetab)) {
1.483 albertel 6954: #no specific packages well let's get default then
6955: if ($key!~/^default&/) { next; }
1.488 albertel 6956: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 6957: \%metathesekeys);
6958: }
6959: }
1.338 www 6960: # are there custom rights to evaluate
1.599 albertel 6961: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 6962:
1.338 www 6963: #
6964: # Importing a rights file here
1.339 albertel 6965: #
6966: unless ($depthcount) {
1.599 albertel 6967: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 6968: my $dir=$filename;
6969: $dir=~s|[^/]*$||;
6970: $location=&filelocation($dir,$location);
1.736 albertel 6971: my $rights_metadata =
6972: &metadata($uri,'keys',$location,'_rights',
6973: $depthcount+1);
6974: foreach my $rights (split(',',$rights_metadata)) {
6975: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
6976: $metathesekeys{$rights}=1;
1.339 albertel 6977: }
6978: }
6979: }
1.737 albertel 6980: # uniqifiy package listing
6981: my %seen;
6982: my @uniq_packages =
6983: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
6984: $metaentry{':packages'} = join(',',@uniq_packages);
6985:
6986: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 6987: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
6988: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699 albertel 6989: &do_cache_new('meta',$uri,\%metaentry,60*60);
1.177 www 6990: # this is the end of "was not already recently cached
1.71 www 6991: }
1.599 albertel 6992: return $metaentry{':'.$what};
1.261 albertel 6993: }
6994:
1.488 albertel 6995: sub metadata_create_package_def {
1.483 albertel 6996: my ($uri,$key,$package,$metathesekeys)=@_;
6997: my ($pack,$name,$subp)=split(/\&/,$key);
6998: if ($subp eq 'default') { next; }
6999:
1.599 albertel 7000: if (defined($metaentry{':packages'})) {
7001: $metaentry{':packages'}.=','.$package;
1.483 albertel 7002: } else {
1.599 albertel 7003: $metaentry{':packages'}=$package;
1.483 albertel 7004: }
7005: my $value=$packagetab{$key};
7006: my $unikey;
7007: $unikey='parameter_0_'.$name;
1.599 albertel 7008: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 7009: $$metathesekeys{$unikey}=1;
1.599 albertel 7010: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7011: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 7012: }
1.599 albertel 7013: if (defined($metaentry{':'.$unikey.'.default'})) {
7014: $metaentry{':'.$unikey}=
7015: $metaentry{':'.$unikey.'.default'};
1.483 albertel 7016: }
7017: }
7018:
1.261 albertel 7019: sub metadata_generate_part0 {
7020: my ($metadata,$metacache,$uri) = @_;
7021: my %allnames;
1.737 albertel 7022: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 7023: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 7024: my $part=$$metacache{':'.$metakey.'.part'};
7025: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 7026: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 7027: $allnames{$name}=$part;
7028: }
7029: }
7030: }
7031: foreach my $name (keys(%allnames)) {
7032: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 7033: my $key=":parameter_0_$name";
1.261 albertel 7034: $$metacache{"$key.part"}='0';
7035: $$metacache{"$key.name"}=$name;
1.428 albertel 7036: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 7037: $allnames{$name}.'_'.$name.
7038: '.type'};
1.428 albertel 7039: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 7040: '.display'};
1.644 www 7041: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 7042: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 7043: $$metacache{"$key.display"}=$olddis;
7044: }
1.71 www 7045: }
7046:
1.764 albertel 7047: # ------------------------------------------------------ Devalidate title cache
7048:
7049: sub devalidate_title_cache {
7050: my ($url)=@_;
7051: if (!$env{'request.course.id'}) { return; }
7052: my $symb=&symbread($url);
7053: if (!$symb) { return; }
7054: my $key=$env{'request.course.id'}."\0".$symb;
7055: &devalidate_cache_new('title',$key);
7056: }
7057:
1.301 www 7058: # ------------------------------------------------- Get the title of a resource
7059:
7060: sub gettitle {
7061: my $urlsymb=shift;
7062: my $symb=&symbread($urlsymb);
1.534 albertel 7063: if ($symb) {
1.620 albertel 7064: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 7065: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 7066: if (defined($cached)) {
7067: return $result;
7068: }
1.534 albertel 7069: my ($map,$resid,$url)=&decode_symb($symb);
7070: my $title='';
1.907 albertel 7071: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
7072: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
7073: } else {
7074: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7075: &GDBM_READER(),0640)) {
7076: my $mapid=$bighash{'map_pc_'.&clutter($map)};
7077: $title=$bighash{'title_'.$mapid.'.'.$resid};
7078: untie(%bighash);
7079: }
1.534 albertel 7080: }
7081: $title=~s/\&colon\;/\:/gs;
7082: if ($title) {
1.599 albertel 7083: return &do_cache_new('title',$key,$title,600);
1.534 albertel 7084: }
7085: $urlsymb=$url;
7086: }
7087: my $title=&metadata($urlsymb,'title');
7088: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
7089: return $title;
1.301 www 7090: }
1.613 albertel 7091:
1.614 albertel 7092: sub get_slot {
7093: my ($which,$cnum,$cdom)=@_;
7094: if (!$cnum || !$cdom) {
1.790 albertel 7095: (undef,my $courseid)=&whichuser();
1.620 albertel 7096: $cdom=$env{'course.'.$courseid.'.domain'};
7097: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 7098: }
1.703 albertel 7099: my $key=join("\0",'slots',$cdom,$cnum,$which);
7100: my %slotinfo;
7101: if (exists($remembered{$key})) {
7102: $slotinfo{$which} = $remembered{$key};
7103: } else {
7104: %slotinfo=&get('slots',[$which],$cdom,$cnum);
7105: &Apache::lonhomework::showhash(%slotinfo);
7106: my ($tmp)=keys(%slotinfo);
7107: if ($tmp=~/^error:/) { return (); }
7108: $remembered{$key} = $slotinfo{$which};
7109: }
1.616 albertel 7110: if (ref($slotinfo{$which}) eq 'HASH') {
7111: return %{$slotinfo{$which}};
7112: }
7113: return $slotinfo{$which};
1.614 albertel 7114: }
1.31 www 7115: # ------------------------------------------------- Update symbolic store links
7116:
7117: sub symblist {
7118: my ($mapname,%newhash)=@_;
1.438 www 7119: $mapname=&deversion(&declutter($mapname));
1.31 www 7120: my %hash;
1.620 albertel 7121: if (($env{'request.course.fn'}) && (%newhash)) {
7122: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7123: &GDBM_WRCREAT(),0640)) {
1.711 albertel 7124: foreach my $url (keys %newhash) {
7125: next if ($url eq 'last_known'
7126: && $env{'form.no_update_last_known'});
7127: $hash{declutter($url)}=&encode_symb($mapname,
7128: $newhash{$url}->[1],
7129: $newhash{$url}->[0]);
1.191 harris41 7130: }
1.31 www 7131: if (untie(%hash)) {
7132: return 'ok';
7133: }
7134: }
7135: }
7136: return 'error';
1.212 www 7137: }
7138:
7139: # --------------------------------------------------------------- Verify a symb
7140:
7141: sub symbverify {
1.510 www 7142: my ($symb,$thisurl)=@_;
7143: my $thisfn=$thisurl;
1.439 www 7144: $thisfn=&declutter($thisfn);
1.215 www 7145: # direct jump to resource in page or to a sequence - will construct own symbs
7146: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
7147: # check URL part
1.409 www 7148: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 7149:
1.431 www 7150: unless ($url eq $thisfn) { return 0; }
1.213 www 7151:
1.216 www 7152: $symb=&symbclean($symb);
1.510 www 7153: $thisurl=&deversion($thisurl);
1.439 www 7154: $thisfn=&deversion($thisfn);
1.213 www 7155:
7156: my %bighash;
7157: my $okay=0;
1.431 www 7158:
1.620 albertel 7159: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7160: &GDBM_READER(),0640)) {
1.510 www 7161: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 7162: unless ($ids) {
1.510 www 7163: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 7164: }
7165: if ($ids) {
7166: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 7167: foreach my $id (split(/\,/,$ids)) {
7168: my ($mapid,$resid)=split(/\./,$id);
1.216 www 7169: if (
7170: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
7171: eq $symb) {
1.620 albertel 7172: if (($env{'request.role.adv'}) ||
1.800 albertel 7173: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 7174: $okay=1;
7175: }
7176: }
1.216 www 7177: }
7178: }
1.213 www 7179: untie(%bighash);
7180: }
7181: return $okay;
1.31 www 7182: }
7183:
1.210 www 7184: # --------------------------------------------------------------- Clean-up symb
7185:
7186: sub symbclean {
7187: my $symb=shift;
1.568 albertel 7188: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 7189: # remove version from map
7190: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 7191:
1.210 www 7192: # remove version from URL
7193: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 7194:
1.507 www 7195: # remove wrapper
7196:
1.510 www 7197: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 7198: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 7199: return $symb;
1.409 www 7200: }
7201:
7202: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 7203:
7204: sub encode_symb {
7205: my ($map,$resid,$url)=@_;
7206: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
7207: }
1.409 www 7208:
7209: sub decode_symb {
1.568 albertel 7210: my $symb=shift;
7211: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
7212: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 7213: return (&fixversion($map),$resid,&fixversion($url));
7214: }
7215:
7216: sub fixversion {
7217: my $fn=shift;
1.609 banghart 7218: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 7219: my %bighash;
7220: my $uri=&clutter($fn);
1.620 albertel 7221: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 7222: # is this cached?
1.599 albertel 7223: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 7224: if (defined($cached)) { return $result; }
7225: # unfortunately not cached, or expired
1.620 albertel 7226: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 7227: &GDBM_READER(),0640)) {
7228: if ($bighash{'version_'.$uri}) {
7229: my $version=$bighash{'version_'.$uri};
1.444 www 7230: unless (($version eq 'mostrecent') ||
7231: ($version==&getversion($uri))) {
1.440 www 7232: $uri=~s/\.(\w+)$/\.$version\.$1/;
7233: }
7234: }
7235: untie %bighash;
1.413 www 7236: }
1.599 albertel 7237: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 7238: }
7239:
7240: sub deversion {
7241: my $url=shift;
7242: $url=~s/\.\d+\.(\w+)$/\.$1/;
7243: return $url;
1.210 www 7244: }
7245:
1.31 www 7246: # ------------------------------------------------------ Return symb list entry
7247:
7248: sub symbread {
1.249 www 7249: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 7250: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 7251: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 7252: # no filename provided? try from environment
1.44 www 7253: unless ($thisfn) {
1.620 albertel 7254: if ($env{'request.symb'}) {
7255: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 7256: }
1.620 albertel 7257: $thisfn=$env{'request.filename'};
1.44 www 7258: }
1.569 albertel 7259: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 7260: # is that filename actually a symb? Verify, clean, and return
7261: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 7262: if (&symbverify($thisfn,$1)) {
1.620 albertel 7263: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 7264: }
1.242 www 7265: }
1.44 www 7266: $thisfn=declutter($thisfn);
1.31 www 7267: my %hash;
1.37 www 7268: my %bighash;
7269: my $syval='';
1.620 albertel 7270: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 7271: my $targetfn = $thisfn;
1.609 banghart 7272: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 7273: $targetfn = 'adm/wrapper/'.$thisfn;
7274: }
1.687 albertel 7275: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
7276: $targetfn=$1;
7277: }
1.620 albertel 7278: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7279: &GDBM_READER(),0640)) {
1.481 raeburn 7280: $syval=$hash{$targetfn};
1.37 www 7281: untie(%hash);
7282: }
7283: # ---------------------------------------------------------- There was an entry
7284: if ($syval) {
1.601 albertel 7285: #unless ($syval=~/\_\d+$/) {
1.620 albertel 7286: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601 albertel 7287: #&appenv('request.ambiguous' => $thisfn);
1.620 albertel 7288: #return $env{$cache_str}='';
1.601 albertel 7289: #}
7290: #$syval.=$1;
7291: #}
1.37 www 7292: } else {
7293: # ------------------------------------------------------- Was not in symb table
1.620 albertel 7294: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7295: &GDBM_READER(),0640)) {
1.37 www 7296: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 7297: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 7298: unless ($ids) {
7299: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 7300: }
7301: unless ($ids) {
7302: # alias?
7303: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 7304: }
1.37 www 7305: if ($ids) {
7306: # ------------------------------------------------------------------- Has ID(s)
7307: my @possibilities=split(/\,/,$ids);
1.39 www 7308: if ($#possibilities==0) {
7309: # ----------------------------------------------- There is only one possibility
1.37 www 7310: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 7311: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7312: $resid,$thisfn);
1.249 www 7313: } elsif (!$donotrecurse) {
1.39 www 7314: # ------------------------------------------ There is more than one possibility
7315: my $realpossible=0;
1.800 albertel 7316: foreach my $id (@possibilities) {
7317: my $file=$bighash{'src_'.$id};
1.39 www 7318: if (&allowed('bre',$file)) {
1.800 albertel 7319: my ($mapid,$resid)=split(/\./,$id);
1.39 www 7320: if ($bighash{'map_type_'.$mapid} ne 'page') {
7321: $realpossible++;
1.626 albertel 7322: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7323: $resid,$thisfn);
1.39 www 7324: }
7325: }
1.191 harris41 7326: }
1.39 www 7327: if ($realpossible!=1) { $syval=''; }
1.249 www 7328: } else {
7329: $syval='';
1.37 www 7330: }
7331: }
7332: untie(%bighash)
1.481 raeburn 7333: }
1.31 www 7334: }
1.62 www 7335: if ($syval) {
1.620 albertel 7336: return $env{$cache_str}=$syval;
1.62 www 7337: }
1.31 www 7338: }
1.44 www 7339: &appenv('request.ambiguous' => $thisfn);
1.620 albertel 7340: return $env{$cache_str}='';
1.31 www 7341: }
7342:
7343: # ---------------------------------------------------------- Return random seed
7344:
1.32 www 7345: sub numval {
7346: my $txt=shift;
7347: $txt=~tr/A-J/0-9/;
7348: $txt=~tr/a-j/0-9/;
7349: $txt=~tr/K-T/0-9/;
7350: $txt=~tr/k-t/0-9/;
7351: $txt=~tr/U-Z/0-5/;
7352: $txt=~tr/u-z/0-5/;
7353: $txt=~s/\D//g;
1.564 albertel 7354: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 7355: return int($txt);
1.368 albertel 7356: }
7357:
1.484 albertel 7358: sub numval2 {
7359: my $txt=shift;
7360: $txt=~tr/A-J/0-9/;
7361: $txt=~tr/a-j/0-9/;
7362: $txt=~tr/K-T/0-9/;
7363: $txt=~tr/k-t/0-9/;
7364: $txt=~tr/U-Z/0-5/;
7365: $txt=~tr/u-z/0-5/;
7366: $txt=~s/\D//g;
7367: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7368: my $total;
7369: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 7370: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 7371: return int($total);
7372: }
7373:
1.575 albertel 7374: sub numval3 {
7375: use integer;
7376: my $txt=shift;
7377: $txt=~tr/A-J/0-9/;
7378: $txt=~tr/a-j/0-9/;
7379: $txt=~tr/K-T/0-9/;
7380: $txt=~tr/k-t/0-9/;
7381: $txt=~tr/U-Z/0-5/;
7382: $txt=~tr/u-z/0-5/;
7383: $txt=~s/\D//g;
7384: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7385: my $total;
7386: foreach my $val (@txts) { $total+=$val; }
7387: if ($_64bit) { $total=(($total<<32)>>32); }
7388: return $total;
7389: }
7390:
1.675 albertel 7391: sub digest {
7392: my ($data)=@_;
7393: my $digest=&Digest::MD5::md5($data);
7394: my ($a,$b,$c,$d)=unpack("iiii",$digest);
7395: my ($e,$f);
7396: {
7397: use integer;
7398: $e=($a+$b);
7399: $f=($c+$d);
7400: if ($_64bit) {
7401: $e=(($e<<32)>>32);
7402: $f=(($f<<32)>>32);
7403: }
7404: }
7405: if (wantarray) {
7406: return ($e,$f);
7407: } else {
7408: my $g;
7409: {
7410: use integer;
7411: $g=($e+$f);
7412: if ($_64bit) {
7413: $g=(($g<<32)>>32);
7414: }
7415: }
7416: return $g;
7417: }
7418: }
7419:
1.368 albertel 7420: sub latest_rnd_algorithm_id {
1.675 albertel 7421: return '64bit5';
1.366 albertel 7422: }
1.32 www 7423:
1.503 albertel 7424: sub get_rand_alg {
7425: my ($courseid)=@_;
1.790 albertel 7426: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 7427: if ($courseid) {
1.620 albertel 7428: return $env{"course.$courseid.rndseed"};
1.503 albertel 7429: }
7430: return &latest_rnd_algorithm_id();
7431: }
7432:
1.562 albertel 7433: sub validCODE {
7434: my ($CODE)=@_;
7435: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
7436: return 0;
7437: }
7438:
1.491 albertel 7439: sub getCODE {
1.620 albertel 7440: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 7441: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
7442: defined($Apache::lonhomework::parsing_a_task) ) &&
7443: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 7444: return $Apache::lonhomework::history{'resource.CODE'};
7445: }
7446: return undef;
7447: }
7448:
1.31 www 7449: sub rndseed {
1.155 albertel 7450: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 7451: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 7452: if (!defined($symb)) {
1.366 albertel 7453: unless ($symb=$wsymb) { return time; }
7454: }
7455: if (!$courseid) { $courseid=$wcourseid; }
7456: if (!$domain) { $domain=$wdomain; }
7457: if (!$username) { $username=$wusername }
1.503 albertel 7458: my $which=&get_rand_alg();
1.803 albertel 7459:
1.491 albertel 7460: if (defined(&getCODE())) {
1.675 albertel 7461: if ($which eq '64bit5') {
7462: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
7463: } elsif ($which eq '64bit4') {
1.575 albertel 7464: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
7465: } else {
7466: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
7467: }
1.675 albertel 7468: } elsif ($which eq '64bit5') {
7469: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 7470: } elsif ($which eq '64bit4') {
7471: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 7472: } elsif ($which eq '64bit3') {
7473: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 7474: } elsif ($which eq '64bit2') {
7475: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 7476: } elsif ($which eq '64bit') {
7477: return &rndseed_64bit($symb,$courseid,$domain,$username);
7478: }
7479: return &rndseed_32bit($symb,$courseid,$domain,$username);
7480: }
7481:
7482: sub rndseed_32bit {
7483: my ($symb,$courseid,$domain,$username)=@_;
7484: {
7485: use integer;
7486: my $symbchck=unpack("%32C*",$symb) << 27;
7487: my $symbseed=numval($symb) << 22;
7488: my $namechck=unpack("%32C*",$username) << 17;
7489: my $nameseed=numval($username) << 12;
7490: my $domainseed=unpack("%32C*",$domain) << 7;
7491: my $courseseed=unpack("%32C*",$courseid);
7492: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 7493: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7494: #&logthis("rndseed :$num:$symb");
1.564 albertel 7495: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 7496: return $num;
7497: }
7498: }
7499:
7500: sub rndseed_64bit {
7501: my ($symb,$courseid,$domain,$username)=@_;
7502: {
7503: use integer;
7504: my $symbchck=unpack("%32S*",$symb) << 21;
7505: my $symbseed=numval($symb) << 10;
7506: my $namechck=unpack("%32S*",$username);
7507:
7508: my $nameseed=numval($username) << 21;
7509: my $domainseed=unpack("%32S*",$domain) << 10;
7510: my $courseseed=unpack("%32S*",$courseid);
7511:
7512: my $num1=$symbchck+$symbseed+$namechck;
7513: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7514: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7515: #&logthis("rndseed :$num:$symb");
1.564 albertel 7516: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 7517: return "$num1,$num2";
1.155 albertel 7518: }
1.366 albertel 7519: }
7520:
1.443 albertel 7521: sub rndseed_64bit2 {
7522: my ($symb,$courseid,$domain,$username)=@_;
7523: {
7524: use integer;
7525: # strings need to be an even # of cahracters long, it it is odd the
7526: # last characters gets thrown away
7527: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7528: my $symbseed=numval($symb) << 10;
7529: my $namechck=unpack("%32S*",$username.' ');
7530:
7531: my $nameseed=numval($username) << 21;
1.501 albertel 7532: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7533: my $courseseed=unpack("%32S*",$courseid.' ');
7534:
7535: my $num1=$symbchck+$symbseed+$namechck;
7536: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7537: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7538: #&logthis("rndseed :$num:$symb");
1.803 albertel 7539: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 7540: return "$num1,$num2";
7541: }
7542: }
7543:
7544: sub rndseed_64bit3 {
7545: my ($symb,$courseid,$domain,$username)=@_;
7546: {
7547: use integer;
7548: # strings need to be an even # of cahracters long, it it is odd the
7549: # last characters gets thrown away
7550: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7551: my $symbseed=numval2($symb) << 10;
7552: my $namechck=unpack("%32S*",$username.' ');
7553:
7554: my $nameseed=numval2($username) << 21;
1.443 albertel 7555: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7556: my $courseseed=unpack("%32S*",$courseid.' ');
7557:
7558: my $num1=$symbchck+$symbseed+$namechck;
7559: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7560: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7561: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 7562: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7563:
1.503 albertel 7564: return "$num1:$num2";
1.443 albertel 7565: }
7566: }
7567:
1.575 albertel 7568: sub rndseed_64bit4 {
7569: my ($symb,$courseid,$domain,$username)=@_;
7570: {
7571: use integer;
7572: # strings need to be an even # of cahracters long, it it is odd the
7573: # last characters gets thrown away
7574: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7575: my $symbseed=numval3($symb) << 10;
7576: my $namechck=unpack("%32S*",$username.' ');
7577:
7578: my $nameseed=numval3($username) << 21;
7579: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7580: my $courseseed=unpack("%32S*",$courseid.' ');
7581:
7582: my $num1=$symbchck+$symbseed+$namechck;
7583: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7584: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7585: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 7586: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7587:
7588: return "$num1:$num2";
7589: }
7590: }
7591:
1.675 albertel 7592: sub rndseed_64bit5 {
7593: my ($symb,$courseid,$domain,$username)=@_;
7594: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
7595: return "$num1:$num2";
7596: }
7597:
1.366 albertel 7598: sub rndseed_CODE_64bit {
7599: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 7600: {
1.366 albertel 7601: use integer;
1.443 albertel 7602: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 7603: my $symbseed=numval2($symb);
1.491 albertel 7604: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7605: my $CODEseed=numval(&getCODE());
1.443 albertel 7606: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 7607: my $num1=$symbseed+$CODEchck;
7608: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7609: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7610: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 7611: if ($_64bit) { $num1=(($num1<<32)>>32); }
7612: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 7613: return "$num1:$num2";
1.366 albertel 7614: }
7615: }
7616:
1.575 albertel 7617: sub rndseed_CODE_64bit4 {
7618: my ($symb,$courseid,$domain,$username)=@_;
7619: {
7620: use integer;
7621: my $symbchck=unpack("%32S*",$symb.' ') << 16;
7622: my $symbseed=numval3($symb);
7623: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7624: my $CODEseed=numval3(&getCODE());
7625: my $courseseed=unpack("%32S*",$courseid.' ');
7626: my $num1=$symbseed+$CODEchck;
7627: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7628: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7629: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 7630: if ($_64bit) { $num1=(($num1<<32)>>32); }
7631: if ($_64bit) { $num2=(($num2<<32)>>32); }
7632: return "$num1:$num2";
7633: }
7634: }
7635:
1.675 albertel 7636: sub rndseed_CODE_64bit5 {
7637: my ($symb,$courseid,$domain,$username)=@_;
7638: my $code = &getCODE();
7639: my ($num1,$num2)=&digest("$symb,$courseid,$code");
7640: return "$num1:$num2";
7641: }
7642:
1.366 albertel 7643: sub setup_random_from_rndseed {
7644: my ($rndseed)=@_;
1.503 albertel 7645: if ($rndseed =~/([,:])/) {
7646: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 7647: &Math::Random::random_set_seed(abs($num1),abs($num2));
7648: } else {
7649: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 7650: }
1.36 albertel 7651: }
7652:
1.474 albertel 7653: sub latest_receipt_algorithm_id {
1.835 albertel 7654: return 'receipt3';
1.474 albertel 7655: }
7656:
1.480 www 7657: sub recunique {
7658: my $fucourseid=shift;
7659: my $unique;
1.835 albertel 7660: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
7661: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7662: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 7663: } else {
7664: $unique=$perlvar{'lonReceipt'};
7665: }
7666: return unpack("%32C*",$unique);
7667: }
7668:
7669: sub recprefix {
7670: my $fucourseid=shift;
7671: my $prefix;
1.835 albertel 7672: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
7673: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7674: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 7675: } else {
7676: $prefix=$perlvar{'lonHostID'};
7677: }
7678: return unpack("%32C*",$prefix);
7679: }
7680:
1.76 www 7681: sub ireceipt {
1.474 albertel 7682: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 7683:
7684: my $return =&recprefix($fucourseid).'-';
7685:
7686: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
7687: $env{'request.state'} eq 'construct') {
7688: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
7689: return $return;
7690: }
7691:
1.76 www 7692: my $cuname=unpack("%32C*",$funame);
7693: my $cudom=unpack("%32C*",$fudom);
7694: my $cucourseid=unpack("%32C*",$fucourseid);
7695: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 7696: my $cunique=&recunique($fucourseid);
1.474 albertel 7697: my $cpart=unpack("%32S*",$part);
1.835 albertel 7698: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
7699:
1.790 albertel 7700: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 7701:
7702: $return.= ($cunique%$cuname+
7703: $cunique%$cudom+
7704: $cusymb%$cuname+
7705: $cusymb%$cudom+
7706: $cucourseid%$cuname+
7707: $cucourseid%$cudom+
7708: $cpart%$cuname+
7709: $cpart%$cudom);
7710: } else {
7711: $return.= ($cunique%$cuname+
7712: $cunique%$cudom+
7713: $cusymb%$cuname+
7714: $cusymb%$cudom+
7715: $cucourseid%$cuname+
7716: $cucourseid%$cudom);
7717: }
7718: return $return;
1.76 www 7719: }
7720:
7721: sub receipt {
1.474 albertel 7722: my ($part)=@_;
1.790 albertel 7723: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 7724: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 7725: }
1.260 ng 7726:
1.790 albertel 7727: sub whichuser {
7728: my ($passedsymb)=@_;
7729: my ($symb,$courseid,$domain,$name,$publicuser);
7730: if (defined($env{'form.grade_symb'})) {
7731: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
7732: my $allowed=&allowed('vgr',$tmp_courseid);
7733: if (!$allowed &&
7734: exists($env{'request.course.sec'}) &&
7735: $env{'request.course.sec'} !~ /^\s*$/) {
7736: $allowed=&allowed('vgr',$tmp_courseid.
7737: '/'.$env{'request.course.sec'});
7738: }
7739: if ($allowed) {
7740: ($symb)=&get_env_multiple('form.grade_symb');
7741: $courseid=$tmp_courseid;
7742: ($domain)=&get_env_multiple('form.grade_domain');
7743: ($name)=&get_env_multiple('form.grade_username');
7744: return ($symb,$courseid,$domain,$name,$publicuser);
7745: }
7746: }
7747: if (!$passedsymb) {
7748: $symb=&symbread();
7749: } else {
7750: $symb=$passedsymb;
7751: }
7752: $courseid=$env{'request.course.id'};
7753: $domain=$env{'user.domain'};
7754: $name=$env{'user.name'};
7755: if ($name eq 'public' && $domain eq 'public') {
7756: if (!defined($env{'form.username'})) {
7757: $env{'form.username'}.=time.rand(10000000);
7758: }
7759: $name.=$env{'form.username'};
7760: }
7761: return ($symb,$courseid,$domain,$name,$publicuser);
7762:
7763: }
7764:
1.36 albertel 7765: # ------------------------------------------------------------ Serves up a file
1.472 albertel 7766: # returns either the contents of the file or
7767: # -1 if the file doesn't exist
1.481 raeburn 7768: #
7769: # if the target is a file that was uploaded via DOCS,
7770: # a check will be made to see if a current copy exists on the local server,
7771: # if it does this will be served, otherwise a copy will be retrieved from
7772: # the home server for the course and stored in /home/httpd/html/userfiles on
7773: # the local server.
1.472 albertel 7774:
1.36 albertel 7775: sub getfile {
1.538 albertel 7776: my ($file) = @_;
1.609 banghart 7777: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 7778: &repcopy($file);
7779: return &readfile($file);
7780: }
7781:
7782: sub repcopy_userfile {
7783: my ($file)=@_;
1.609 banghart 7784: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 7785: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 7786: my ($cdom,$cnum,$filename) =
1.811 albertel 7787: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 7788: my $uri="/uploaded/$cdom/$cnum/$filename";
7789: if (-e "$file") {
1.828 www 7790: # we already have a local copy, check it out
1.538 albertel 7791: my @fileinfo = stat($file);
1.828 www 7792: my $rtncode;
7793: my $info;
1.538 albertel 7794: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 7795: if ($lwpresp ne 'ok') {
1.828 www 7796: # there is no such file anymore, even though we had a local copy
1.482 albertel 7797: if ($rtncode eq '404') {
1.538 albertel 7798: unlink($file);
1.482 albertel 7799: }
7800: return -1;
7801: }
7802: if ($info < $fileinfo[9]) {
1.828 www 7803: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 7804: return 'ok';
1.828 www 7805: } else {
7806: # the file is outdated, get rid of it
7807: unlink($file);
1.482 albertel 7808: }
1.828 www 7809: }
7810: # one way or the other, at this point, we don't have the file
7811: # construct the correct path for the file
7812: my @parts = ($cdom,$cnum);
7813: if ($filename =~ m|^(.+)/[^/]+$|) {
7814: push @parts, split(/\//,$1);
7815: }
7816: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
7817: foreach my $part (@parts) {
7818: $path .= '/'.$part;
7819: if (!-e $path) {
7820: mkdir($path,0770);
1.482 albertel 7821: }
7822: }
1.828 www 7823: # now the path exists for sure
7824: # get a user agent
7825: my $ua=new LWP::UserAgent;
7826: my $transferfile=$file.'.in.transfer';
7827: # FIXME: this should flock
7828: if (-e $transferfile) { return 'ok'; }
7829: my $request;
7830: $uri=~s/^\///;
1.838 albertel 7831: $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828 www 7832: my $response=$ua->request($request,$transferfile);
7833: # did it work?
7834: if ($response->is_error()) {
7835: unlink($transferfile);
7836: &logthis("Userfile repcopy failed for $uri");
7837: return -1;
7838: }
7839: # worked, rename the transfer file
7840: rename($transferfile,$file);
1.607 raeburn 7841: return 'ok';
1.481 raeburn 7842: }
7843:
1.517 albertel 7844: sub tokenwrapper {
7845: my $uri=shift;
1.552 albertel 7846: $uri=~s|^http\://([^/]+)||;
7847: $uri=~s|^/||;
1.620 albertel 7848: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 7849: my $token=$1;
1.552 albertel 7850: my (undef,$udom,$uname,$file)=split('/',$uri,4);
7851: if ($udom && $uname && $file) {
7852: $file=~s|(\?\.*)*$||;
1.620 albertel 7853: &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838 albertel 7854: return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517 albertel 7855: (($uri=~/\?/)?'&':'?').'token='.$token.
7856: '&tokenissued='.$perlvar{'lonHostID'};
7857: } else {
7858: return '/adm/notfound.html';
7859: }
7860: }
7861:
1.828 www 7862: # call with reqtype HEAD: get last modification time
7863: # call with reqtype GET: get the file contents
7864: # Do not call this with reqtype GET for large files! It loads everything into memory
7865: #
1.481 raeburn 7866: sub getuploaded {
7867: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
7868: $uri=~s/^\///;
1.838 albertel 7869: $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481 raeburn 7870: my $ua=new LWP::UserAgent;
7871: my $request=new HTTP::Request($reqtype,$uri);
7872: my $response=$ua->request($request);
7873: $$rtncode = $response->code;
1.482 albertel 7874: if (! $response->is_success()) {
7875: return 'failed';
7876: }
7877: if ($reqtype eq 'HEAD') {
1.486 www 7878: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 7879: } elsif ($reqtype eq 'GET') {
7880: $$info = $response->content;
1.472 albertel 7881: }
1.482 albertel 7882: return 'ok';
1.36 albertel 7883: }
7884:
1.481 raeburn 7885: sub readfile {
7886: my $file = shift;
7887: if ( (! -e $file ) || ($file eq '') ) { return -1; };
7888: my $fh;
7889: open($fh,"<$file");
7890: my $a='';
1.800 albertel 7891: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 7892: return $a;
7893: }
7894:
1.36 albertel 7895: sub filelocation {
1.590 banghart 7896: my ($dir,$file) = @_;
7897: my $location;
7898: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 7899:
7900: if ($file =~ m-^/adm/-) {
7901: $file=~s-^/adm/wrapper/-/-;
7902: $file=~s-^/adm/coursedocs/showdoc/-/-;
7903: }
1.882 albertel 7904:
1.590 banghart 7905: if ($file=~m:^/~:) { # is a contruction space reference
7906: $location = $file;
7907: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 7908: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 7909: # is a correct contruction space reference
7910: $location = $file;
1.609 banghart 7911: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 7912: my ($udom,$uname,$filename)=
1.811 albertel 7913: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 7914: my $home=&homeserver($uname,$udom);
7915: my $is_me=0;
7916: my @ids=¤t_machine_ids();
7917: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
7918: if ($is_me) {
1.740 www 7919: $location=&propath($udom,$uname).
1.590 banghart 7920: '/userfiles/'.$filename;
7921: } else {
7922: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
7923: $udom.'/'.$uname.'/'.$filename;
7924: }
1.882 albertel 7925: } elsif ($file =~ m-^/adm/-) {
7926: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 7927: } else {
7928: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
7929: $file=~s:^/res/:/:;
7930: if ( !( $file =~ m:^/:) ) {
7931: $location = $dir. '/'.$file;
7932: } else {
7933: $location = '/home/httpd/html/res'.$file;
7934: }
1.59 albertel 7935: }
1.590 banghart 7936: $location=~s://+:/:g; # remove duplicate /
7937: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
7938: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
7939: return $location;
1.46 www 7940: }
1.36 albertel 7941:
1.46 www 7942: sub hreflocation {
7943: my ($dir,$file)=@_;
1.460 albertel 7944: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666 albertel 7945: $file=filelocation($dir,$file);
1.700 albertel 7946: } elsif ($file=~m-^/adm/-) {
7947: $file=~s-^/adm/wrapper/-/-;
7948: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 7949: }
7950: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
7951: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 7952: } elsif ($file=~m-/home/($match_username)/public_html/-) {
7953: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 7954: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 7955: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 7956: -/uploaded/$1/$2/-x;
1.46 www 7957: }
1.913 albertel 7958: if ($file=~ m{^/userfiles/}) {
7959: $file =~ s{^/userfiles/}{/uploaded/};
7960: }
1.462 albertel 7961: return $file;
1.465 albertel 7962: }
7963:
7964: sub current_machine_domains {
1.853 albertel 7965: return &machine_domains(&hostname($perlvar{'lonHostID'}));
7966: }
7967:
7968: sub machine_domains {
7969: my ($hostname) = @_;
1.465 albertel 7970: my @domains;
1.838 albertel 7971: my %hostname = &all_hostnames();
1.465 albertel 7972: while( my($id, $name) = each(%hostname)) {
1.467 matthew 7973: # &logthis("-$id-$name-$hostname-");
1.465 albertel 7974: if ($hostname eq $name) {
1.844 albertel 7975: push(@domains,&host_domain($id));
1.465 albertel 7976: }
7977: }
7978: return @domains;
7979: }
7980:
7981: sub current_machine_ids {
1.853 albertel 7982: return &machine_ids(&hostname($perlvar{'lonHostID'}));
7983: }
7984:
7985: sub machine_ids {
7986: my ($hostname) = @_;
7987: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 7988: my @ids;
1.888 albertel 7989: my %name_to_host = &all_names();
1.889 albertel 7990: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
7991: return @{ $name_to_host{$hostname} };
7992: }
7993: return;
1.31 www 7994: }
7995:
1.824 raeburn 7996: sub additional_machine_domains {
7997: my @domains;
7998: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
7999: while( my $line = <$fh>) {
8000: $line =~ s/\s//g;
8001: push(@domains,$line);
8002: }
8003: return @domains;
8004: }
8005:
8006: sub default_login_domain {
8007: my $domain = $perlvar{'lonDefDomain'};
8008: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
8009: foreach my $posdom (¤t_machine_domains(),
8010: &additional_machine_domains()) {
8011: if (lc($posdom) eq lc($testdomain)) {
8012: $domain=$posdom;
8013: last;
8014: }
8015: }
8016: return $domain;
8017: }
8018:
1.31 www 8019: # ------------------------------------------------------------- Declutters URLs
8020:
8021: sub declutter {
8022: my $thisfn=shift;
1.569 albertel 8023: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 8024: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 8025: $thisfn=~s/^\///;
1.697 albertel 8026: $thisfn=~s|^adm/wrapper/||;
8027: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 8028: $thisfn=~s/^res\///;
1.235 www 8029: $thisfn=~s/\?.+$//;
1.268 www 8030: return $thisfn;
8031: }
8032:
8033: # ------------------------------------------------------------- Clutter up URLs
8034:
8035: sub clutter {
8036: my $thisfn='/'.&declutter(shift);
1.887 albertel 8037: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 8038: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 8039: $thisfn='/res'.$thisfn;
8040: }
1.694 albertel 8041: if ($thisfn !~m|/adm|) {
1.695 albertel 8042: if ($thisfn =~ m|/ext/|) {
1.694 albertel 8043: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 8044: } else {
8045: my ($ext) = ($thisfn =~ /\.(\w+)$/);
8046: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 8047: if ($embstyle eq 'ssi'
8048: || ($embstyle eq 'hdn')
8049: || ($embstyle eq 'rat')
8050: || ($embstyle eq 'prv')
8051: || ($embstyle eq 'ign')) {
8052: #do nothing with these
8053: } elsif (($embstyle eq 'img')
1.695 albertel 8054: || ($embstyle eq 'emb')
8055: || ($embstyle eq 'wrp')) {
8056: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 8057: } elsif ($embstyle eq 'unk'
8058: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 8059: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 8060: } else {
1.718 www 8061: # &logthis("Got a blank emb style");
1.695 albertel 8062: }
1.694 albertel 8063: }
8064: }
1.31 www 8065: return $thisfn;
1.12 www 8066: }
8067:
1.787 albertel 8068: sub clutter_with_no_wrapper {
8069: my $uri = &clutter(shift);
8070: if ($uri =~ m-^/adm/-) {
8071: $uri =~ s-^/adm/wrapper/-/-;
8072: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
8073: }
8074: return $uri;
8075: }
8076:
1.557 albertel 8077: sub freeze_escape {
8078: my ($value)=@_;
8079: if (ref($value)) {
8080: $value=&nfreeze($value);
8081: return '__FROZEN__'.&escape($value);
8082: }
8083: return &escape($value);
8084: }
8085:
1.11 www 8086:
1.557 albertel 8087: sub thaw_unescape {
8088: my ($value)=@_;
8089: if ($value =~ /^__FROZEN__/) {
8090: substr($value,0,10,undef);
8091: $value=&unescape($value);
8092: return &thaw($value);
8093: }
8094: return &unescape($value);
8095: }
8096:
1.436 albertel 8097: sub correct_line_ends {
8098: my ($result)=@_;
8099: $$result =~s/\r\n/\n/mg;
8100: $$result =~s/\r/\n/mg;
1.415 albertel 8101: }
1.1 albertel 8102: # ================================================================ Main Program
8103:
1.184 www 8104: sub goodbye {
1.204 albertel 8105: &logthis("Starting Shut down");
1.443 albertel 8106: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 8107: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 8108: #converted
1.599 albertel 8109: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 8110: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
8111: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
8112: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 8113: #1.1 only
1.870 albertel 8114: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
8115: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
8116: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
8117: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
8118: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 8119: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
8120: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 8121: &flushcourselogs();
8122: &logthis("Shutting down");
8123: }
8124:
1.852 albertel 8125: sub get_dns {
1.869 albertel 8126: my ($url,$func,$ignore_cache) = @_;
8127: if (!$ignore_cache) {
8128: my ($content,$cached)=
8129: &Apache::lonnet::is_cached_new('dns',$url);
8130: if ($cached) {
8131: &$func($content);
8132: return;
8133: }
8134: }
8135:
8136: my %alldns;
1.852 albertel 8137: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8138: foreach my $dns (<$config>) {
8139: next if ($dns !~ /^\^(\S*)/x);
1.869 albertel 8140: $alldns{$1} = 1;
8141: }
8142: while (%alldns) {
8143: my ($dns) = keys(%alldns);
8144: delete($alldns{$dns});
1.852 albertel 8145: my $ua=new LWP::UserAgent;
8146: my $request=new HTTP::Request('GET',"http://$dns$url");
8147: my $response=$ua->request($request);
8148: next if ($response->is_error());
8149: my @content = split("\n",$response->content);
1.869 albertel 8150: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 8151: &$func(\@content);
1.869 albertel 8152: return;
1.852 albertel 8153: }
8154: close($config);
1.871 albertel 8155: my $which = (split('/',$url))[3];
8156: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
8157: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 8158: my @content = <$config>;
8159: &$func(\@content);
8160: return;
1.852 albertel 8161: }
1.327 albertel 8162: # ------------------------------------------------------------ Read domain file
8163: {
1.852 albertel 8164: my $loaded;
1.846 albertel 8165: my %domain;
8166:
1.852 albertel 8167: sub parse_domain_tab {
8168: my ($lines) = @_;
8169: foreach my $line (@$lines) {
8170: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 8171:
1.846 albertel 8172: chomp($line);
1.852 albertel 8173: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 8174: my %this_domain;
8175: foreach my $field ('description', 'auth_def', 'auth_arg_def',
8176: 'lang_def', 'city', 'longi', 'lati',
8177: 'primary') {
8178: $this_domain{$field} = shift(@elements);
8179: }
8180: $domain{$name} = \%this_domain;
1.852 albertel 8181: }
8182: }
1.864 albertel 8183:
8184: sub reset_domain_info {
8185: undef($loaded);
8186: undef(%domain);
8187: }
8188:
1.852 albertel 8189: sub load_domain_tab {
1.869 albertel 8190: my ($ignore_cache) = @_;
8191: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 8192: my $fh;
8193: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
8194: my @lines = <$fh>;
8195: &parse_domain_tab(\@lines);
1.448 albertel 8196: }
1.852 albertel 8197: close($fh);
8198: $loaded = 1;
1.327 albertel 8199: }
1.846 albertel 8200:
8201: sub domain {
1.852 albertel 8202: &load_domain_tab() if (!$loaded);
8203:
1.846 albertel 8204: my ($name,$what) = @_;
8205: return if ( !exists($domain{$name}) );
8206:
8207: if (!$what) {
8208: return $domain{$name}{'description'};
8209: }
8210: return $domain{$name}{$what};
8211: }
1.327 albertel 8212: }
8213:
8214:
1.1 albertel 8215: # ------------------------------------------------------------- Read hosts file
8216: {
1.838 albertel 8217: my %hostname;
1.844 albertel 8218: my %hostdom;
1.845 albertel 8219: my %libserv;
1.852 albertel 8220: my $loaded;
1.888 albertel 8221: my %name_to_host;
1.852 albertel 8222:
8223: sub parse_hosts_tab {
8224: my ($file) = @_;
8225: foreach my $configline (@$file) {
8226: next if ($configline =~ /^(\#|\s*$ )/x);
8227: next if ($configline =~ /^\^/);
8228: chomp($configline);
8229: my ($id,$domain,$role,$name)=split(/:/,$configline);
8230: $name=~s/\s//g;
8231: if ($id && $domain && $role && $name) {
8232: $hostname{$id}=$name;
1.888 albertel 8233: push(@{$name_to_host{$name}}, $id);
1.852 albertel 8234: $hostdom{$id}=$domain;
8235: if ($role eq 'library') { $libserv{$id}=$name; }
8236: }
8237: }
8238: }
1.864 albertel 8239:
8240: sub reset_hosts_info {
1.897 albertel 8241: &purge_remembered();
1.864 albertel 8242: &reset_domain_info();
8243: &reset_hosts_ip_info();
1.892 albertel 8244: undef(%name_to_host);
1.864 albertel 8245: undef(%hostname);
8246: undef(%hostdom);
8247: undef(%libserv);
8248: undef($loaded);
8249: }
1.1 albertel 8250:
1.852 albertel 8251: sub load_hosts_tab {
1.869 albertel 8252: my ($ignore_cache) = @_;
8253: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 8254: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8255: my @config = <$config>;
8256: &parse_hosts_tab(\@config);
8257: close($config);
8258: $loaded=1;
1.1 albertel 8259: }
1.852 albertel 8260:
1.838 albertel 8261: sub hostname {
1.852 albertel 8262: &load_hosts_tab() if (!$loaded);
8263:
1.838 albertel 8264: my ($lonid) = @_;
8265: return $hostname{$lonid};
8266: }
1.845 albertel 8267:
1.838 albertel 8268: sub all_hostnames {
1.852 albertel 8269: &load_hosts_tab() if (!$loaded);
8270:
1.838 albertel 8271: return %hostname;
8272: }
1.845 albertel 8273:
1.888 albertel 8274: sub all_names {
8275: &load_hosts_tab() if (!$loaded);
8276:
8277: return %name_to_host;
8278: }
8279:
1.845 albertel 8280: sub is_library {
1.852 albertel 8281: &load_hosts_tab() if (!$loaded);
8282:
1.845 albertel 8283: return exists($libserv{$_[0]});
8284: }
8285:
8286: sub all_library {
1.852 albertel 8287: &load_hosts_tab() if (!$loaded);
8288:
1.845 albertel 8289: return %libserv;
8290: }
8291:
1.841 albertel 8292: sub get_servers {
1.852 albertel 8293: &load_hosts_tab() if (!$loaded);
8294:
1.841 albertel 8295: my ($domain,$type) = @_;
8296: my %possible_hosts = ($type eq 'library') ? %libserv
8297: : %hostname;
8298: my %result;
1.842 albertel 8299: if (ref($domain) eq 'ARRAY') {
8300: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 8301: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 8302: $result{$host} = $hostname;
8303: }
8304: }
8305: } else {
8306: while ( my ($host,$hostname) = each(%possible_hosts)) {
8307: if ($hostdom{$host} eq $domain) {
8308: $result{$host} = $hostname;
8309: }
1.841 albertel 8310: }
8311: }
8312: return %result;
8313: }
1.845 albertel 8314:
1.844 albertel 8315: sub host_domain {
1.852 albertel 8316: &load_hosts_tab() if (!$loaded);
8317:
1.844 albertel 8318: my ($lonid) = @_;
8319: return $hostdom{$lonid};
8320: }
8321:
1.841 albertel 8322: sub all_domains {
1.852 albertel 8323: &load_hosts_tab() if (!$loaded);
8324:
1.841 albertel 8325: my %seen;
8326: my @uniq = grep(!$seen{$_}++, values(%hostdom));
8327: return @uniq;
8328: }
1.1 albertel 8329: }
8330:
1.847 albertel 8331: {
8332: my %iphost;
1.856 albertel 8333: my %name_to_ip;
8334: my %lonid_to_ip;
1.869 albertel 8335:
1.847 albertel 8336: sub get_hosts_from_ip {
8337: my ($ip) = @_;
8338: my %iphosts = &get_iphost();
8339: if (ref($iphosts{$ip})) {
8340: return @{$iphosts{$ip}};
8341: }
8342: return;
1.839 albertel 8343: }
1.864 albertel 8344:
8345: sub reset_hosts_ip_info {
8346: undef(%iphost);
8347: undef(%name_to_ip);
8348: undef(%lonid_to_ip);
8349: }
1.856 albertel 8350:
8351: sub get_host_ip {
8352: my ($lonid) = @_;
8353: if (exists($lonid_to_ip{$lonid})) {
8354: return $lonid_to_ip{$lonid};
8355: }
8356: my $name=&hostname($lonid);
8357: my $ip = gethostbyname($name);
8358: return if (!$ip || length($ip) ne 4);
8359: $ip=inet_ntoa($ip);
8360: $name_to_ip{$name} = $ip;
8361: $lonid_to_ip{$lonid} = $ip;
8362: return $ip;
8363: }
1.847 albertel 8364:
8365: sub get_iphost {
1.869 albertel 8366: my ($ignore_cache) = @_;
1.894 albertel 8367:
1.869 albertel 8368: if (!$ignore_cache) {
8369: if (%iphost) {
8370: return %iphost;
8371: }
8372: my ($ip_info,$cached)=
8373: &Apache::lonnet::is_cached_new('iphost','iphost');
8374: if ($cached) {
8375: %iphost = %{$ip_info->[0]};
8376: %name_to_ip = %{$ip_info->[1]};
8377: %lonid_to_ip = %{$ip_info->[2]};
8378: return %iphost;
8379: }
8380: }
1.894 albertel 8381:
8382: # get yesterday's info for fallback
8383: my %old_name_to_ip;
8384: my ($ip_info,$cached)=
8385: &Apache::lonnet::is_cached_new('iphost','iphost');
8386: if ($cached) {
8387: %old_name_to_ip = %{$ip_info->[1]};
8388: }
8389:
1.888 albertel 8390: my %name_to_host = &all_names();
8391: foreach my $name (keys(%name_to_host)) {
1.847 albertel 8392: my $ip;
8393: if (!exists($name_to_ip{$name})) {
8394: $ip = gethostbyname($name);
8395: if (!$ip || length($ip) ne 4) {
1.894 albertel 8396: if (defined($old_name_to_ip{$name})) {
8397: $ip = $old_name_to_ip{$name};
8398: &logthis("Can't find $name defaulting to old $ip");
8399: } else {
8400: &logthis("Name $name no IP found");
8401: next;
8402: }
8403: } else {
8404: $ip=inet_ntoa($ip);
1.847 albertel 8405: }
8406: $name_to_ip{$name} = $ip;
8407: } else {
8408: $ip = $name_to_ip{$name};
1.653 albertel 8409: }
1.888 albertel 8410: foreach my $id (@{ $name_to_host{$name} }) {
8411: $lonid_to_ip{$id} = $ip;
8412: }
8413: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 8414: }
1.869 albertel 8415: &Apache::lonnet::do_cache_new('iphost','iphost',
8416: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 8417: 48*60*60);
1.869 albertel 8418:
1.847 albertel 8419: return %iphost;
1.598 albertel 8420: }
8421: }
8422:
1.862 albertel 8423: BEGIN {
8424:
8425: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
8426: unless ($readit) {
8427: {
8428: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
8429: %perlvar = (%perlvar,%{$configvars});
8430: }
8431:
8432:
1.1 albertel 8433: # ------------------------------------------------------ Read spare server file
8434: {
1.448 albertel 8435: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 8436:
8437: while (my $configline=<$config>) {
8438: chomp($configline);
1.284 matthew 8439: if ($configline) {
1.784 albertel 8440: my ($host,$type) = split(':',$configline,2);
1.785 albertel 8441: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 8442: push(@{ $spareid{$type} }, $host);
1.1 albertel 8443: }
8444: }
1.448 albertel 8445: close($config);
1.1 albertel 8446: }
1.11 www 8447: # ------------------------------------------------------------ Read permissions
8448: {
1.448 albertel 8449: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 8450:
8451: while (my $configline=<$config>) {
1.448 albertel 8452: chomp($configline);
8453: if ($configline) {
8454: my ($role,$perm)=split(/ /,$configline);
8455: if ($perm ne '') { $pr{$role}=$perm; }
8456: }
1.11 www 8457: }
1.448 albertel 8458: close($config);
1.11 www 8459: }
8460:
8461: # -------------------------------------------- Read plain texts for permissions
8462: {
1.448 albertel 8463: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 8464:
8465: while (my $configline=<$config>) {
1.448 albertel 8466: chomp($configline);
8467: if ($configline) {
1.742 raeburn 8468: my ($short,@plain)=split(/:/,$configline);
8469: %{$prp{$short}} = ();
8470: if (@plain > 0) {
8471: $prp{$short}{'std'} = $plain[0];
8472: for (my $i=1; $i<@plain; $i++) {
8473: $prp{$short}{'alt'.$i} = $plain[$i];
8474: }
8475: }
1.448 albertel 8476: }
1.135 www 8477: }
1.448 albertel 8478: close($config);
1.135 www 8479: }
8480:
8481: # ---------------------------------------------------------- Read package table
8482: {
1.448 albertel 8483: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 8484:
8485: while (my $configline=<$config>) {
1.483 albertel 8486: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 8487: chomp($configline);
8488: my ($short,$plain)=split(/:/,$configline);
8489: my ($pack,$name)=split(/\&/,$short);
8490: if ($plain ne '') {
8491: $packagetab{$pack.'&'.$name.'&name'}=$name;
8492: $packagetab{$short}=$plain;
8493: }
1.11 www 8494: }
1.448 albertel 8495: close($config);
1.329 matthew 8496: }
8497:
8498: # ------------- set up temporary directory
8499: {
8500: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
8501:
1.11 www 8502: }
8503:
1.794 albertel 8504: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
8505: 'compress_threshold'=> 20_000,
8506: });
1.185 www 8507:
1.281 www 8508: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 8509: $dumpcount=0;
1.22 www 8510:
1.163 harris41 8511: &logtouch();
1.672 albertel 8512: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 8513: $readit=1;
1.564 albertel 8514: {
8515: use integer;
8516: my $test=(2**32)+1;
1.568 albertel 8517: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 8518: &logthis(" Detected 64bit platform ($_64bit)");
8519: }
1.195 www 8520: }
1.1 albertel 8521: }
1.179 www 8522:
1.1 albertel 8523: 1;
1.191 harris41 8524: __END__
8525:
1.243 albertel 8526: =pod
8527:
1.191 harris41 8528: =head1 NAME
8529:
1.243 albertel 8530: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 8531:
8532: =head1 SYNOPSIS
8533:
1.243 albertel 8534: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 8535:
8536: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
8537:
1.243 albertel 8538: Common parameters:
8539:
8540: =over 4
8541:
8542: =item *
8543:
8544: $uname : an internal username (if $cname expecting a course Id specifically)
8545:
8546: =item *
8547:
8548: $udom : a domain (if $cdom expecting a course's domain specifically)
8549:
8550: =item *
8551:
8552: $symb : a resource instance identifier
8553:
8554: =item *
8555:
8556: $namespace : the name of a .db file that contains the data needed or
8557: being set.
8558:
8559: =back
8560:
1.394 bowersj2 8561: =head1 OVERVIEW
1.191 harris41 8562:
1.394 bowersj2 8563: lonnet provides subroutines which interact with the
8564: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
8565: about classes, users, and resources.
1.243 albertel 8566:
8567: For many of these objects you can also use this to store data about
8568: them or modify them in various ways.
1.191 harris41 8569:
1.394 bowersj2 8570: =head2 Symbs
1.191 harris41 8571:
1.394 bowersj2 8572: To identify a specific instance of a resource, LON-CAPA uses symbols
8573: or "symbs"X<symb>. These identifiers are built from the URL of the
8574: map, the resource number of the resource in the map, and the URL of
8575: the resource itself. The latter is somewhat redundant, but might help
8576: if maps change.
8577:
8578: An example is
8579:
8580: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
8581:
8582: The respective map entry is
8583:
8584: <resource id="19" src="/res/msu/korte/tests/part12.problem"
8585: title="Problem 2">
8586: </resource>
8587:
8588: Symbs are used by the random number generator, as well as to store and
8589: restore data specific to a certain instance of for example a problem.
8590:
8591: =head2 Storing And Retrieving Data
8592:
8593: X<store()>X<cstore()>X<restore()>Three of the most important functions
8594: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
8595: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
8596: is is the non-critical message twin of cstore. These functions are for
8597: handlers to store a perl hash to a user's permanent data space in an
8598: easy manner, and to retrieve it again on another call. It is expected
8599: that a handler would use this once at the beginning to retrieve data,
8600: and then again once at the end to send only the new data back.
8601:
8602: The data is stored in the user's data directory on the user's
8603: homeserver under the ID of the course.
8604:
8605: The hash that is returned by restore will have all of the previous
8606: value for all of the elements of the hash.
8607:
8608: Example:
8609:
8610: #creating a hash
8611: my %hash;
8612: $hash{'foo'}='bar';
8613:
8614: #storing it
8615: &Apache::lonnet::cstore(\%hash);
8616:
8617: #changing a value
8618: $hash{'foo'}='notbar';
8619:
8620: #adding a new value
8621: $hash{'bar'}='foo';
8622: &Apache::lonnet::cstore(\%hash);
8623:
8624: #retrieving the hash
8625: my %history=&Apache::lonnet::restore();
8626:
8627: #print the hash
8628: foreach my $key (sort(keys(%history))) {
8629: print("\%history{$key} = $history{$key}");
8630: }
8631:
8632: Will print out:
1.191 harris41 8633:
1.394 bowersj2 8634: %history{1:foo} = bar
8635: %history{1:keys} = foo:timestamp
8636: %history{1:timestamp} = 990455579
8637: %history{2:bar} = foo
8638: %history{2:foo} = notbar
8639: %history{2:keys} = foo:bar:timestamp
8640: %history{2:timestamp} = 990455580
8641: %history{bar} = foo
8642: %history{foo} = notbar
8643: %history{timestamp} = 990455580
8644: %history{version} = 2
8645:
8646: Note that the special hash entries C<keys>, C<version> and
8647: C<timestamp> were added to the hash. C<version> will be equal to the
8648: total number of versions of the data that have been stored. The
8649: C<timestamp> attribute will be the UNIX time the hash was
8650: stored. C<keys> is available in every historical section to list which
8651: keys were added or changed at a specific historical revision of a
8652: hash.
8653:
8654: B<Warning>: do not store the hash that restore returns directly. This
8655: will cause a mess since it will restore the historical keys as if the
8656: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 8657:
1.394 bowersj2 8658: Calling convention:
1.191 harris41 8659:
1.394 bowersj2 8660: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
8661: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 8662:
1.394 bowersj2 8663: For more detailed information, see lonnet specific documentation.
1.191 harris41 8664:
1.394 bowersj2 8665: =head1 RETURN MESSAGES
1.191 harris41 8666:
1.394 bowersj2 8667: =over 4
1.191 harris41 8668:
1.394 bowersj2 8669: =item * B<con_lost>: unable to contact remote host
1.191 harris41 8670:
1.394 bowersj2 8671: =item * B<con_delayed>: unable to contact remote host, message will be delivered
8672: when the connection is brought back up
1.191 harris41 8673:
1.394 bowersj2 8674: =item * B<con_failed>: unable to contact remote host and unable to save message
8675: for later delivery
1.191 harris41 8676:
1.394 bowersj2 8677: =item * B<error:>: an error a occured, a description of the error follows the :
1.191 harris41 8678:
1.394 bowersj2 8679: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 8680: that was requested
1.191 harris41 8681:
1.243 albertel 8682: =back
1.191 harris41 8683:
1.243 albertel 8684: =head1 PUBLIC SUBROUTINES
1.191 harris41 8685:
1.243 albertel 8686: =head2 Session Environment Functions
1.191 harris41 8687:
1.243 albertel 8688: =over 4
1.191 harris41 8689:
1.394 bowersj2 8690: =item *
8691: X<appenv()>
8692: B<appenv(%hash)>: the value of %hash is written to
8693: the user envirnoment file, and will be restored for each access this
1.620 albertel 8694: user makes during this session, also modifies the %env for the current
1.394 bowersj2 8695: process
1.191 harris41 8696:
8697: =item *
1.394 bowersj2 8698: X<delenv()>
8699: B<delenv($regexp)>: removes all items from the session
8700: environment file that matches the regular expression in $regexp. The
1.620 albertel 8701: values are also delted from the current processes %env.
1.191 harris41 8702:
1.795 albertel 8703: =item * get_env_multiple($name)
8704:
8705: gets $name from the %env hash, it seemlessly handles the cases where multiple
8706: values may be defined and end up as an array ref.
8707:
8708: returns an array of values
8709:
1.243 albertel 8710: =back
8711:
8712: =head2 User Information
1.191 harris41 8713:
1.243 albertel 8714: =over 4
1.191 harris41 8715:
8716: =item *
1.394 bowersj2 8717: X<queryauthenticate()>
8718: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 8719: authentication scheme
8720:
8721: =item *
1.394 bowersj2 8722: X<authenticate()>
8723: B<authenticate($uname,$upass,$udom)>: try to
8724: authenticate user from domain's lib servers (first use the current
8725: one). C<$upass> should be the users password.
1.191 harris41 8726:
8727: =item *
1.394 bowersj2 8728: X<homeserver()>
8729: B<homeserver($uname,$udom)>: find the server which has
8730: the user's directory and files (there must be only one), this caches
8731: the answer, and also caches if there is a borken connection.
1.191 harris41 8732:
8733: =item *
1.394 bowersj2 8734: X<idget()>
8735: B<idget($udom,@ids)>: find the usernames behind a list of IDs
8736: (IDs are a unique resource in a domain, there must be only 1 ID per
8737: username, and only 1 username per ID in a specific domain) (returns
8738: hash: id=>name,id=>name)
1.191 harris41 8739:
8740: =item *
1.394 bowersj2 8741: X<idrget()>
8742: B<idrget($udom,@unames)>: find the IDs behind a list of
8743: usernames (returns hash: name=>id,name=>id)
1.191 harris41 8744:
8745: =item *
1.394 bowersj2 8746: X<idput()>
8747: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 8748:
8749: =item *
1.394 bowersj2 8750: X<rolesinit()>
8751: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 8752:
8753: =item *
1.551 albertel 8754: X<getsection()>
8755: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 8756: course $cname, return section name/number or '' for "not in course"
8757: and '-1' for "no section"
8758:
8759: =item *
1.394 bowersj2 8760: X<userenvironment()>
8761: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 8762: passed in @what from the requested user's environment, returns a hash
8763:
1.858 raeburn 8764: =item *
8765: X<userlog_query()>
1.859 albertel 8766: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
8767: activity.log file. %filters defines filters applied when parsing the
8768: log file. These can be start or end timestamps, or the type of action
8769: - log to look for Login or Logout events, check for Checkin or
8770: Checkout, role for role selection. The response is in the form
8771: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
8772: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 8773:
1.243 albertel 8774: =back
8775:
8776: =head2 User Roles
8777:
8778: =over 4
8779:
8780: =item *
8781:
1.810 raeburn 8782: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 8783: F: full access
8784: U,I,K: authentication modes (cxx only)
8785: '': forbidden
8786: 1: user needs to choose course
8787: 2: browse allowed
1.766 albertel 8788: A: passphrase authentication needed
1.243 albertel 8789:
8790: =item *
8791:
8792: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
8793: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
8794: and course level
8795:
8796: =item *
8797:
8798: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
8799: explanation of a user role term
8800:
1.832 raeburn 8801: =item *
8802:
1.858 raeburn 8803: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
8804: All arguments are optional. Returns a hash of a roles, either for
8805: co-author/assistant author roles for a user's Construction Space
1.906 albertel 8806: (default), or if $context is 'userroles', roles for the user himself,
1.858 raeburn 8807: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
8808: and value is set to colon-separated start and end times for the role.
8809: If no username and domain are specified, will default to current
8810: user/domain. Types, roles, and roledoms are references to arrays,
8811: of role statuses (active, future or previous), roles
8812: (e.g., cc,in, st etc.) and domains of the roles which can be used
8813: to restrict the list of roles reported. If no array ref is
8814: provided for types, will default to return only active roles.
1.834 albertel 8815:
1.243 albertel 8816: =back
8817:
8818: =head2 User Modification
8819:
8820: =over 4
8821:
8822: =item *
8823:
8824: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
8825: user for the level given by URL. Optional start and end dates (leave empty
8826: string or zero for "no date")
1.191 harris41 8827:
8828: =item *
8829:
1.243 albertel 8830: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
8831: change a users, password, possible return values are: ok,
8832: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
8833: refused
1.191 harris41 8834:
8835: =item *
8836:
1.243 albertel 8837: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 8838:
8839: =item *
8840:
1.243 albertel 8841: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
8842: modify user
1.191 harris41 8843:
8844: =item *
8845:
1.286 matthew 8846: modifystudent
8847:
8848: modify a students enrollment and identification information.
8849: The course id is resolved based on the current users environment.
8850: This means the envoking user must be a course coordinator or otherwise
8851: associated with a course.
8852:
1.297 matthew 8853: This call is essentially a wrapper for lonnet::modifyuser and
8854: lonnet::modify_student_enrollment
1.286 matthew 8855:
8856: Inputs:
8857:
8858: =over 4
8859:
8860: =item B<$udom> Students loncapa domain
8861:
8862: =item B<$uname> Students loncapa login name
8863:
8864: =item B<$uid> Students id/student number
8865:
8866: =item B<$umode> Students authentication mode
8867:
8868: =item B<$upass> Students password
8869:
8870: =item B<$first> Students first name
8871:
8872: =item B<$middle> Students middle name
8873:
8874: =item B<$last> Students last name
8875:
8876: =item B<$gene> Students generation
8877:
8878: =item B<$usec> Students section in course
8879:
8880: =item B<$end> Unix time of the roles expiration
8881:
8882: =item B<$start> Unix time of the roles start date
8883:
8884: =item B<$forceid> If defined, allow $uid to be changed
8885:
8886: =item B<$desiredhome> server to use as home server for student
8887:
8888: =back
1.297 matthew 8889:
8890: =item *
8891:
8892: modify_student_enrollment
8893:
8894: Change a students enrollment status in a class. The environment variable
8895: 'role.request.course' must be defined for this function to proceed.
8896:
8897: Inputs:
8898:
8899: =over 4
8900:
8901: =item $udom, students domain
8902:
8903: =item $uname, students name
8904:
8905: =item $uid, students user id
8906:
8907: =item $first, students first name
8908:
8909: =item $middle
8910:
8911: =item $last
8912:
8913: =item $gene
8914:
8915: =item $usec
8916:
8917: =item $end
8918:
8919: =item $start
8920:
8921: =back
8922:
1.191 harris41 8923:
8924: =item *
8925:
1.243 albertel 8926: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
8927: custom role; give a custom role to a user for the level given by URL. Specify
8928: name and domain of role author, and role name
1.191 harris41 8929:
8930: =item *
8931:
1.243 albertel 8932: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 8933:
8934: =item *
8935:
1.243 albertel 8936: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
8937:
8938: =back
8939:
8940: =head2 Course Infomation
8941:
8942: =over 4
1.191 harris41 8943:
8944: =item *
8945:
1.631 albertel 8946: coursedescription($courseid) : returns a hash of information about the
8947: specified course id, including all environment settings for the
8948: course, the description of the course will be in the hash under the
8949: key 'description'
1.191 harris41 8950:
8951: =item *
8952:
1.624 albertel 8953: resdata($name,$domain,$type,@which) : request for current parameter
8954: setting for a specific $type, where $type is either 'course' or 'user',
8955: @what should be a list of parameters to ask about. This routine caches
8956: answers for 5 minutes.
1.243 albertel 8957:
1.877 foxr 8958: =item *
8959:
8960: get_courseresdata($courseid, $domain) : dump the entire course resource
8961: data base, returning a hash that is keyed by the resource name and has
8962: values that are the resource value. I believe that the timestamps and
8963: versions are also returned.
8964:
8965:
1.243 albertel 8966: =back
8967:
8968: =head2 Course Modification
8969:
8970: =over 4
1.191 harris41 8971:
8972: =item *
8973:
1.243 albertel 8974: writecoursepref($courseid,%prefs) : write preferences (environment
8975: database) for a course
1.191 harris41 8976:
8977: =item *
8978:
1.243 albertel 8979: createcourse($udom,$description,$url) : make/modify course
8980:
8981: =back
8982:
8983: =head2 Resource Subroutines
8984:
8985: =over 4
1.191 harris41 8986:
8987: =item *
8988:
1.243 albertel 8989: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 8990:
8991: =item *
8992:
1.243 albertel 8993: repcopy($filename) : subscribes to the requested file, and attempts to
8994: replicate from the owning library server, Might return
1.607 raeburn 8995: 'unavailable', 'not_found', 'forbidden', 'ok', or
8996: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 8997: resource. Expects the local filesystem pathname
8998: (/home/httpd/html/res/....)
8999:
9000: =back
9001:
9002: =head2 Resource Information
9003:
9004: =over 4
1.191 harris41 9005:
9006: =item *
9007:
1.243 albertel 9008: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
9009: a vairety of different possible values, $varname should be a request
9010: string, and the other parameters can be used to specify who and what
9011: one is asking about.
9012:
9013: Possible values for $varname are environment.lastname (or other item
9014: from the envirnment hash), user.name (or someother aspect about the
9015: user), resource.0.maxtries (or some other part and parameter of a
9016: resource)
1.204 albertel 9017:
9018: =item *
9019:
1.243 albertel 9020: directcondval($number) : get current value of a condition; reads from a state
9021: string
1.204 albertel 9022:
9023: =item *
9024:
1.243 albertel 9025: condval($condidx) : value of condition index based on state
1.204 albertel 9026:
9027: =item *
9028:
1.243 albertel 9029: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
9030: resource's metadata, $what should be either a specific key, or either
9031: 'keys' (to get a list of possible keys) or 'packages' to get a list of
9032: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
9033:
9034: this function automatically caches all requests
1.191 harris41 9035:
9036: =item *
9037:
1.243 albertel 9038: metadata_query($query,$custom,$customshow) : make a metadata query against the
9039: network of library servers; returns file handle of where SQL and regex results
9040: will be stored for query
1.191 harris41 9041:
9042: =item *
9043:
1.243 albertel 9044: symbread($filename) : return symbolic list entry (filename argument optional);
9045: returns the data handle
1.191 harris41 9046:
9047: =item *
9048:
1.243 albertel 9049: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 9050: a possible symb for the URL in $thisfn, and if is an encryypted
9051: resource that the user accessed using /enc/ returns a 1 on success, 0
9052: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 9053: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 9054:
1.191 harris41 9055:
9056: =item *
9057:
1.243 albertel 9058: symbclean($symb) : removes versions numbers from a symb, returns the
9059: cleaned symb
1.191 harris41 9060:
9061: =item *
9062:
1.243 albertel 9063: is_on_map($uri) : checks if the $uri is somewhere on the current
9064: course map, user must be in a course for it to work.
1.191 harris41 9065:
9066: =item *
9067:
1.243 albertel 9068: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 9069:
9070: =item *
9071:
1.243 albertel 9072: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
9073: a random seed, all arguments are optional, if they aren't sent it uses the
9074: environment to derive them. Note: if symb isn't sent and it can't get one
9075: from &symbread it will use the current time as its return value
1.191 harris41 9076:
9077: =item *
9078:
1.243 albertel 9079: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
9080: unfakeable, receipt
1.191 harris41 9081:
9082: =item *
9083:
1.620 albertel 9084: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 9085:
9086: =item *
9087:
1.243 albertel 9088: countacc($url) : count the number of accesses to a given URL
1.191 harris41 9089:
9090: =item *
9091:
1.243 albertel 9092: 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 9093:
9094: =item *
9095:
1.243 albertel 9096: 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 9097:
9098: =item *
9099:
1.243 albertel 9100: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 9101:
9102: =item *
9103:
1.243 albertel 9104: devalidate($symb) : devalidate temporary spreadsheet calculations,
9105: forcing spreadsheet to reevaluate the resource scores next time.
9106:
9107: =back
9108:
9109: =head2 Storing/Retreiving Data
9110:
9111: =over 4
1.191 harris41 9112:
9113: =item *
9114:
1.243 albertel 9115: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
9116: for this url; hashref needs to be given and should be a \%hashname; the
9117: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 9118: be derived from the env
1.191 harris41 9119:
9120: =item *
9121:
1.243 albertel 9122: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
9123: uses critical subroutine
1.191 harris41 9124:
9125: =item *
9126:
1.243 albertel 9127: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
9128: all args are optional
1.191 harris41 9129:
9130: =item *
9131:
1.717 albertel 9132: dumpstore($namespace,$udom,$uname,$regexp,$range) :
9133: dumps the complete (or key matching regexp) namespace into a hash
9134: ($udom, $uname, $regexp, $range are optional) for a namespace that is
9135: normally &store()ed into
9136:
9137: $range should be either an integer '100' (give me the first 100
9138: matching records)
9139: or be two integers sperated by a - with no spaces
9140: '30-50' (give me the 30th through the 50th matching
9141: records)
9142:
9143:
9144: =item *
9145:
9146: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
9147: replaces a &store() version of data with a replacement set of data
9148: for a particular resource in a namespace passed in the $storehash hash
9149: reference
9150:
9151: =item *
9152:
1.243 albertel 9153: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
9154: works very similar to store/cstore, but all data is stored in a
9155: temporary location and can be reset using tmpreset, $storehash should
9156: be a hash reference, returns nothing on success
1.191 harris41 9157:
9158: =item *
9159:
1.243 albertel 9160: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
9161: similar to restore, but all data is stored in a temporary location and
9162: can be reset using tmpreset. Returns a hash of values on success,
9163: error string otherwise.
1.191 harris41 9164:
9165: =item *
9166:
1.243 albertel 9167: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
9168: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 9169:
9170: =item *
9171:
1.243 albertel 9172: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9173: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 9174:
9175: =item *
9176:
1.243 albertel 9177: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
9178: namesp ($udom and $uname are optional)
1.191 harris41 9179:
9180: =item *
9181:
1.702 albertel 9182: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 9183: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 9184: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 9185:
1.702 albertel 9186: $range should be either an integer '100' (give me the first 100
9187: matching records)
9188: or be two integers sperated by a - with no spaces
9189: '30-50' (give me the 30th through the 50th matching
9190: records)
1.449 matthew 9191: =item *
9192:
9193: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
9194: $store can be a scalar, an array reference, or if the amount to be
9195: incremented is > 1, a hash reference.
9196:
9197: ($udom and $uname are optional)
1.191 harris41 9198:
9199: =item *
9200:
1.243 albertel 9201: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
9202: ($udom and $uname are optional)
1.191 harris41 9203:
9204: =item *
9205:
1.243 albertel 9206: cput($namespace,$storehash,$udom,$uname) : critical put
9207: ($udom and $uname are optional)
1.191 harris41 9208:
9209: =item *
9210:
1.748 albertel 9211: newput($namespace,$storehash,$udom,$uname) :
9212:
9213: Attempts to store the items in the $storehash, but only if they don't
9214: currently exist, if this succeeds you can be certain that you have
9215: successfully created a new key value pair in the $namespace db.
9216:
9217:
9218: Args:
9219: $namespace: name of database to store values to
9220: $storehash: hashref to store to the db
9221: $udom: (optional) domain of user containing the db
9222: $uname: (optional) name of user caontaining the db
9223:
9224: Returns:
9225: 'ok' -> succeeded in storing all keys of $storehash
9226: 'key_exists: <key>' -> failed to anything out of $storehash, as at
9227: least <key> already existed in the db (other
9228: requested keys may also already exist)
9229: 'error: <msg>' -> unable to tie the DB or other erorr occured
9230: 'con_lost' -> unable to contact request server
9231: 'refused' -> action was not allowed by remote machine
9232:
9233:
9234: =item *
9235:
1.243 albertel 9236: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9237: reference filled in from namesp (encrypts the return communication)
9238: ($udom and $uname are optional)
1.191 harris41 9239:
9240: =item *
9241:
1.243 albertel 9242: log($udom,$name,$home,$message) : write to permanent log for user; use
9243: critical subroutine
9244:
1.806 raeburn 9245: =item *
9246:
1.860 raeburn 9247: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
9248: array reference filled in from namespace found in domain level on either
9249: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 9250:
9251: =item *
9252:
1.860 raeburn 9253: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
9254: domain level either on specified domain server ($uhome) or primary domain
9255: server ($udom and $uhome are optional)
1.806 raeburn 9256:
1.243 albertel 9257: =back
9258:
9259: =head2 Network Status Functions
9260:
9261: =over 4
1.191 harris41 9262:
9263: =item *
9264:
9265: dirlist($uri) : return directory list based on URI
9266:
9267: =item *
9268:
1.243 albertel 9269: spareserver() : find server with least workload from spare.tab
9270:
9271: =back
9272:
9273: =head2 Apache Request
9274:
9275: =over 4
1.191 harris41 9276:
9277: =item *
9278:
1.243 albertel 9279: ssi($url,%hash) : server side include, does a complete request cycle on url to
9280: localhost, posts hash
9281:
9282: =back
9283:
9284: =head2 Data to String to Data
9285:
9286: =over 4
1.191 harris41 9287:
9288: =item *
9289:
1.243 albertel 9290: hash2str(%hash) : convert a hash into a string complete with escaping and '='
9291: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 9292:
9293: =item *
9294:
1.243 albertel 9295: hashref2str($hashref) : convert a hashref into a string complete with
9296: escaping and '=' and '&' separators, supports elements that are
9297: arrayrefs and hashrefs
1.191 harris41 9298:
9299: =item *
9300:
1.243 albertel 9301: arrayref2str($arrayref) : convert an arrayref into a string complete
9302: with escaping and '&' separators, supports elements that are arrayrefs
9303: and hashrefs
1.191 harris41 9304:
9305: =item *
9306:
1.243 albertel 9307: str2hash($string) : convert string to hash using unescaping and
9308: splitting on '=' and '&', supports elements that are arrayrefs and
9309: hashrefs
1.191 harris41 9310:
9311: =item *
9312:
1.243 albertel 9313: str2array($string) : convert string to hash using unescaping and
9314: splitting on '&', supports elements that are arrayrefs and hashrefs
9315:
9316: =back
9317:
9318: =head2 Logging Routines
9319:
9320: =over 4
9321:
9322: These routines allow one to make log messages in the lonnet.log and
9323: lonnet.perm logfiles.
1.191 harris41 9324:
9325: =item *
9326:
1.243 albertel 9327: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 9328:
9329: =item *
9330:
1.243 albertel 9331: logthis() : append message to the normal lonnet.log file, it gets
9332: preiodically rolled over and deleted.
1.191 harris41 9333:
9334: =item *
9335:
1.243 albertel 9336: logperm() : append a permanent message to lonnet.perm.log, this log
9337: file never gets deleted by any automated portion of the system, only
9338: messages of critical importance should go in here.
9339:
9340: =back
9341:
9342: =head2 General File Helper Routines
9343:
9344: =over 4
1.191 harris41 9345:
9346: =item *
9347:
1.481 raeburn 9348: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
9349: (a) files in /uploaded
9350: (i) If a local copy of the file exists -
9351: compares modification date of local copy with last-modified date for
9352: definitive version stored on home server for course. If local copy is
9353: stale, requests a new version from the home server and stores it.
9354: If the original has been removed from the home server, then local copy
9355: is unlinked.
9356: (ii) If local copy does not exist -
9357: requests the file from the home server and stores it.
9358:
9359: If $caller is 'uploadrep':
9360: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
9361: for request for files originally uploaded via DOCS.
9362: - returns 'ok' if fresh local copy now available, -1 otherwise.
9363:
9364: Otherwise:
9365: This indicates a call from the content generation phase of the request.
9366: - returns the entire contents of the file or -1.
9367:
9368: (b) files in /res
9369: - returns the entire contents of a file or -1;
9370: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 9371:
1.712 albertel 9372:
9373: =item *
9374:
9375: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
9376: reference
9377:
9378: returns either a stat() list of data about the file or an empty list
9379: if the file doesn't exist or couldn't find out about it (connection
9380: problems or user unknown)
9381:
1.191 harris41 9382: =item *
9383:
1.243 albertel 9384: filelocation($dir,$file) : returns file system location of a file
9385: based on URI; meant to be "fairly clean" absolute reference, $dir is a
9386: directory that relative $file lookups are to looked in ($dir of /a/dir
9387: and a file of ../bob will become /a/bob)
1.191 harris41 9388:
9389: =item *
9390:
9391: hreflocation($dir,$file) : returns file system location or a URL; same as
9392: filelocation except for hrefs
9393:
9394: =item *
9395:
9396: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
9397:
1.243 albertel 9398: =back
9399:
1.608 albertel 9400: =head2 Usererfile file routines (/uploaded*)
9401:
9402: =over 4
9403:
9404: =item *
9405:
9406: userfileupload(): main rotine for putting a file in a user or course's
9407: filespace, arguments are,
9408:
1.620 albertel 9409: formname - required - this is the name of the element in $env where the
1.608 albertel 9410: filename, and the contents of the file to create/modifed exist
1.620 albertel 9411: the filename is in $env{'form.'.$formname.'.filename'} and the
9412: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 9413: coursedoc - if true, store the file in the course of the active role
9414: of the current user
9415: subdir - required - subdirectory to put the file in under ../userfiles/
9416: if undefined, it will be placed in "unknown"
9417:
9418: (This routine calls clean_filename() to remove any dangerous
9419: characters from the filename, and then calls finuserfileupload() to
9420: complete the transaction)
9421:
9422: returns either the url of the uploaded file (/uploaded/....) if successful
9423: and /adm/notfound.html if unsuccessful
9424:
9425: =item *
9426:
9427: clean_filename(): routine for cleaing a filename up for storage in
9428: userfile space, argument is:
9429:
9430: filename - proposed filename
9431:
9432: returns: the new clean filename
9433:
9434: =item *
9435:
9436: finishuserfileupload(): routine that creaes and sends the file to
9437: userspace, probably shouldn't be called directly
9438:
9439: docuname: username or courseid of destination for the file
9440: docudom: domain of user/course of destination for the file
9441: formname: same as for userfileupload()
9442: fname: filename (inculding subdirectories) for the file
9443:
9444: returns either the url of the uploaded file (/uploaded/....) if successful
9445: and /adm/notfound.html if unsuccessful
9446:
9447: =item *
9448:
9449: renameuserfile(): renames an existing userfile to a new name
9450:
9451: Args:
9452: docuname: username or courseid of destination for the file
9453: docudom: domain of user/course of destination for the file
9454: old: current file name (including any subdirs under userfiles)
9455: new: desired file name (including any subdirs under userfiles)
9456:
9457: =item *
9458:
9459: mkdiruserfile(): creates a directory is a userfiles dir
9460:
9461: Args:
9462: docuname: username or courseid of destination for the file
9463: docudom: domain of user/course of destination for the file
9464: dir: dir to create (including any subdirs under userfiles)
9465:
9466: =item *
9467:
9468: removeuserfile(): removes a file that exists in userfiles
9469:
9470: Args:
9471: docuname: username or courseid of destination for the file
9472: docudom: domain of user/course of destination for the file
9473: fname: filname to delete (including any subdirs under userfiles)
9474:
9475: =item *
9476:
9477: removeuploadedurl(): convience function for removeuserfile()
9478:
9479: Args:
9480: url: a full /uploaded/... url to delete
9481:
1.747 albertel 9482: =item *
9483:
9484: get_portfile_permissions():
9485: Args:
9486: domain: domain of user or course contain the portfolio files
9487: user: name of user or num of course contain the portfolio files
9488: Returns:
9489: hashref of a dump of the proper file_permissions.db
9490:
9491:
9492: =item *
9493:
9494: get_access_controls():
9495:
9496: Args:
9497: current_permissions: the hash ref returned from get_portfile_permissions()
9498: group: (optional) the group you want the files associated with
9499: file: (optional) the file you want access info on
9500:
9501: Returns:
1.749 raeburn 9502: a hash (keys are file names) of hashes containing
9503: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
9504: values are XML containing access control settings (see below)
1.747 albertel 9505:
9506: Internal notes:
9507:
1.749 raeburn 9508: access controls are stored in file_permissions.db as key=value pairs.
9509: key -> path to file/file_name\0uniqueID:scope_end_start
9510: where scope -> public,guest,course,group,domains or users.
9511: end -> UNIX time for end of access (0 -> no end date)
9512: start -> UNIX time for start of access
9513:
9514: value -> XML description of access control
9515: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
9516: <start></start>
9517: <end></end>
9518:
9519: <password></password> for scope type = guest
9520:
9521: <domain></domain> for scope type = course or group
9522: <number></number>
9523: <roles id="">
9524: <role></role>
9525: <access></access>
9526: <section></section>
9527: <group></group>
9528: </roles>
9529:
9530: <dom></dom> for scope type = domains
9531:
9532: <users> for scope type = users
9533: <user>
9534: <uname></uname>
9535: <udom></udom>
9536: </user>
9537: </users>
9538: </scope>
9539:
9540: Access data is also aggregated for each file in an additional key=value pair:
9541: key -> path to file/file_name\0accesscontrol
9542: value -> reference to hash
9543: hash contains key = value pairs
9544: where key = uniqueID:scope_end_start
9545: value = UNIX time record was last updated
9546:
9547: Used to improve speed of look-ups of access controls for each file.
9548:
9549: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
9550:
9551: modify_access_controls():
9552:
9553: Modifies access controls for a portfolio file
9554: Args
9555: 1. file name
9556: 2. reference to hash of required changes,
9557: 3. domain
9558: 4. username
9559: where domain,username are the domain of the portfolio owner
9560: (either a user or a course)
9561:
9562: Returns:
9563: 1. result of additions or updates ('ok' or 'error', with error message).
9564: 2. result of deletions ('ok' or 'error', with error message).
9565: 3. reference to hash of any new or updated access controls.
9566: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
9567: key = integer (inbound ID)
9568: value = uniqueID
1.747 albertel 9569:
1.608 albertel 9570: =back
9571:
1.243 albertel 9572: =head2 HTTP Helper Routines
9573:
9574: =over 4
9575:
1.191 harris41 9576: =item *
9577:
9578: escape() : unpack non-word characters into CGI-compatible hex codes
9579:
9580: =item *
9581:
9582: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
9583:
1.243 albertel 9584: =back
9585:
9586: =head1 PRIVATE SUBROUTINES
9587:
9588: =head2 Underlying communication routines (Shouldn't call)
9589:
9590: =over 4
9591:
9592: =item *
9593:
9594: subreply() : tries to pass a message to lonc, returns con_lost if incapable
9595:
9596: =item *
9597:
9598: reply() : uses subreply to send a message to remote machine, logs all failures
9599:
9600: =item *
9601:
9602: critical() : passes a critical message to another server; if cannot
9603: get through then place message in connection buffer directory and
9604: returns con_delayed, if incapable of saving message, returns
9605: con_failed
9606:
9607: =item *
9608:
9609: reconlonc() : tries to reconnect lonc client processes.
9610:
9611: =back
9612:
9613: =head2 Resource Access Logging
9614:
9615: =over 4
9616:
9617: =item *
9618:
9619: flushcourselogs() : flush (save) buffer logs and access logs
9620:
9621: =item *
9622:
9623: courselog($what) : save message for course in hash
9624:
9625: =item *
9626:
9627: courseacclog($what) : save message for course using &courselog(). Perform
9628: special processing for specific resource types (problems, exams, quizzes, etc).
9629:
1.191 harris41 9630: =item *
9631:
9632: goodbye() : flush course logs and log shutting down; it is called in srm.conf
9633: as a PerlChildExitHandler
1.243 albertel 9634:
9635: =back
9636:
9637: =head2 Other
9638:
9639: =over 4
9640:
9641: =item *
9642:
9643: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 9644:
9645: =back
9646:
9647: =cut
1.877 foxr 9648:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>