Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.920
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.920 ! raeburn 4: # $Id: lonnet.pm,v 1.919 2007/10/03 21:59:13 albertel Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.1 albertel 30: package Apache::lonnet;
31:
32: use strict;
1.8 www 33: use LWP::UserAgent();
1.486 www 34: use HTTP::Date;
35: # use Date::Parse;
1.871 albertel 36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
37: $_64bit %env);
38:
39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
40: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
41: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
42: %courseownerbuf, %coursetypebuf);
1.403 www 43:
1.1 albertel 44: use IO::Socket;
1.31 www 45: use GDBM_File;
1.208 albertel 46: use HTML::LCParser;
1.88 www 47: use Fcntl qw(:flock);
1.870 albertel 48: use Storable qw(thaw nfreeze);
1.539 albertel 49: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 50: use Cache::Memcached;
1.676 albertel 51: use Digest::MD5;
1.790 albertel 52: use Math::Random;
1.807 albertel 53: use LONCAPA qw(:DEFAULT :match);
1.740 www 54: use LONCAPA::Configuration;
1.676 albertel 55:
1.195 www 56: my $readit;
1.550 foxr 57: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 58:
1.619 albertel 59: require Exporter;
60:
61: our @ISA = qw (Exporter);
62: our @EXPORT = qw(%env);
63:
1.449 matthew 64: =pod
65:
66: =head1 Package Variables
67:
68: These are largely undocumented, so if you decipher one please note it here.
69:
70: =over 4
71:
72: =item $processmarker
73:
74: Contains the time this process was started and this servers host id.
75:
76: =item $dumpcount
77:
78: Counts the number of times a message log flush has been attempted (regardless
79: of success) by this process. Used as part of the filename when messages are
80: delayed.
81:
82: =back
83:
84: =cut
85:
86:
1.1 albertel 87: # --------------------------------------------------------------------- Logging
1.729 www 88: {
89: my $logid;
90: sub instructor_log {
91: my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
92: $logid++;
93: my $id=time().'00000'.$$.'00000'.$logid;
94: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 95: { $id => {
96: 'exe_uname' => $env{'user.name'},
97: 'exe_udom' => $env{'user.domain'},
98: 'exe_time' => time(),
99: 'exe_ip' => $ENV{'REMOTE_ADDR'},
100: 'delflag' => $delflag,
101: 'logentry' => $storehash,
102: 'uname' => $uname,
103: 'udom' => $udom,
104: }
105: },
1.729 www 106: $env{'course.'.$env{'request.course.id'}.'.domain'},
107: $env{'course.'.$env{'request.course.id'}.'.num'}
108: );
109: }
110: }
1.1 albertel 111:
1.163 harris41 112: sub logtouch {
113: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 114: unless (-e "$execdir/logs/lonnet.log") {
115: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 116: close $fh;
117: }
118: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
119: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
120: }
121:
1.1 albertel 122: sub logthis {
123: my $message=shift;
124: my $execdir=$perlvar{'lonDaemons'};
125: my $now=time;
126: my $local=localtime($now);
1.448 albertel 127: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
128: print $fh "$local ($$): $message\n";
129: close($fh);
130: }
1.1 albertel 131: return 1;
132: }
133:
134: sub logperm {
135: my $message=shift;
136: my $execdir=$perlvar{'lonDaemons'};
137: my $now=time;
138: my $local=localtime($now);
1.448 albertel 139: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
140: print $fh "$now:$message:$local\n";
141: close($fh);
142: }
1.1 albertel 143: return 1;
144: }
145:
1.850 albertel 146: sub create_connection {
1.853 albertel 147: my ($hostname,$lonid) = @_;
1.851 albertel 148: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 149: Type => SOCK_STREAM,
150: Timeout => 10);
151: return 0 if (!$client);
1.890 albertel 152: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 153: my $result = <$client>;
154: chomp($result);
155: return 1 if ($result eq 'done');
156: return 0;
157: }
158:
159:
1.1 albertel 160: # -------------------------------------------------- Non-critical communication
161: sub subreply {
162: my ($cmd,$server)=@_;
1.838 albertel 163: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 164: #
165: # With loncnew process trimming, there's a timing hole between lonc server
166: # process exit and the master server picking up the listen on the AF_UNIX
167: # socket. In that time interval, a lock file will exist:
168:
169: my $lockfile=$peerfile.".lock";
170: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
171: sleep(1);
172: }
173: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 174: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 175: #
1.550 foxr 176: # We'll give the connection a few tries before abandoning it. If
177: # connection is not possible, we'll con_lost back to the client.
178: #
179: my $client;
180: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
181: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
182: Type => SOCK_STREAM,
183: Timeout => 10);
1.869 albertel 184: if ($client) {
1.550 foxr 185: last; # Connected!
1.850 albertel 186: } else {
1.853 albertel 187: &create_connection(&hostname($server),$server);
1.550 foxr 188: }
1.850 albertel 189: sleep(1); # Try again later if failed connection.
1.550 foxr 190: }
191: my $answer;
192: if ($client) {
1.704 albertel 193: print $client "sethost:$server:$cmd\n";
1.550 foxr 194: $answer=<$client>;
195: if (!$answer) { $answer="con_lost"; }
196: chomp($answer);
197: } else {
198: $answer = 'con_lost'; # Failed connection.
199: }
1.1 albertel 200: return $answer;
201: }
202:
203: sub reply {
204: my ($cmd,$server)=@_;
1.838 albertel 205: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 206: my $answer=subreply($cmd,$server);
1.65 www 207: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 208: &logthis("<font color=\"blue\">WARNING:".
1.12 www 209: " $cmd to $server returned $answer</font>");
210: }
1.1 albertel 211: return $answer;
212: }
213:
214: # ----------------------------------------------------------- Send USR1 to lonc
215:
216: sub reconlonc {
1.891 albertel 217: my ($lonid) = @_;
218: my $hostname = &hostname($lonid);
219: if ($lonid) {
220: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
221: if ($hostname && -e $peerfile) {
222: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
223: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
224: Type => SOCK_STREAM,
225: Timeout => 10);
226: if ($client) {
227: print $client ("reset_retries\n");
228: my $answer=<$client>;
229: #reset just this one.
230: }
231: }
232: return;
233: }
234:
1.836 www 235: &logthis("Trying to reconnect lonc");
1.1 albertel 236: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 237: if (open(my $fh,"<$loncfile")) {
1.1 albertel 238: my $loncpid=<$fh>;
239: chomp($loncpid);
240: if (kill 0 => $loncpid) {
241: &logthis("lonc at pid $loncpid responding, sending USR1");
242: kill USR1 => $loncpid;
243: sleep 1;
1.836 www 244: } else {
1.12 www 245: &logthis(
1.672 albertel 246: "<font color=\"blue\">WARNING:".
1.12 www 247: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 248: }
249: } else {
1.836 www 250: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 251: }
252: }
253:
254: # ------------------------------------------------------ Critical communication
1.12 www 255:
1.1 albertel 256: sub critical {
257: my ($cmd,$server)=@_;
1.838 albertel 258: unless (&hostname($server)) {
1.672 albertel 259: &logthis("<font color=\"blue\">WARNING:".
1.89 www 260: " Critical message to unknown server ($server)</font>");
261: return 'no_such_host';
262: }
1.1 albertel 263: my $answer=reply($cmd,$server);
264: if ($answer eq 'con_lost') {
265: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 266: my $answer=reply($cmd,$server);
1.1 albertel 267: if ($answer eq 'con_lost') {
268: my $now=time;
269: my $middlename=$cmd;
1.5 www 270: $middlename=substr($middlename,0,16);
1.1 albertel 271: $middlename=~s/\W//g;
272: my $dfilename=
1.305 www 273: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
274: $dumpcount++;
1.1 albertel 275: {
1.448 albertel 276: my $dfh;
277: if (open($dfh,">$dfilename")) {
278: print $dfh "$cmd\n";
279: close($dfh);
280: }
1.1 albertel 281: }
282: sleep 2;
283: my $wcmd='';
284: {
1.448 albertel 285: my $dfh;
286: if (open($dfh,"<$dfilename")) {
287: $wcmd=<$dfh>;
288: close($dfh);
289: }
1.1 albertel 290: }
291: chomp($wcmd);
1.7 www 292: if ($wcmd eq $cmd) {
1.672 albertel 293: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 294: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 295: &logperm("D:$server:$cmd");
296: return 'con_delayed';
297: } else {
1.672 albertel 298: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 299: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 300: &logperm("F:$server:$cmd");
301: return 'con_failed';
302: }
303: }
304: }
305: return $answer;
1.405 albertel 306: }
307:
1.755 albertel 308: # ------------------------------------------- check if return value is an error
309:
310: sub error {
311: my ($result) = @_;
1.756 albertel 312: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 313: if ($2 == 2) { return undef; }
314: return $1;
315: }
316: return undef;
317: }
318:
1.783 albertel 319: sub convert_and_load_session_env {
320: my ($lonidsdir,$handle)=@_;
321: my @profile;
322: {
1.917 albertel 323: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
324: if (!$opened) {
1.915 albertel 325: return 0;
326: }
1.783 albertel 327: flock($idf,LOCK_SH);
328: @profile=<$idf>;
329: close($idf);
330: }
331: my %temp_env;
332: foreach my $line (@profile) {
1.786 albertel 333: if ($line !~ m/=/) {
334: return 0;
335: }
1.783 albertel 336: chomp($line);
337: my ($envname,$envvalue)=split(/=/,$line,2);
338: $temp_env{&unescape($envname)} = &unescape($envvalue);
339: }
340: unlink("$lonidsdir/$handle.id");
341: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
342: 0640)) {
343: %disk_env = %temp_env;
344: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
345: untie(%disk_env);
346: }
1.786 albertel 347: return 1;
1.783 albertel 348: }
349:
1.374 www 350: # ------------------------------------------- Transfer profile into environment
1.780 albertel 351: my $env_loaded;
352: sub transfer_profile_to_env {
1.788 albertel 353: my ($lonidsdir,$handle,$force_transfer) = @_;
354: if (!$force_transfer && $env_loaded) { return; }
1.374 www 355:
1.720 albertel 356: if (!defined($lonidsdir)) {
357: $lonidsdir = $perlvar{'lonIDsDir'};
358: }
359: if (!defined($handle)) {
360: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
361: }
362:
1.786 albertel 363: my $convert;
364: {
1.917 albertel 365: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
366: if (!$opened) {
1.915 albertel 367: return;
368: }
1.786 albertel 369: flock($idf,LOCK_SH);
370: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
371: &GDBM_READER(),0640)) {
372: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
373: untie(%disk_env);
374: } else {
375: $convert = 1;
376: }
377: }
378: if ($convert) {
379: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
380: &logthis("Failed to load session, or convert session.");
381: }
1.374 www 382: }
1.783 albertel 383:
1.786 albertel 384: my %remove;
1.783 albertel 385: while ( my $envname = each(%env) ) {
1.433 matthew 386: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
387: if ($time < time-300) {
1.783 albertel 388: $remove{$key}++;
1.433 matthew 389: }
390: }
391: }
1.783 albertel 392:
1.619 albertel 393: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 394: $env_loaded=1;
1.783 albertel 395: foreach my $expired_key (keys(%remove)) {
1.433 matthew 396: &delenv($expired_key);
1.374 www 397: }
1.1 albertel 398: }
399:
1.916 albertel 400: # ---------------------------------------------------- Check for valid session
401: sub check_for_valid_session {
402: my ($r) = @_;
403: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
404: my $lonid=$cookies{'lonID'};
405: return undef if (!$lonid);
406:
407: my $handle=&LONCAPA::clean_handle($lonid->value);
408: my $lonidsdir=$r->dir_config('lonIDsDir');
409: return undef if (!-e "$lonidsdir/$handle.id");
410:
1.917 albertel 411: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
412: return undef if (!$opened);
1.916 albertel 413:
414: flock($idf,LOCK_SH);
415: my %disk_env;
416: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
417: &GDBM_READER(),0640)) {
418: return undef;
419: }
420:
421: if (!defined($disk_env{'user.name'})
422: || !defined($disk_env{'user.domain'})) {
423: return undef;
424: }
425: return $handle;
426: }
427:
1.830 albertel 428: sub timed_flock {
429: my ($file,$lock_type) = @_;
430: my $failed=0;
431: eval {
432: local $SIG{__DIE__}='DEFAULT';
433: local $SIG{ALRM}=sub {
434: $failed=1;
435: die("failed lock");
436: };
437: alarm(13);
438: flock($file,$lock_type);
439: alarm(0);
440: };
441: if ($failed) {
442: return undef;
443: } else {
444: return 1;
445: }
446: }
447:
1.5 www 448: # ---------------------------------------------------------- Append Environment
449:
450: sub appenv {
1.6 www 451: my %newenv=@_;
1.692 albertel 452: foreach my $key (keys(%newenv)) {
453: if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672 albertel 454: &logthis("<font color=\"blue\">WARNING: ".
1.692 albertel 455: "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151 www 456: .'</font>');
1.692 albertel 457: delete($newenv{$key});
1.35 www 458: } else {
1.692 albertel 459: $env{$key}=$newenv{$key};
1.35 www 460: }
1.191 harris41 461: }
1.917 albertel 462: my $opened = open(my $env_file,'+<',$env{'user.environment'});
463: if ($opened
1.915 albertel 464: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 465: &&
466: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
467: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 468: while (my ($key,$value) = each(%newenv)) {
469: $disk_env{$key} = $value;
1.448 albertel 470: }
1.783 albertel 471: untie(%disk_env);
1.56 www 472: }
473: return 'ok';
474: }
475: # ----------------------------------------------------- Delete from Environment
476:
477: sub delenv {
478: my $delthis=shift;
479: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 480: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 481: "Attempt to delete from environment ".$delthis);
482: return 'error';
483: }
1.917 albertel 484: my $opened = open(my $env_file,'+<',$env{'user.environment'});
485: if ($opened
1.915 albertel 486: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 487: &&
488: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
489: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 490: foreach my $key (keys(%disk_env)) {
491: if ($key=~/^$delthis/) {
1.915 albertel 492: delete($env{$key});
493: delete($disk_env{$key});
494: }
1.448 albertel 495: }
1.783 albertel 496: untie(%disk_env);
1.5 www 497: }
498: return 'ok';
1.369 albertel 499: }
500:
1.790 albertel 501: sub get_env_multiple {
502: my ($name) = @_;
503: my @values;
504: if (defined($env{$name})) {
505: # exists is it an array
506: if (ref($env{$name})) {
507: @values=@{ $env{$name} };
508: } else {
509: $values[0]=$env{$name};
510: }
511: }
512: return(@values);
513: }
514:
1.369 albertel 515: # ------------------------------------------ Find out current server userload
516: # 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.800 albertel 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}),
2190: 'instcode' => &escape($courseinstcodebuf{$crsid}),
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),
2201: $courseidbuffer{$crs_home},$crs_home);
1.352 www 2202: }
2203: #
2204: # File accesses
2205: # Writes to the dynamic metadata of resources to get hit counts, etc.
2206: #
1.449 matthew 2207: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2208: if ($entry =~ /___count$/) {
2209: my ($dom,$name);
1.807 albertel 2210: ($dom,$name,undef)=
1.811 albertel 2211: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2212: if (! defined($dom) || $dom eq '' ||
2213: ! defined($name) || $name eq '') {
1.620 albertel 2214: my $cid = $env{'request.course.id'};
2215: $dom = $env{'request.'.$cid.'.domain'};
2216: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2217: }
1.450 matthew 2218: my $value = $accesshash{$entry};
2219: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2220: my %temphash=($url => $value);
1.449 matthew 2221: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2222: if ($result eq 'ok') {
2223: delete $accesshash{$entry};
2224: } elsif ($result eq 'unknown_cmd') {
2225: # Target server has old code running on it.
1.450 matthew 2226: my %temphash=($entry => $value);
1.449 matthew 2227: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2228: delete $accesshash{$entry};
2229: }
2230: }
2231: } else {
1.811 albertel 2232: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2233: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2234: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2235: delete $accesshash{$entry};
2236: }
1.185 www 2237: }
1.191 harris41 2238: }
1.352 www 2239: #
2240: # Roles
2241: # Reverse lookup of user roles for course faculty/staff and co-authorship
2242: #
1.800 albertel 2243: foreach my $entry (keys(%userrolehash)) {
1.351 www 2244: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2245: split(/\:/,$entry);
2246: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2247: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2248: $rudom,$runame) eq 'ok') {
2249: delete $userrolehash{$entry};
2250: }
2251: }
1.662 raeburn 2252: #
2253: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2254: #
2255: my %domrolebuffer = ();
2256: foreach my $entry (keys %domainrolehash) {
1.901 albertel 2257: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2258: if ($domrolebuffer{$rudom}) {
2259: $domrolebuffer{$rudom}.='&'.&escape($entry).
2260: '='.&escape($domainrolehash{$entry});
2261: } else {
2262: $domrolebuffer{$rudom}.=&escape($entry).
2263: '='.&escape($domainrolehash{$entry});
2264: }
2265: delete $domainrolehash{$entry};
2266: }
2267: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2268: my %servers = &get_servers($dom,'library');
2269: foreach my $tryserver (keys(%servers)) {
2270: unless (&reply('domroleput:'.$dom.':'.
2271: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2272: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2273: }
1.662 raeburn 2274: }
2275: }
1.186 www 2276: $dumpcount++;
1.157 www 2277: }
2278:
2279: sub courselog {
2280: my $what=shift;
1.158 www 2281: $what=time.':'.$what;
1.620 albertel 2282: unless ($env{'request.course.id'}) { return ''; }
2283: $coursedombuf{$env{'request.course.id'}}=
2284: $env{'course.'.$env{'request.course.id'}.'.domain'};
2285: $coursenumbuf{$env{'request.course.id'}}=
2286: $env{'course.'.$env{'request.course.id'}.'.num'};
2287: $coursehombuf{$env{'request.course.id'}}=
2288: $env{'course.'.$env{'request.course.id'}.'.home'};
2289: $coursedescrbuf{$env{'request.course.id'}}=
2290: $env{'course.'.$env{'request.course.id'}.'.description'};
2291: $courseinstcodebuf{$env{'request.course.id'}}=
2292: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2293: $courseownerbuf{$env{'request.course.id'}}=
2294: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2295: $coursetypebuf{$env{'request.course.id'}}=
2296: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2297: if (defined $courselogs{$env{'request.course.id'}}) {
2298: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2299: } else {
1.620 albertel 2300: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2301: }
1.620 albertel 2302: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2303: &flushcourselogs();
2304: }
1.158 www 2305: }
2306:
2307: sub courseacclog {
2308: my $fnsymb=shift;
1.620 albertel 2309: unless ($env{'request.course.id'}) { return ''; }
2310: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2311: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2312: $what.=':POST';
1.583 matthew 2313: # FIXME: Probably ought to escape things....
1.800 albertel 2314: foreach my $key (keys(%env)) {
2315: if ($key=~/^form\.(.*)/) {
2316: $what.=':'.$1.'='.$env{$key};
1.158 www 2317: }
1.191 harris41 2318: }
1.583 matthew 2319: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2320: # FIXME: We should not be depending on a form parameter that someone
2321: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2322: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2323: $what.= ':POST';
2324: # FIXME: Probably ought to escape things....
2325: foreach my $element ('courseexp','crsfulltext','crsrelated',
2326: 'crsdiscuss') {
1.620 albertel 2327: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2328: }
2329: }
1.158 www 2330: }
2331: &courselog($what);
1.149 www 2332: }
2333:
1.185 www 2334: sub countacc {
2335: my $url=&declutter(shift);
1.458 matthew 2336: return if (! defined($url) || $url eq '');
1.620 albertel 2337: unless ($env{'request.course.id'}) { return ''; }
2338: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2339: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2340: $accesshash{$key}++;
1.185 www 2341: }
1.349 www 2342:
1.361 www 2343: sub linklog {
2344: my ($from,$to)=@_;
2345: $from=&declutter($from);
2346: $to=&declutter($to);
2347: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2348: $accesshash{$to.'___'.$from.'___goto'}=1;
2349: }
2350:
1.349 www 2351: sub userrolelog {
2352: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2353: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2354: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2355: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2356: ($trole=~/^ta/)) {
1.350 www 2357: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2358: $userrolehash
2359: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2360: =$tend.':'.$tstart;
1.662 raeburn 2361: }
1.898 albertel 2362: if (($env{'request.role'} =~ /dc\./) &&
2363: (($trole=~/^au/) || ($trole=~/^in/) ||
2364: ($trole=~/^cc/) || ($trole=~/^ep/) ||
2365: ($trole=~/^cr/) || ($trole=~/^ta/))) {
2366: $userrolehash
2367: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2368: =$tend.':'.$tstart;
2369: }
1.662 raeburn 2370: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2371: ($trole=~/^li/) || ($trole=~/^li/) ||
2372: ($trole=~/^au/) || ($trole=~/^dg/) ||
2373: ($trole=~/^sc/)) {
2374: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2375: $domainrolehash
2376: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2377: = $tend.':'.$tstart;
2378: }
1.351 www 2379: }
2380:
2381: sub get_course_adv_roles {
2382: my $cid=shift;
1.620 albertel 2383: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2384: my %coursehash=&coursedescription($cid);
1.470 www 2385: my %nothide=();
1.800 albertel 2386: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2387: $nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470 www 2388: }
1.351 www 2389: my %returnhash=();
2390: my %dumphash=
2391: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2392: my $now=time;
1.800 albertel 2393: foreach my $entry (keys %dumphash) {
2394: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2395: if (($tstart) && ($tstart<0)) { next; }
2396: if (($tend) && ($tend<$now)) { next; }
2397: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2398: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2399: if ($username eq '' || $domain eq '') { next; }
1.470 www 2400: if ((&privileged($username,$domain)) &&
2401: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2402: if ($role eq 'cr') { next; }
1.351 www 2403: my $key=&plaintext($role);
2404: if ($section) { $key.=' (Sec/Grp '.$section.')'; }
2405: if ($returnhash{$key}) {
2406: $returnhash{$key}.=','.$username.':'.$domain;
2407: } else {
2408: $returnhash{$key}=$username.':'.$domain;
2409: }
1.400 www 2410: }
2411: return %returnhash;
2412: }
2413:
2414: sub get_my_roles {
1.858 raeburn 2415: my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620 albertel 2416: unless (defined($uname)) { $uname=$env{'user.name'}; }
2417: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858 raeburn 2418: my %dumphash;
2419: if ($context eq 'userroles') {
2420: %dumphash = &dump('roles',$udom,$uname);
2421: } else {
2422: %dumphash=
1.400 www 2423: &dump('nohist_userroles',$udom,$uname);
1.858 raeburn 2424: }
1.400 www 2425: my %returnhash=();
2426: my $now=time;
1.800 albertel 2427: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2428: my ($role,$tend,$tstart);
2429: if ($context eq 'userroles') {
2430: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2431: } else {
2432: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2433: }
1.400 www 2434: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2435: my $status = 'active';
2436: if (($tend) && ($tend<$now)) {
2437: $status = 'previous';
2438: }
2439: if (($tstart) && ($now<$tstart)) {
2440: $status = 'future';
2441: }
2442: if (ref($types) eq 'ARRAY') {
2443: if (!grep(/^\Q$status\E$/,@{$types})) {
2444: next;
2445: }
2446: } else {
2447: if ($status ne 'active') {
2448: next;
2449: }
2450: }
1.867 raeburn 2451: my ($rolecode,$username,$domain,$section,$area);
2452: if ($context eq 'userroles') {
2453: ($area,$rolecode) = split(/_/,$entry);
2454: (undef,$domain,$username,$section) = split(/\//,$area);
2455: } else {
2456: ($role,$username,$domain,$section) = split(/\:/,$entry);
2457: }
1.832 raeburn 2458: if (ref($roledoms) eq 'ARRAY') {
2459: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2460: next;
2461: }
2462: }
2463: if (ref($roles) eq 'ARRAY') {
2464: if (!grep(/^\Q$role\E$/,@{$roles})) {
2465: next;
2466: }
1.867 raeburn 2467: }
1.400 www 2468: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832 raeburn 2469: }
1.373 www 2470: return %returnhash;
1.399 www 2471: }
2472:
2473: # ----------------------------------------------------- Frontpage Announcements
2474: #
2475: #
2476:
2477: sub postannounce {
2478: my ($server,$text)=@_;
1.844 albertel 2479: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2480: unless ($text=~/\w/) { $text=''; }
2481: return &reply('setannounce:'.&escape($text),$server);
2482: }
2483:
2484: sub getannounce {
1.448 albertel 2485:
2486: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 2487: my $announcement='';
1.800 albertel 2488: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 2489: close($fh);
1.399 www 2490: if ($announcement=~/\w/) {
2491: return
2492: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 2493: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 2494: } else {
2495: return '';
2496: }
2497: } else {
2498: return '';
2499: }
1.351 www 2500: }
1.353 www 2501:
2502: # ---------------------------------------------------------- Course ID routines
2503: # Deal with domain's nohist_courseid.db files
2504: #
2505:
2506: sub courseidput {
1.918 raeburn 2507: my ($domain,$storehash,$coursehome)=@_;
2508: my $items='';
2509: my $now = time;
2510: foreach my $item (keys(%$storehash)) {
2511: $storehash->{$item}{'lasttime'} = $now;
2512: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
2513: }
2514: $items=~s/\&$//;
2515: my $outcome = &reply('courseidputhash:'.$domain.':'.$items,$coursehome);
2516: if ($outcome eq 'unknown_cmd') {
2517: my $what;
2518: foreach my $cid (keys(%$storehash)) {
2519: $what .= &escape($cid).'=';
2520: foreach my $item ('description','instcode','owner','type') {
2521: $what .= $storehash->{$item}.':';
2522: }
2523: $what =~ s/\:$/&/;
2524: }
2525: $what =~ s/\&$//;
2526: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2527: } else {
2528: return $outcome;
2529: }
1.353 www 2530: }
2531:
2532: sub courseiddump {
1.791 raeburn 2533: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.918 raeburn 2534: my $as_hash = 1;
2535: my %returnhash;
2536: if (!$domfilter) { $domfilter=''; }
1.845 albertel 2537: my %libserv = &all_library();
2538: foreach my $tryserver (keys(%libserv)) {
2539: if ( ( $hostidflag == 1
2540: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
2541: || (!defined($hostidflag)) ) {
2542:
1.918 raeburn 2543: if (($domfilter eq '') ||
2544: (&host_domain($tryserver) eq $domfilter)) {
2545: my $rep =
2546: &reply('courseiddump:'.&host_domain($tryserver).':'.
2547: $sincefilter.':'.&escape($descfilter).':'.
2548: &escape($instcodefilter).':'.&escape($ownerfilter).
2549: ':'.&escape($coursefilter).':'.&escape($typefilter).
2550: ':'.&escape($regexp_ok).':'.$as_hash,$tryserver);
2551: my @pairs=split(/\&/,$rep);
2552: foreach my $item (@pairs) {
2553: my ($key,$value)=split(/\=/,$item,2);
2554: $key = &unescape($key);
2555: next if ($key =~ /^error: 2 /);
2556: my $result = &thaw_unescape($value);
2557: if (ref($result) eq 'HASH') {
2558: $returnhash{$key}=$result;
2559: } else {
2560: my @responses = split(/:/,$result);
2561: my @items = ('description','instcode','owner','type');
2562: for (my $i=0; $i<@responses; $i++) {
2563: $returnhash{$key}{$items[$i]} = $responses[$i];
2564: }
2565: }
1.353 www 2566: }
2567: }
2568: }
2569: }
2570: return %returnhash;
2571: }
2572:
1.658 raeburn 2573: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 2574:
2575: sub dcmailput {
1.685 raeburn 2576: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 2577: my $status = &Apache::lonnet::critical(
1.740 www 2578: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2579: &escape($message),$server);
1.662 raeburn 2580: return $status;
2581: }
2582:
1.658 raeburn 2583: sub dcmaildump {
2584: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 2585: my %returnhash=();
1.846 albertel 2586:
2587: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 2588: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2589: &escape($enddate).':';
2590: my @esc_senders=map { &escape($_)} @$senders;
2591: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 2592: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 2593: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 2594: if (($key) && ($value)) {
2595: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 2596: }
2597: }
2598: }
2599: return %returnhash;
2600: }
1.662 raeburn 2601: # ---------------------------------------------------------- Domain roles
2602:
2603: sub get_domain_roles {
2604: my ($dom,$roles,$startdate,$enddate)=@_;
2605: if (undef($startdate) || $startdate eq '') {
2606: $startdate = '.';
2607: }
2608: if (undef($enddate) || $enddate eq '') {
2609: $enddate = '.';
2610: }
2611: my $rolelist = join(':',@{$roles});
2612: my %personnel = ();
1.841 albertel 2613:
2614: my %servers = &get_servers($dom,'library');
2615: foreach my $tryserver (keys(%servers)) {
2616: %{$personnel{$tryserver}}=();
2617: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
2618: &escape($startdate).':'.
2619: &escape($enddate).':'.
2620: &escape($rolelist), $tryserver))) {
2621: my ($key,$value) = split(/\=/,$line,2);
2622: if (($key) && ($value)) {
2623: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2624: }
2625: }
1.662 raeburn 2626: }
2627: return %personnel;
2628: }
1.658 raeburn 2629:
1.149 www 2630: # ----------------------------------------------------------- Check out an item
2631:
1.504 albertel 2632: sub get_first_access {
2633: my ($type,$argsymb)=@_;
1.790 albertel 2634: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2635: if ($argsymb) { $symb=$argsymb; }
2636: my ($map,$id,$res)=&decode_symb($symb);
1.588 albertel 2637: if ($type eq 'map') {
2638: $res=&symbread($map);
2639: } else {
2640: $res=$symb;
2641: }
2642: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2643: return $times{"$courseid\0$res"};
1.504 albertel 2644: }
2645:
2646: sub set_first_access {
2647: my ($type)=@_;
1.790 albertel 2648: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2649: my ($map,$id,$res)=&decode_symb($symb);
1.588 albertel 2650: if ($type eq 'map') {
2651: $res=&symbread($map);
2652: } else {
2653: $res=$symb;
2654: }
2655: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 2656: if (!$firstaccess) {
1.588 albertel 2657: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 2658: }
2659: return 'already_set';
1.504 albertel 2660: }
2661:
1.149 www 2662: sub checkout {
2663: my ($symb,$tuname,$tudom,$tcrsid)=@_;
2664: my $now=time;
2665: my $lonhost=$perlvar{'lonHostID'};
2666: my $infostr=&escape(
1.234 www 2667: 'CHECKOUTTOKEN&'.
1.149 www 2668: $tuname.'&'.
2669: $tudom.'&'.
2670: $tcrsid.'&'.
2671: $symb.'&'.
2672: $now.'&'.$ENV{'REMOTE_ADDR'});
2673: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 2674: if ($token=~/^error\:/) {
1.672 albertel 2675: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2676: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
2677: "</font>");
2678: return '';
2679: }
2680:
1.149 www 2681: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
2682: $token=~tr/a-z/A-Z/;
2683:
1.153 www 2684: my %infohash=('resource.0.outtoken' => $token,
2685: 'resource.0.checkouttime' => $now,
2686: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 2687:
2688: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2689: return '';
1.151 www 2690: } else {
1.672 albertel 2691: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2692: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
2693: "</font>");
1.149 www 2694: }
2695:
2696: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2697: &escape('Checkout '.$infostr.' - '.
2698: $token)) ne 'ok') {
2699: return '';
1.151 www 2700: } else {
1.672 albertel 2701: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2702: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
2703: "</font>");
1.149 www 2704: }
1.151 www 2705: return $token;
1.149 www 2706: }
2707:
2708: # ------------------------------------------------------------ Check in an item
2709:
2710: sub checkin {
2711: my $token=shift;
1.150 www 2712: my $now=time;
2713: my ($ta,$tb,$lonhost)=split(/\*/,$token);
2714: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 2715: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 2716: $dtoken=~s/\W/\_/g;
1.234 www 2717: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 2718: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
2719:
1.154 www 2720: unless (($tuname) && ($tudom)) {
2721: &logthis('Check in '.$token.' ('.$dtoken.') failed');
2722: return '';
2723: }
2724:
2725: unless (&allowed('mgr',$tcrsid)) {
2726: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 2727: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 2728: return '';
2729: }
2730:
1.153 www 2731: my %infohash=('resource.0.intoken' => $token,
2732: 'resource.0.checkintime' => $now,
2733: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 2734:
2735: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2736: return '';
2737: }
2738:
2739: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2740: &escape('Checkin - '.$token)) ne 'ok') {
2741: return '';
2742: }
2743:
2744: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 2745: }
2746:
2747: # --------------------------------------------- Set Expire Date for Spreadsheet
2748:
2749: sub expirespread {
2750: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 2751: my $cid=$env{'request.course.id'};
1.110 www 2752: if ($cid) {
2753: my $now=time;
2754: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 2755: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
2756: $env{'course.'.$cid.'.num'}.
1.110 www 2757: ':nohist_expirationdates:'.
2758: &escape($key).'='.$now,
1.620 albertel 2759: $env{'course.'.$cid.'.home'})
1.110 www 2760: }
2761: return 'ok';
1.14 www 2762: }
2763:
1.109 www 2764: # ----------------------------------------------------- Devalidate Spreadsheets
2765:
2766: sub devalidate {
1.325 www 2767: my ($symb,$uname,$udom)=@_;
1.620 albertel 2768: my $cid=$env{'request.course.id'};
1.109 www 2769: if ($cid) {
1.391 matthew 2770: # delete the stored spreadsheets for
2771: # - the student level sheet of this user in course's homespace
2772: # - the assessment level sheet for this resource
2773: # for this user in user's homespace
1.553 albertel 2774: # - current conditional state info
1.325 www 2775: my $key=$uname.':'.$udom.':';
1.109 www 2776: my $status=
1.299 matthew 2777: &del('nohist_calculatedsheets',
1.391 matthew 2778: [$key.'studentcalc:'],
1.620 albertel 2779: $env{'course.'.$cid.'.domain'},
2780: $env{'course.'.$cid.'.num'})
1.133 albertel 2781: .' '.
2782: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 2783: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 2784: unless ($status eq 'ok ok') {
2785: &logthis('Could not devalidate spreadsheet '.
1.325 www 2786: $uname.' at '.$udom.' for '.
1.109 www 2787: $symb.': '.$status);
1.133 albertel 2788: }
1.553 albertel 2789: &delenv('user.state.'.$cid);
1.109 www 2790: }
2791: }
2792:
1.265 albertel 2793: sub get_scalar {
2794: my ($string,$end) = @_;
2795: my $value;
2796: if ($$string =~ s/^([^&]*?)($end)/$2/) {
2797: $value = $1;
2798: } elsif ($$string =~ s/^([^&]*?)&//) {
2799: $value = $1;
2800: }
2801: return &unescape($value);
2802: }
2803:
2804: sub array2str {
2805: my (@array) = @_;
2806: my $result=&arrayref2str(\@array);
2807: $result=~s/^__ARRAY_REF__//;
2808: $result=~s/__END_ARRAY_REF__$//;
2809: return $result;
2810: }
2811:
1.204 albertel 2812: sub arrayref2str {
2813: my ($arrayref) = @_;
1.265 albertel 2814: my $result='__ARRAY_REF__';
1.204 albertel 2815: foreach my $elem (@$arrayref) {
1.265 albertel 2816: if(ref($elem) eq 'ARRAY') {
2817: $result.=&arrayref2str($elem).'&';
2818: } elsif(ref($elem) eq 'HASH') {
2819: $result.=&hashref2str($elem).'&';
2820: } elsif(ref($elem)) {
2821: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 2822: } else {
2823: $result.=&escape($elem).'&';
2824: }
2825: }
2826: $result=~s/\&$//;
1.265 albertel 2827: $result .= '__END_ARRAY_REF__';
1.204 albertel 2828: return $result;
2829: }
2830:
1.168 albertel 2831: sub hash2str {
1.204 albertel 2832: my (%hash) = @_;
2833: my $result=&hashref2str(\%hash);
1.265 albertel 2834: $result=~s/^__HASH_REF__//;
2835: $result=~s/__END_HASH_REF__$//;
1.204 albertel 2836: return $result;
2837: }
2838:
2839: sub hashref2str {
2840: my ($hashref)=@_;
1.265 albertel 2841: my $result='__HASH_REF__';
1.800 albertel 2842: foreach my $key (sort(keys(%$hashref))) {
2843: if (ref($key) eq 'ARRAY') {
2844: $result.=&arrayref2str($key).'=';
2845: } elsif (ref($key) eq 'HASH') {
2846: $result.=&hashref2str($key).'=';
2847: } elsif (ref($key)) {
1.265 albertel 2848: $result.='=';
1.800 albertel 2849: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 2850: } else {
1.800 albertel 2851: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 2852: }
2853:
1.800 albertel 2854: if(ref($hashref->{$key}) eq 'ARRAY') {
2855: $result.=&arrayref2str($hashref->{$key}).'&';
2856: } elsif(ref($hashref->{$key}) eq 'HASH') {
2857: $result.=&hashref2str($hashref->{$key}).'&';
2858: } elsif(ref($hashref->{$key})) {
1.265 albertel 2859: $result.='&';
1.800 albertel 2860: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 2861: } else {
1.800 albertel 2862: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 2863: }
2864: }
1.168 albertel 2865: $result=~s/\&$//;
1.265 albertel 2866: $result .= '__END_HASH_REF__';
1.168 albertel 2867: return $result;
2868: }
2869:
2870: sub str2hash {
1.265 albertel 2871: my ($string)=@_;
2872: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
2873: return %$hash;
2874: }
2875:
2876: sub str2hashref {
1.168 albertel 2877: my ($string) = @_;
1.265 albertel 2878:
2879: my %hash;
2880:
2881: if($string !~ /^__HASH_REF__/) {
2882: if (! ($string eq '' || !defined($string))) {
2883: $hash{'error'}='Not hash reference';
2884: }
2885: return (\%hash, $string);
2886: }
2887:
2888: $string =~ s/^__HASH_REF__//;
2889:
2890: while($string !~ /^__END_HASH_REF__/) {
2891: #key
2892: my $key='';
2893: if($string =~ /^__HASH_REF__/) {
2894: ($key, $string)=&str2hashref($string);
2895: if(defined($key->{'error'})) {
2896: $hash{'error'}='Bad data';
2897: return (\%hash, $string);
2898: }
2899: } elsif($string =~ /^__ARRAY_REF__/) {
2900: ($key, $string)=&str2arrayref($string);
2901: if($key->[0] eq 'Array reference error') {
2902: $hash{'error'}='Bad data';
2903: return (\%hash, $string);
2904: }
2905: } else {
2906: $string =~ s/^(.*?)=//;
1.267 albertel 2907: $key=&unescape($1);
1.265 albertel 2908: }
2909: $string =~ s/^=//;
2910:
2911: #value
2912: my $value='';
2913: if($string =~ /^__HASH_REF__/) {
2914: ($value, $string)=&str2hashref($string);
2915: if(defined($value->{'error'})) {
2916: $hash{'error'}='Bad data';
2917: return (\%hash, $string);
2918: }
2919: } elsif($string =~ /^__ARRAY_REF__/) {
2920: ($value, $string)=&str2arrayref($string);
2921: if($value->[0] eq 'Array reference error') {
2922: $hash{'error'}='Bad data';
2923: return (\%hash, $string);
2924: }
2925: } else {
2926: $value=&get_scalar(\$string,'__END_HASH_REF__');
2927: }
2928: $string =~ s/^&//;
2929:
2930: $hash{$key}=$value;
1.204 albertel 2931: }
1.265 albertel 2932:
2933: $string =~ s/^__END_HASH_REF__//;
2934:
2935: return (\%hash, $string);
1.204 albertel 2936: }
2937:
2938: sub str2array {
1.265 albertel 2939: my ($string)=@_;
2940: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
2941: return @$array;
2942: }
2943:
2944: sub str2arrayref {
1.204 albertel 2945: my ($string) = @_;
1.265 albertel 2946: my @array;
2947:
2948: if($string !~ /^__ARRAY_REF__/) {
2949: if (! ($string eq '' || !defined($string))) {
2950: $array[0]='Array reference error';
2951: }
2952: return (\@array, $string);
2953: }
2954:
2955: $string =~ s/^__ARRAY_REF__//;
2956:
2957: while($string !~ /^__END_ARRAY_REF__/) {
2958: my $value='';
2959: if($string =~ /^__HASH_REF__/) {
2960: ($value, $string)=&str2hashref($string);
2961: if(defined($value->{'error'})) {
2962: $array[0] ='Array reference error';
2963: return (\@array, $string);
2964: }
2965: } elsif($string =~ /^__ARRAY_REF__/) {
2966: ($value, $string)=&str2arrayref($string);
2967: if($value->[0] eq 'Array reference error') {
2968: $array[0] ='Array reference error';
2969: return (\@array, $string);
2970: }
2971: } else {
2972: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
2973: }
2974: $string =~ s/^&//;
2975:
2976: push(@array, $value);
1.191 harris41 2977: }
1.265 albertel 2978:
2979: $string =~ s/^__END_ARRAY_REF__//;
2980:
2981: return (\@array, $string);
1.168 albertel 2982: }
2983:
1.167 albertel 2984: # -------------------------------------------------------------------Temp Store
2985:
1.168 albertel 2986: sub tmpreset {
2987: my ($symb,$namespace,$domain,$stuname) = @_;
2988: if (!$symb) {
2989: $symb=&symbread();
1.620 albertel 2990: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2991: }
2992: $symb=escape($symb);
2993:
1.620 albertel 2994: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 2995: $namespace=~s/\//\_/g;
2996: $namespace=~s/\W//g;
2997:
1.620 albertel 2998: if (!$domain) { $domain=$env{'user.domain'}; }
2999: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3000: if ($domain eq 'public' && $stuname eq 'public') {
3001: $stuname=$ENV{'REMOTE_ADDR'};
3002: }
1.168 albertel 3003: my $path=$perlvar{'lonDaemons'}.'/tmp';
3004: my %hash;
3005: if (tie(%hash,'GDBM_File',
3006: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3007: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3008: foreach my $key (keys %hash) {
1.180 albertel 3009: if ($key=~ /:$symb/) {
1.168 albertel 3010: delete($hash{$key});
3011: }
3012: }
3013: }
3014: }
3015:
1.167 albertel 3016: sub tmpstore {
1.168 albertel 3017: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3018:
3019: if (!$symb) {
3020: $symb=&symbread();
1.620 albertel 3021: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3022: }
3023: $symb=escape($symb);
3024:
3025: if (!$namespace) {
3026: # I don't think we would ever want to store this for a course.
3027: # it seems this will only be used if we don't have a course.
1.620 albertel 3028: #$namespace=$env{'request.course.id'};
1.168 albertel 3029: #if (!$namespace) {
1.620 albertel 3030: $namespace=$env{'request.state'};
1.168 albertel 3031: #}
3032: }
3033: $namespace=~s/\//\_/g;
3034: $namespace=~s/\W//g;
1.620 albertel 3035: if (!$domain) { $domain=$env{'user.domain'}; }
3036: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3037: if ($domain eq 'public' && $stuname eq 'public') {
3038: $stuname=$ENV{'REMOTE_ADDR'};
3039: }
1.168 albertel 3040: my $now=time;
3041: my %hash;
3042: my $path=$perlvar{'lonDaemons'}.'/tmp';
3043: if (tie(%hash,'GDBM_File',
3044: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3045: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3046: $hash{"version:$symb"}++;
3047: my $version=$hash{"version:$symb"};
3048: my $allkeys='';
3049: foreach my $key (keys(%$storehash)) {
3050: $allkeys.=$key.':';
1.591 albertel 3051: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3052: }
3053: $hash{"$version:$symb:timestamp"}=$now;
3054: $allkeys.='timestamp';
3055: $hash{"$version:keys:$symb"}=$allkeys;
3056: if (untie(%hash)) {
3057: return 'ok';
3058: } else {
3059: return "error:$!";
3060: }
3061: } else {
3062: return "error:$!";
3063: }
3064: }
1.167 albertel 3065:
1.168 albertel 3066: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3067:
1.168 albertel 3068: sub tmprestore {
3069: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3070:
1.168 albertel 3071: if (!$symb) {
3072: $symb=&symbread();
1.620 albertel 3073: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3074: }
3075: $symb=escape($symb);
3076:
1.620 albertel 3077: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3078:
1.620 albertel 3079: if (!$domain) { $domain=$env{'user.domain'}; }
3080: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3081: if ($domain eq 'public' && $stuname eq 'public') {
3082: $stuname=$ENV{'REMOTE_ADDR'};
3083: }
1.168 albertel 3084: my %returnhash;
3085: $namespace=~s/\//\_/g;
3086: $namespace=~s/\W//g;
3087: my %hash;
3088: my $path=$perlvar{'lonDaemons'}.'/tmp';
3089: if (tie(%hash,'GDBM_File',
3090: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3091: &GDBM_READER(),0640)) {
1.168 albertel 3092: my $version=$hash{"version:$symb"};
3093: $returnhash{'version'}=$version;
3094: my $scope;
3095: for ($scope=1;$scope<=$version;$scope++) {
3096: my $vkeys=$hash{"$scope:keys:$symb"};
3097: my @keys=split(/:/,$vkeys);
3098: my $key;
3099: $returnhash{"$scope:keys"}=$vkeys;
3100: foreach $key (@keys) {
1.591 albertel 3101: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3102: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3103: }
3104: }
1.168 albertel 3105: if (!(untie(%hash))) {
3106: return "error:$!";
3107: }
3108: } else {
3109: return "error:$!";
3110: }
3111: return %returnhash;
1.167 albertel 3112: }
3113:
1.9 www 3114: # ----------------------------------------------------------------------- Store
3115:
3116: sub store {
1.124 www 3117: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3118: my $home='';
3119:
1.168 albertel 3120: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3121:
1.213 www 3122: $symb=&symbclean($symb);
1.122 albertel 3123: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3124:
1.620 albertel 3125: if (!$domain) { $domain=$env{'user.domain'}; }
3126: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3127:
3128: &devalidate($symb,$stuname,$domain);
1.109 www 3129:
3130: $symb=escape($symb);
1.187 www 3131: if (!$namespace) {
1.620 albertel 3132: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3133: return '';
3134: }
3135: }
1.620 albertel 3136: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3137:
3138: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3139: $$storehash{'host'}=$perlvar{'lonHostID'};
3140:
1.12 www 3141: my $namevalue='';
1.800 albertel 3142: foreach my $key (keys(%$storehash)) {
3143: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3144: }
1.12 www 3145: $namevalue=~s/\&$//;
1.187 www 3146: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3147: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3148: }
3149:
1.47 www 3150: # -------------------------------------------------------------- Critical Store
3151:
3152: sub cstore {
1.124 www 3153: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3154: my $home='';
3155:
1.168 albertel 3156: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3157:
1.213 www 3158: $symb=&symbclean($symb);
1.122 albertel 3159: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3160:
1.620 albertel 3161: if (!$domain) { $domain=$env{'user.domain'}; }
3162: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3163:
3164: &devalidate($symb,$stuname,$domain);
1.109 www 3165:
3166: $symb=escape($symb);
1.187 www 3167: if (!$namespace) {
1.620 albertel 3168: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3169: return '';
3170: }
3171: }
1.620 albertel 3172: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3173:
3174: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3175: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3176:
1.47 www 3177: my $namevalue='';
1.800 albertel 3178: foreach my $key (keys(%$storehash)) {
3179: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3180: }
1.47 www 3181: $namevalue=~s/\&$//;
1.187 www 3182: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3183: return critical
3184: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3185: }
3186:
1.9 www 3187: # --------------------------------------------------------------------- Restore
3188:
3189: sub restore {
1.124 www 3190: my ($symb,$namespace,$domain,$stuname) = @_;
3191: my $home='';
3192:
1.168 albertel 3193: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3194:
1.122 albertel 3195: if (!$symb) {
3196: unless ($symb=escape(&symbread())) { return ''; }
3197: } else {
1.213 www 3198: $symb=&escape(&symbclean($symb));
1.122 albertel 3199: }
1.188 www 3200: if (!$namespace) {
1.620 albertel 3201: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3202: return '';
3203: }
3204: }
1.620 albertel 3205: if (!$domain) { $domain=$env{'user.domain'}; }
3206: if (!$stuname) { $stuname=$env{'user.name'}; }
3207: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3208: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3209:
1.12 www 3210: my %returnhash=();
1.800 albertel 3211: foreach my $line (split(/\&/,$answer)) {
3212: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3213: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3214: }
1.75 www 3215: my $version;
3216: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3217: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3218: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3219: }
1.75 www 3220: }
1.13 www 3221: return %returnhash;
1.34 www 3222: }
3223:
3224: # ---------------------------------------------------------- Course Description
3225:
3226: sub coursedescription {
1.731 albertel 3227: my ($courseid,$args)=@_;
1.34 www 3228: $courseid=~s/^\///;
1.49 www 3229: $courseid=~s/\_/\//g;
1.34 www 3230: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3231: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3232: my $normalid=$cdomain.'_'.$cnum;
3233: # need to always cache even if we get errors otherwise we keep
3234: # trying and trying and trying to get the course description.
3235: my %envhash=();
3236: my %returnhash=();
1.731 albertel 3237:
3238: my $expiretime=600;
3239: if ($env{'request.course.id'} eq $normalid) {
3240: $expiretime=120;
3241: }
3242:
3243: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3244: if (!$args->{'freshen_cache'}
3245: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3246: foreach my $key (keys(%env)) {
3247: next if ($key !~ /^\Q$prefix\E(.*)/);
3248: my ($setting) = $1;
3249: $returnhash{$setting} = $env{$key};
3250: }
3251: return %returnhash;
3252: }
3253:
3254: # get the data agin
3255: if (!$args->{'one_time'}) {
3256: $envhash{'course.'.$normalid.'.last_cache'}=time;
3257: }
1.811 albertel 3258:
1.34 www 3259: if ($chome ne 'no_host') {
1.302 albertel 3260: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3261: if (!exists($returnhash{'con_lost'})) {
3262: $returnhash{'home'}= $chome;
3263: $returnhash{'domain'} = $cdomain;
3264: $returnhash{'num'} = $cnum;
1.741 raeburn 3265: if (!defined($returnhash{'type'})) {
3266: $returnhash{'type'} = 'Course';
3267: }
1.130 albertel 3268: while (my ($name,$value) = each %returnhash) {
1.53 www 3269: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3270: }
1.270 www 3271: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3272: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3273: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3274: $envhash{'course.'.$normalid.'.home'}=$chome;
3275: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3276: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3277: }
3278: }
1.731 albertel 3279: if (!$args->{'one_time'}) {
3280: &appenv(%envhash);
3281: }
1.302 albertel 3282: return %returnhash;
1.461 www 3283: }
3284:
3285: # -------------------------------------------------See if a user is privileged
3286:
3287: sub privileged {
3288: my ($username,$domain)=@_;
3289: my $rolesdump=&reply("dump:$domain:$username:roles",
3290: &homeserver($username,$domain));
3291: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
3292: my $now=time;
3293: if ($rolesdump ne '') {
1.800 albertel 3294: foreach my $entry (split(/&/,$rolesdump)) {
3295: if ($entry!~/^rolesdef_/) {
3296: my ($area,$role)=split(/=/,$entry);
1.461 www 3297: $area=~s/\_\w\w$//;
3298: my ($trole,$tend,$tstart)=split(/_/,$role);
3299: if (($trole eq 'dc') || ($trole eq 'su')) {
3300: my $active=1;
3301: if ($tend) {
3302: if ($tend<$now) { $active=0; }
3303: }
3304: if ($tstart) {
3305: if ($tstart>$now) { $active=0; }
3306: }
3307: if ($active) { return 1; }
3308: }
3309: }
3310: }
3311: }
3312: return 0;
1.9 www 3313: }
1.1 albertel 3314:
1.103 harris41 3315: # -------------------------------------------------------- Get user privileges
1.11 www 3316:
3317: sub rolesinit {
3318: my ($domain,$username,$authhost)=@_;
3319: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12 www 3320: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11 www 3321: my %allroles=();
1.678 raeburn 3322: my %allgroups=();
1.11 www 3323: my $now=time;
1.743 albertel 3324: my %userroles = ('user.login.time' => $now);
1.678 raeburn 3325: my $group_privs;
1.11 www 3326:
3327: if ($rolesdump ne '') {
1.800 albertel 3328: foreach my $entry (split(/&/,$rolesdump)) {
3329: if ($entry!~/^rolesdef_/) {
3330: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3331: $area=~s/\_\w\w$//;
1.678 raeburn 3332: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3333: if ($role=~/^cr/) {
1.807 albertel 3334: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3335: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3336: ($tend,$tstart)=split('_',$trest);
3337: } else {
3338: $trole=$role;
3339: }
1.678 raeburn 3340: } elsif ($role =~ m|^gr/|) {
3341: ($trole,$tend,$tstart) = split(/_/,$role);
3342: ($trole,$group_privs) = split(/\//,$trole);
3343: $group_privs = &unescape($group_privs);
1.587 albertel 3344: } else {
3345: ($trole,$tend,$tstart)=split(/_/,$role);
3346: }
1.743 albertel 3347: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3348: $username);
3349: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3350: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3351: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3352: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3353: my $spec=$trole.'.'.$area;
3354: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3355: if ($trole =~ /^cr\//) {
1.567 raeburn 3356: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3357: } elsif ($trole eq 'gr') {
3358: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3359: } else {
1.567 raeburn 3360: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3361: }
1.12 www 3362: }
1.662 raeburn 3363: }
1.191 harris41 3364: }
1.743 albertel 3365: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3366: $userroles{'user.adv'} = $adv;
3367: $userroles{'user.author'} = $author;
1.620 albertel 3368: $env{'user.adv'}=$adv;
1.11 www 3369: }
1.743 albertel 3370: return \%userroles;
1.11 www 3371: }
3372:
1.567 raeburn 3373: sub set_arearole {
3374: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3375: # log the associated role with the area
3376: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3377: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3378: }
3379:
3380: sub custom_roleprivs {
3381: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3382: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3383: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3384: if (&hostname($homsvr) ne '') {
1.567 raeburn 3385: my ($rdummy,$roledef)=
3386: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3387: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3388: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3389: if (defined($syspriv)) {
3390: $$allroles{'cm./'}.=':'.$syspriv;
3391: $$allroles{$spec.'./'}.=':'.$syspriv;
3392: }
3393: if ($tdomain ne '') {
3394: if (defined($dompriv)) {
3395: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3396: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3397: }
3398: if (($trest ne '') && (defined($coursepriv))) {
3399: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3400: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3401: }
3402: }
3403: }
3404: }
3405: }
3406:
1.678 raeburn 3407: sub group_roleprivs {
3408: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3409: my $access = 1;
3410: my $now = time;
3411: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3412: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3413: if ($access) {
1.811 albertel 3414: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3415: $$allgroups{$course}{$group} .=':'.$group_privs;
3416: }
3417: }
1.567 raeburn 3418:
3419: sub standard_roleprivs {
3420: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3421: if (defined($pr{$trole.':s'})) {
3422: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3423: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3424: }
3425: if ($tdomain ne '') {
3426: if (defined($pr{$trole.':d'})) {
3427: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3428: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3429: }
3430: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3431: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3432: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3433: }
3434: }
3435: }
3436:
3437: sub set_userprivs {
1.678 raeburn 3438: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 3439: my $author=0;
3440: my $adv=0;
1.678 raeburn 3441: my %grouproles = ();
3442: if (keys(%{$allgroups}) > 0) {
3443: foreach my $role (keys %{$allroles}) {
1.681 raeburn 3444: my ($trole,$area,$sec,$extendedarea);
1.881 raeburn 3445: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678 raeburn 3446: $trole = $1;
3447: $area = $2;
1.681 raeburn 3448: $sec = $3;
3449: $extendedarea = $area.$sec;
3450: if (exists($$allgroups{$area})) {
3451: foreach my $group (keys(%{$$allgroups{$area}})) {
3452: my $spec = $trole.'.'.$extendedarea;
3453: $grouproles{$spec.'.'.$area.'/'.$group} =
3454: $$allgroups{$area}{$group};
1.678 raeburn 3455: }
3456: }
3457: }
3458: }
3459: }
1.800 albertel 3460: foreach my $group (keys(%grouproles)) {
3461: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3462: }
1.800 albertel 3463: foreach my $role (keys(%{$allroles})) {
3464: my %thesepriv;
3465: if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
3466: foreach my $item (split(/:/,$$allroles{$role})) {
3467: if ($item ne '') {
3468: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3469: if ($restrictions eq '') {
3470: $thesepriv{$privilege}='F';
3471: } elsif ($thesepriv{$privilege} ne 'F') {
3472: $thesepriv{$privilege}.=$restrictions;
3473: }
3474: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3475: }
3476: }
3477: my $thesestr='';
1.800 albertel 3478: foreach my $priv (keys(%thesepriv)) {
3479: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3480: }
3481: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3482: }
3483: return ($author,$adv);
3484: }
3485:
1.12 www 3486: # --------------------------------------------------------------- get interface
3487:
3488: sub get {
1.131 albertel 3489: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3490: my $items='';
1.800 albertel 3491: foreach my $item (@$storearr) {
3492: $items.=&escape($item).'&';
1.191 harris41 3493: }
1.12 www 3494: $items=~s/\&$//;
1.620 albertel 3495: if (!$udomain) { $udomain=$env{'user.domain'}; }
3496: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 3497: my $uhome=&homeserver($uname,$udomain);
3498:
1.133 albertel 3499: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3500: my @pairs=split(/\&/,$rep);
1.273 albertel 3501: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
3502: return @pairs;
3503: }
1.15 www 3504: my %returnhash=();
1.42 www 3505: my $i=0;
1.800 albertel 3506: foreach my $item (@$storearr) {
3507: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3508: $i++;
1.191 harris41 3509: }
1.15 www 3510: return %returnhash;
1.27 www 3511: }
3512:
3513: # --------------------------------------------------------------- del interface
3514:
3515: sub del {
1.133 albertel 3516: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 3517: my $items='';
1.800 albertel 3518: foreach my $item (@$storearr) {
3519: $items.=&escape($item).'&';
1.191 harris41 3520: }
1.27 www 3521: $items=~s/\&$//;
1.620 albertel 3522: if (!$udomain) { $udomain=$env{'user.domain'}; }
3523: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3524: my $uhome=&homeserver($uname,$udomain);
3525:
3526: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3527: }
3528:
3529: # -------------------------------------------------------------- dump interface
3530:
3531: sub dump {
1.755 albertel 3532: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3533: if (!$udomain) { $udomain=$env{'user.domain'}; }
3534: if (!$uname) { $uname=$env{'user.name'}; }
3535: my $uhome=&homeserver($uname,$udomain);
3536: if ($regexp) {
3537: $regexp=&escape($regexp);
3538: } else {
3539: $regexp='.';
3540: }
3541: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3542: my @pairs=split(/\&/,$rep);
3543: my %returnhash=();
3544: foreach my $item (@pairs) {
3545: my ($key,$value)=split(/=/,$item,2);
3546: $key = &unescape($key);
3547: next if ($key =~ /^error: 2 /);
3548: $returnhash{$key}=&thaw_unescape($value);
3549: }
3550: return %returnhash;
1.407 www 3551: }
3552:
1.717 albertel 3553: # --------------------------------------------------------- dumpstore interface
3554:
3555: sub dumpstore {
3556: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 3557: if (!$udomain) { $udomain=$env{'user.domain'}; }
3558: if (!$uname) { $uname=$env{'user.name'}; }
3559: my $uhome=&homeserver($uname,$udomain);
3560: if ($regexp) {
3561: $regexp=&escape($regexp);
3562: } else {
3563: $regexp='.';
3564: }
3565: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3566: my @pairs=split(/\&/,$rep);
3567: my %returnhash=();
3568: foreach my $item (@pairs) {
3569: my ($key,$value)=split(/=/,$item,2);
3570: next if ($key =~ /^error: 2 /);
3571: $returnhash{$key}=&thaw_unescape($value);
3572: }
3573: return %returnhash;
1.717 albertel 3574: }
3575:
1.407 www 3576: # -------------------------------------------------------------- keys interface
3577:
3578: sub getkeys {
3579: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 3580: if (!$udomain) { $udomain=$env{'user.domain'}; }
3581: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 3582: my $uhome=&homeserver($uname,$udomain);
3583: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3584: my @keyarray=();
1.800 albertel 3585: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 3586: next if ($key =~ /^error: 2 /);
1.800 albertel 3587: push(@keyarray,&unescape($key));
1.407 www 3588: }
3589: return @keyarray;
1.318 matthew 3590: }
3591:
1.319 matthew 3592: # --------------------------------------------------------------- currentdump
3593: sub currentdump {
1.328 matthew 3594: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 3595: $courseid = $env{'request.course.id'} if (! defined($courseid));
3596: $sdom = $env{'user.domain'} if (! defined($sdom));
3597: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 3598: my $uhome = &homeserver($sname,$sdom);
3599: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 3600: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 3601: #
1.318 matthew 3602: my %returnhash=();
1.319 matthew 3603: #
3604: if ($rep eq "unknown_cmd") {
3605: # an old lond will not know currentdump
3606: # Do a dump and make it look like a currentdump
1.822 albertel 3607: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 3608: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3609: my %hash = @tmp;
3610: @tmp=();
1.424 matthew 3611: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 3612: } else {
3613: my @pairs=split(/\&/,$rep);
1.800 albertel 3614: foreach my $pair (@pairs) {
3615: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 3616: my ($symb,$param) = split(/:/,$key);
3617: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 3618: &thaw_unescape($value);
1.319 matthew 3619: }
1.191 harris41 3620: }
1.12 www 3621: return %returnhash;
1.424 matthew 3622: }
3623:
3624: sub convert_dump_to_currentdump{
3625: my %hash = %{shift()};
3626: my %returnhash;
3627: # Code ripped from lond, essentially. The only difference
3628: # here is the unescaping done by lonnet::dump(). Conceivably
3629: # we might run in to problems with parameter names =~ /^v\./
3630: while (my ($key,$value) = each(%hash)) {
3631: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 3632: $symb = &unescape($symb);
3633: $param = &unescape($param);
1.424 matthew 3634: next if ($v eq 'version' || $symb eq 'keys');
3635: next if (exists($returnhash{$symb}) &&
3636: exists($returnhash{$symb}->{$param}) &&
3637: $returnhash{$symb}->{'v.'.$param} > $v);
3638: $returnhash{$symb}->{$param}=$value;
3639: $returnhash{$symb}->{'v.'.$param}=$v;
3640: }
3641: #
3642: # Remove all of the keys in the hashes which keep track of
3643: # the version of the parameter.
3644: while (my ($symb,$param_hash) = each(%returnhash)) {
3645: # use a foreach because we are going to delete from the hash.
3646: foreach my $key (keys(%$param_hash)) {
3647: delete($param_hash->{$key}) if ($key =~ /^v\./);
3648: }
3649: }
3650: return \%returnhash;
1.12 www 3651: }
3652:
1.627 albertel 3653: # ------------------------------------------------------ critical inc interface
3654:
3655: sub cinc {
3656: return &inc(@_,'critical');
3657: }
3658:
1.449 matthew 3659: # --------------------------------------------------------------- inc interface
3660:
3661: sub inc {
1.627 albertel 3662: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 3663: if (!$udomain) { $udomain=$env{'user.domain'}; }
3664: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 3665: my $uhome=&homeserver($uname,$udomain);
3666: my $items='';
3667: if (! ref($store)) {
3668: # got a single value, so use that instead
3669: $items = &escape($store).'=&';
3670: } elsif (ref($store) eq 'SCALAR') {
3671: $items = &escape($$store).'=&';
3672: } elsif (ref($store) eq 'ARRAY') {
3673: $items = join('=&',map {&escape($_);} @{$store});
3674: } elsif (ref($store) eq 'HASH') {
3675: while (my($key,$value) = each(%{$store})) {
3676: $items.= &escape($key).'='.&escape($value).'&';
3677: }
3678: }
3679: $items=~s/\&$//;
1.627 albertel 3680: if ($critical) {
3681: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
3682: } else {
3683: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
3684: }
1.449 matthew 3685: }
3686:
1.12 www 3687: # --------------------------------------------------------------- put interface
3688:
3689: sub put {
1.134 albertel 3690: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3691: if (!$udomain) { $udomain=$env{'user.domain'}; }
3692: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3693: my $uhome=&homeserver($uname,$udomain);
1.12 www 3694: my $items='';
1.800 albertel 3695: foreach my $item (keys(%$storehash)) {
3696: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3697: }
1.12 www 3698: $items=~s/\&$//;
1.134 albertel 3699: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 3700: }
3701:
1.631 albertel 3702: # ------------------------------------------------------------ newput interface
3703:
3704: sub newput {
3705: my ($namespace,$storehash,$udomain,$uname)=@_;
3706: if (!$udomain) { $udomain=$env{'user.domain'}; }
3707: if (!$uname) { $uname=$env{'user.name'}; }
3708: my $uhome=&homeserver($uname,$udomain);
3709: my $items='';
3710: foreach my $key (keys(%$storehash)) {
3711: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3712: }
3713: $items=~s/\&$//;
3714: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
3715: }
3716:
3717: # --------------------------------------------------------- putstore interface
3718:
1.524 raeburn 3719: sub putstore {
1.715 albertel 3720: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 3721: if (!$udomain) { $udomain=$env{'user.domain'}; }
3722: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 3723: my $uhome=&homeserver($uname,$udomain);
3724: my $items='';
1.715 albertel 3725: foreach my $key (keys(%$storehash)) {
3726: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 3727: }
1.715 albertel 3728: $items=~s/\&$//;
1.716 albertel 3729: my $esc_symb=&escape($symb);
3730: my $esc_v=&escape($version);
1.715 albertel 3731: my $reply =
1.716 albertel 3732: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 3733: $uhome);
3734: if ($reply eq 'unknown_cmd') {
1.716 albertel 3735: # gfall back to way things use to be done
1.715 albertel 3736: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
3737: $uname);
1.524 raeburn 3738: }
1.715 albertel 3739: return $reply;
3740: }
3741:
3742: sub old_putstore {
1.716 albertel 3743: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3744: if (!$udomain) { $udomain=$env{'user.domain'}; }
3745: if (!$uname) { $uname=$env{'user.name'}; }
3746: my $uhome=&homeserver($uname,$udomain);
3747: my %newstorehash;
1.800 albertel 3748: foreach my $item (keys(%$storehash)) {
3749: my $key = $version.':'.&escape($symb).':'.$item;
3750: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 3751: }
3752: my $items='';
3753: my %allitems = ();
1.800 albertel 3754: foreach my $item (keys(%newstorehash)) {
3755: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 3756: my $key = $1.':keys:'.$2;
3757: $allitems{$key} .= $3.':';
3758: }
1.800 albertel 3759: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 3760: }
1.800 albertel 3761: foreach my $item (keys(%allitems)) {
3762: $allitems{$item} =~ s/\:$//;
3763: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 3764: }
3765: $items=~s/\&$//;
3766: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 3767: }
3768:
1.47 www 3769: # ------------------------------------------------------ critical put interface
3770:
3771: sub cput {
1.134 albertel 3772: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3773: if (!$udomain) { $udomain=$env{'user.domain'}; }
3774: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3775: my $uhome=&homeserver($uname,$udomain);
1.47 www 3776: my $items='';
1.800 albertel 3777: foreach my $item (keys(%$storehash)) {
3778: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3779: }
1.47 www 3780: $items=~s/\&$//;
1.134 albertel 3781: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3782: }
3783:
3784: # -------------------------------------------------------------- eget interface
3785:
3786: sub eget {
1.133 albertel 3787: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3788: my $items='';
1.800 albertel 3789: foreach my $item (@$storearr) {
3790: $items.=&escape($item).'&';
1.191 harris41 3791: }
1.12 www 3792: $items=~s/\&$//;
1.620 albertel 3793: if (!$udomain) { $udomain=$env{'user.domain'}; }
3794: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3795: my $uhome=&homeserver($uname,$udomain);
3796: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3797: my @pairs=split(/\&/,$rep);
3798: my %returnhash=();
1.42 www 3799: my $i=0;
1.800 albertel 3800: foreach my $item (@$storearr) {
3801: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3802: $i++;
1.191 harris41 3803: }
1.12 www 3804: return %returnhash;
3805: }
3806:
1.667 albertel 3807: # ------------------------------------------------------------ tmpput interface
3808: sub tmpput {
1.802 raeburn 3809: my ($storehash,$server,$context)=@_;
1.667 albertel 3810: my $items='';
1.800 albertel 3811: foreach my $item (keys(%$storehash)) {
3812: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 3813: }
3814: $items=~s/\&$//;
1.802 raeburn 3815: if (defined($context)) {
3816: $items .= ':'.&escape($context);
3817: }
1.667 albertel 3818: return &reply("tmpput:$items",$server);
3819: }
3820:
3821: # ------------------------------------------------------------ tmpget interface
3822: sub tmpget {
1.688 albertel 3823: my ($token,$server)=@_;
3824: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3825: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 3826: my %returnhash;
3827: foreach my $item (split(/\&/,$rep)) {
3828: my ($key,$value)=split(/=/,$item);
3829: $returnhash{&unescape($key)}=&thaw_unescape($value);
3830: }
3831: return %returnhash;
3832: }
3833:
1.688 albertel 3834: # ------------------------------------------------------------ tmpget interface
3835: sub tmpdel {
3836: my ($token,$server)=@_;
3837: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3838: return &reply("tmpdel:$token",$server);
3839: }
3840:
1.765 albertel 3841: # -------------------------------------------------- portfolio access checking
3842:
3843: sub portfolio_access {
1.766 albertel 3844: my ($requrl) = @_;
1.765 albertel 3845: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
3846: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 3847: if ($result) {
3848: my %setters;
3849: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3850: my ($startblock,$endblock) =
3851: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
3852: if ($startblock && $endblock) {
3853: return 'B';
3854: }
3855: } else {
3856: my ($startblock,$endblock) =
3857: &Apache::loncommon::blockcheck(\%setters,'port');
3858: if ($startblock && $endblock) {
3859: return 'B';
3860: }
3861: }
3862: }
1.765 albertel 3863: if ($result eq 'ok') {
1.766 albertel 3864: return 'F';
1.765 albertel 3865: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 3866: return 'A';
1.765 albertel 3867: }
1.766 albertel 3868: return '';
1.765 albertel 3869: }
3870:
3871: sub get_portfolio_access {
1.767 albertel 3872: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
3873:
3874: if (!ref($access_hash)) {
3875: my $current_perms = &get_portfile_permissions($udom,$unum);
3876: my %access_controls = &get_access_controls($current_perms,$group,
3877: $file_name);
3878: $access_hash = $access_controls{$file_name};
3879: }
3880:
1.765 albertel 3881: my ($public,$guest,@domains,@users,@courses,@groups);
3882: my $now = time;
3883: if (ref($access_hash) eq 'HASH') {
3884: foreach my $key (keys(%{$access_hash})) {
3885: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
3886: if ($start > $now) {
3887: next;
3888: }
3889: if ($end && $end<$now) {
3890: next;
3891: }
3892: if ($scope eq 'public') {
3893: $public = $key;
3894: last;
3895: } elsif ($scope eq 'guest') {
3896: $guest = $key;
3897: } elsif ($scope eq 'domains') {
3898: push(@domains,$key);
3899: } elsif ($scope eq 'users') {
3900: push(@users,$key);
3901: } elsif ($scope eq 'course') {
3902: push(@courses,$key);
3903: } elsif ($scope eq 'group') {
3904: push(@groups,$key);
3905: }
3906: }
3907: if ($public) {
3908: return 'ok';
3909: }
3910: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3911: if ($guest) {
3912: return $guest;
3913: }
3914: } else {
3915: if (@domains > 0) {
3916: foreach my $domkey (@domains) {
3917: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
3918: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
3919: return 'ok';
3920: }
3921: }
3922: }
3923: }
3924: if (@users > 0) {
3925: foreach my $userkey (@users) {
1.865 raeburn 3926: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
3927: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
3928: if (ref($item) eq 'HASH') {
3929: if (($item->{'uname'} eq $env{'user.name'}) &&
3930: ($item->{'udom'} eq $env{'user.domain'})) {
3931: return 'ok';
3932: }
3933: }
3934: }
3935: }
1.765 albertel 3936: }
3937: }
3938: my %roleshash;
3939: my @courses_and_groups = @courses;
3940: push(@courses_and_groups,@groups);
3941: if (@courses_and_groups > 0) {
3942: my (%allgroups,%allroles);
3943: my ($start,$end,$role,$sec,$group);
3944: foreach my $envkey (%env) {
1.811 albertel 3945: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 3946: my $cid = $2.'_'.$3;
3947: if ($1 eq 'gr') {
3948: $group = $4;
3949: $allgroups{$cid}{$group} = $env{$envkey};
3950: } else {
3951: if ($4 eq '') {
3952: $sec = 'none';
3953: } else {
3954: $sec = $4;
3955: }
3956: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3957: }
1.811 albertel 3958: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 3959: my $cid = $2.'_'.$3;
3960: if ($4 eq '') {
3961: $sec = 'none';
3962: } else {
3963: $sec = $4;
3964: }
3965: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3966: }
3967: }
3968: if (keys(%allroles) == 0) {
3969: return;
3970: }
3971: foreach my $key (@courses_and_groups) {
3972: my %content = %{$$access_hash{$key}};
3973: my $cnum = $content{'number'};
3974: my $cdom = $content{'domain'};
3975: my $cid = $cdom.'_'.$cnum;
3976: if (!exists($allroles{$cid})) {
3977: next;
3978: }
3979: foreach my $role_id (keys(%{$content{'roles'}})) {
3980: my @sections = @{$content{'roles'}{$role_id}{'section'}};
3981: my @groups = @{$content{'roles'}{$role_id}{'group'}};
3982: my @status = @{$content{'roles'}{$role_id}{'access'}};
3983: my @roles = @{$content{'roles'}{$role_id}{'role'}};
3984: foreach my $role (keys(%{$allroles{$cid}})) {
3985: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
3986: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
3987: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
3988: if (grep/^all$/,@sections) {
3989: return 'ok';
3990: } else {
3991: if (grep/^$sec$/,@sections) {
3992: return 'ok';
3993: }
3994: }
3995: }
3996: }
3997: if (keys(%{$allgroups{$cid}}) == 0) {
3998: if (grep/^none$/,@groups) {
3999: return 'ok';
4000: }
4001: } else {
4002: if (grep/^all$/,@groups) {
4003: return 'ok';
4004: }
4005: foreach my $group (keys(%{$allgroups{$cid}})) {
4006: if (grep/^$group$/,@groups) {
4007: return 'ok';
4008: }
4009: }
4010: }
4011: }
4012: }
4013: }
4014: }
4015: }
4016: if ($guest) {
4017: return $guest;
4018: }
4019: }
4020: }
4021: return;
4022: }
4023:
4024: sub course_group_datechecker {
4025: my ($dates,$now,$status) = @_;
4026: my ($start,$end) = split(/\./,$dates);
4027: if (!$start && !$end) {
4028: return 'ok';
4029: }
4030: if (grep/^active$/,@{$status}) {
4031: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4032: return 'ok';
4033: }
4034: }
4035: if (grep/^previous$/,@{$status}) {
4036: if ($end > $now ) {
4037: return 'ok';
4038: }
4039: }
4040: if (grep/^future$/,@{$status}) {
4041: if ($start > $now) {
4042: return 'ok';
4043: }
4044: }
4045: return;
4046: }
4047:
4048: sub parse_portfolio_url {
4049: my ($url) = @_;
4050:
4051: my ($type,$udom,$unum,$group,$file_name);
4052:
1.823 albertel 4053: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4054: $type = 1;
4055: $udom = $1;
4056: $unum = $2;
4057: $file_name = $3;
1.823 albertel 4058: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4059: $type = 2;
4060: $udom = $1;
4061: $unum = $2;
4062: $group = $3;
4063: $file_name = $3.'/'.$4;
4064: }
4065: if (wantarray) {
4066: return ($type,$udom,$unum,$file_name,$group);
4067: }
4068: return $type;
4069: }
4070:
4071: sub is_portfolio_url {
4072: my ($url) = @_;
4073: return scalar(&parse_portfolio_url($url));
4074: }
4075:
1.798 raeburn 4076: sub is_portfolio_file {
4077: my ($file) = @_;
1.820 raeburn 4078: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4079: return 1;
4080: }
4081: return;
4082: }
4083:
4084:
1.341 www 4085: # ---------------------------------------------- Custom access rule evaluation
4086:
4087: sub customaccess {
4088: my ($priv,$uri)=@_;
1.807 albertel 4089: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 4090: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 4091: $udom = &LONCAPA::clean_domain($udom);
4092: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 4093: my $access=0;
1.800 albertel 4094: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 4095: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4096: if ($type eq 'user') {
4097: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 4098: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 4099: if ($tdom) {
4100: if ($tdom ne $env{'user.domain'}) { next; }
4101: }
1.896 albertel 4102: if ($tuname) {
4103: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 4104: }
4105: $access=($effect eq 'allow');
4106: last;
4107: }
4108: } else {
4109: if ($role) {
4110: if ($role ne $urole) { next; }
4111: }
4112: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4113: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4114: if ($tdom) {
4115: if ($tdom ne $udom) { next; }
4116: }
4117: if ($tcrs) {
4118: if ($tcrs ne $ucrs) { next; }
4119: }
4120: if ($tsec) {
4121: if ($tsec ne $usec) { next; }
4122: }
4123: $access=($effect eq 'allow');
4124: last;
4125: }
4126: if ($realm eq '' && $role eq '') {
4127: $access=($effect eq 'allow');
4128: }
1.402 bowersj2 4129: }
1.341 www 4130: }
4131: return $access;
4132: }
4133:
1.103 harris41 4134: # ------------------------------------------------- Check for a user privilege
1.12 www 4135:
4136: sub allowed {
1.810 raeburn 4137: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 4138: my $ver_orguri=$uri;
1.439 www 4139: $uri=&deversion($uri);
1.152 www 4140: my $orguri=$uri;
1.52 www 4141: $uri=&declutter($uri);
1.809 raeburn 4142:
1.810 raeburn 4143: if ($priv eq 'evb') {
4144: # Evade communication block restrictions for specified role in a course
4145: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4146: return $1;
4147: } else {
4148: return;
4149: }
4150: }
4151:
1.620 albertel 4152: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 4153: # Free bre access to adm and meta resources
1.775 albertel 4154: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 4155: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4156: && ($priv eq 'bre')) {
1.14 www 4157: return 'F';
1.159 www 4158: }
4159:
1.545 banghart 4160: # Free bre access to user's own portfolio contents
1.714 raeburn 4161: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 4162: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 4163: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 4164: my %setters;
4165: my ($startblock,$endblock) =
4166: &Apache::loncommon::blockcheck(\%setters,'port');
4167: if ($startblock && $endblock) {
4168: return 'B';
4169: } else {
4170: return 'F';
4171: }
1.545 banghart 4172: }
4173:
1.762 raeburn 4174: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 4175: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
4176: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
4177: if (exists($env{'request.course.id'})) {
4178: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4179: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4180: if (($domain eq $cdom) && ($name eq $cnum)) {
4181: my $courseprivid=$env{'request.course.id'};
4182: $courseprivid=~s/\_/\//;
4183: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
4184: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
4185: return $1;
1.762 raeburn 4186: } else {
4187: if ($env{'request.course.sec'}) {
4188: $courseprivid.='/'.$env{'request.course.sec'};
4189: }
4190: if ($env{'user.priv.'.$env{'request.role'}.'./'.
4191: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
4192: return $2;
4193: }
1.714 raeburn 4194: }
4195: }
4196: }
4197: }
4198:
1.159 www 4199: # Free bre to public access
4200:
4201: if ($priv eq 'bre') {
1.238 www 4202: my $copyright=&metadata($uri,'copyright');
1.620 albertel 4203: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 4204: return 'F';
4205: }
1.238 www 4206: if ($copyright eq 'priv') {
4207: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4208: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 4209: return '';
4210: }
4211: }
4212: if ($copyright eq 'domain') {
4213: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4214: unless (($env{'user.domain'} eq $1) ||
4215: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 4216: return '';
4217: }
1.262 matthew 4218: }
1.620 albertel 4219: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 4220: # Library role, so allow browsing of resources in this domain.
4221: return 'F';
1.238 www 4222: }
1.341 www 4223: if ($copyright eq 'custom') {
4224: unless (&customaccess($priv,$uri)) { return ''; }
4225: }
1.14 www 4226: }
1.264 matthew 4227: # Domain coordinator is trying to create a course
1.620 albertel 4228: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 4229: # uri is the requested domain in this case.
4230: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 4231: # a role of dc for the domain in question.
1.620 albertel 4232: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 4233: }
1.29 www 4234:
1.52 www 4235: my $thisallowed='';
4236: my $statecond=0;
4237: my $courseprivid='';
4238:
4239: # Course
4240:
1.620 albertel 4241: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4242: $thisallowed.=$1;
4243: }
1.29 www 4244:
1.52 www 4245: # Domain
4246:
1.620 albertel 4247: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 4248: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4249: $thisallowed.=$1;
4250: }
1.52 www 4251:
4252: # Course: uri itself is a course
1.66 www 4253: my $courseuri=$uri;
4254: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 4255: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 4256:
1.620 albertel 4257: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 4258: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4259: $thisallowed.=$1;
4260: }
1.29 www 4261:
1.665 albertel 4262: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 4263: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 4264: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 4265: $thisallowed='';
1.671 raeburn 4266: my ($match)=&is_on_map($uri);
4267: if ($match) {
4268: if ($env{'user.priv.'.$env{'request.role'}.'./'}
4269: =~/\Q$priv\E\&([^\:]*)/) {
4270: $thisallowed.=$1;
4271: }
4272: } else {
1.705 albertel 4273: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 4274: if ($refuri) {
4275: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 4276: $thisallowed='F';
1.671 raeburn 4277: } else {
4278: $refuri=&declutter($refuri);
4279: my ($match) = &is_on_map($refuri);
4280: if ($match) {
4281: $thisallowed='F';
4282: }
1.669 raeburn 4283: }
1.671 raeburn 4284: }
4285: }
1.314 www 4286: }
1.492 albertel 4287:
1.766 albertel 4288: if ($priv eq 'bre'
4289: && $thisallowed ne 'F'
4290: && $thisallowed ne '2'
4291: && &is_portfolio_url($uri)) {
4292: $thisallowed = &portfolio_access($uri);
4293: }
4294:
1.52 www 4295: # Full access at system, domain or course-wide level? Exit.
1.29 www 4296:
4297: if ($thisallowed=~/F/) {
4298: return 'F';
4299: }
4300:
1.52 www 4301: # If this is generating or modifying users, exit with special codes
1.29 www 4302:
1.643 www 4303: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
4304: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 4305: my ($audom,$auname)=split('/',$uri);
1.643 www 4306: # no author name given, so this just checks on the general right to make a co-author in this domain
4307: unless ($auname) { return $thisallowed; }
4308: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 4309: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
4310: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
4311: ($audom ne $env{'request.role.domain'}))) { return ''; }
4312: }
1.52 www 4313: return $thisallowed;
4314: }
4315: #
1.103 harris41 4316: # Gathered so far: system, domain and course wide privileges
1.52 www 4317: #
4318: # Course: See if uri or referer is an individual resource that is part of
4319: # the course
4320:
1.620 albertel 4321: if ($env{'request.course.id'}) {
1.232 www 4322:
1.620 albertel 4323: $courseprivid=$env{'request.course.id'};
4324: if ($env{'request.course.sec'}) {
4325: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 4326: }
4327: $courseprivid=~s/\_/\//;
4328: my $checkreferer=1;
1.232 www 4329: my ($match,$cond)=&is_on_map($uri);
4330: if ($match) {
4331: $statecond=$cond;
1.620 albertel 4332: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4333: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4334: $thisallowed.=$1;
4335: $checkreferer=0;
4336: }
1.29 www 4337: }
1.83 www 4338:
1.148 www 4339: if ($checkreferer) {
1.620 albertel 4340: my $refuri=$env{'httpref.'.$orguri};
1.148 www 4341: unless ($refuri) {
1.800 albertel 4342: foreach my $key (keys(%env)) {
4343: if ($key=~/^httpref\..*\*/) {
4344: my $pattern=$key;
1.156 www 4345: $pattern=~s/^httpref\.\/res\///;
1.148 www 4346: $pattern=~s/\*/\[\^\/\]\+/g;
4347: $pattern=~s/\//\\\//g;
1.152 www 4348: if ($orguri=~/$pattern/) {
1.800 albertel 4349: $refuri=$env{$key};
1.148 www 4350: }
4351: }
1.191 harris41 4352: }
1.148 www 4353: }
1.232 www 4354:
1.148 www 4355: if ($refuri) {
1.152 www 4356: $refuri=&declutter($refuri);
1.232 www 4357: my ($match,$cond)=&is_on_map($refuri);
4358: if ($match) {
4359: my $refstatecond=$cond;
1.620 albertel 4360: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4361: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4362: $thisallowed.=$1;
1.53 www 4363: $uri=$refuri;
4364: $statecond=$refstatecond;
1.52 www 4365: }
4366: }
1.148 www 4367: }
1.29 www 4368: }
1.52 www 4369: }
1.29 www 4370:
1.52 www 4371: #
1.103 harris41 4372: # Gathered now: all privileges that could apply, and condition number
1.52 www 4373: #
4374: #
4375: # Full or no access?
4376: #
1.29 www 4377:
1.52 www 4378: if ($thisallowed=~/F/) {
4379: return 'F';
4380: }
1.29 www 4381:
1.52 www 4382: unless ($thisallowed) {
4383: return '';
4384: }
1.29 www 4385:
1.52 www 4386: # Restrictions exist, deal with them
4387: #
4388: # C:according to course preferences
4389: # R:according to resource settings
4390: # L:unless locked
4391: # X:according to user session state
4392: #
4393:
4394: # Possibly locked functionality, check all courses
1.54 www 4395: # Locks might take effect only after 10 minutes cache expiration for other
4396: # courses, and 2 minutes for current course
1.52 www 4397:
4398: my $envkey;
4399: if ($thisallowed=~/L/) {
1.620 albertel 4400: foreach $envkey (keys %env) {
1.54 www 4401: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
4402: my $courseid=$2;
4403: my $roleid=$1.'.'.$2;
1.92 www 4404: $courseid=~s/^\///;
1.54 www 4405: my $expiretime=600;
1.620 albertel 4406: if ($env{'request.role'} eq $roleid) {
1.54 www 4407: $expiretime=120;
4408: }
4409: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
4410: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 4411: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 4412: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 4413: }
1.620 albertel 4414: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
4415: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
4416: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
4417: &log($env{'user.domain'},$env{'user.name'},
4418: $env{'user.home'},
1.57 www 4419: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 4420: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4421: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4422: return '';
4423: }
4424: }
1.620 albertel 4425: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
4426: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
4427: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
4428: &log($env{'user.domain'},$env{'user.name'},
4429: $env{'user.home'},
1.57 www 4430: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 4431: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4432: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4433: return '';
4434: }
4435: }
4436: }
1.29 www 4437: }
1.52 www 4438: }
4439:
4440: #
4441: # Rest of the restrictions depend on selected course
4442: #
4443:
1.620 albertel 4444: unless ($env{'request.course.id'}) {
1.766 albertel 4445: if ($thisallowed eq 'A') {
4446: return 'A';
1.814 raeburn 4447: } elsif ($thisallowed eq 'B') {
4448: return 'B';
1.766 albertel 4449: } else {
4450: return '1';
4451: }
1.52 www 4452: }
1.29 www 4453:
1.52 www 4454: #
4455: # Now user is definitely in a course
4456: #
1.53 www 4457:
4458:
4459: # Course preferences
4460:
4461: if ($thisallowed=~/C/) {
1.620 albertel 4462: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4463: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
4464: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 4465: =~/\Q$rolecode\E/) {
1.689 albertel 4466: if ($priv ne 'pch') {
4467: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4468: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
4469: $env{'request.course.id'});
4470: }
1.237 www 4471: return '';
4472: }
4473:
1.620 albertel 4474: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 4475: =~/\Q$unamedom\E/) {
1.689 albertel 4476: if ($priv ne 'pch') {
4477: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
4478: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
4479: $env{'request.course.id'});
4480: }
1.54 www 4481: return '';
4482: }
1.53 www 4483: }
4484:
4485: # Resource preferences
4486:
4487: if ($thisallowed=~/R/) {
1.620 albertel 4488: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 4489: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 4490: if ($priv ne 'pch') {
4491: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4492: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
4493: }
4494: return '';
1.54 www 4495: }
1.53 www 4496: }
1.30 www 4497:
1.246 www 4498: # Restricted by state or randomout?
1.30 www 4499:
1.52 www 4500: if ($thisallowed=~/X/) {
1.620 albertel 4501: if ($env{'acc.randomout'}) {
1.579 albertel 4502: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 4503: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 4504: return '';
4505: }
1.247 www 4506: }
4507: if (&condval($statecond)) {
1.52 www 4508: return '2';
4509: } else {
4510: return '';
4511: }
4512: }
1.30 www 4513:
1.766 albertel 4514: if ($thisallowed eq 'A') {
4515: return 'A';
1.814 raeburn 4516: } elsif ($thisallowed eq 'B') {
4517: return 'B';
1.766 albertel 4518: }
1.52 www 4519: return 'F';
1.232 www 4520: }
4521:
1.710 albertel 4522: sub split_uri_for_cond {
4523: my $uri=&deversion(&declutter(shift));
4524: my @uriparts=split(/\//,$uri);
4525: my $filename=pop(@uriparts);
4526: my $pathname=join('/',@uriparts);
4527: return ($pathname,$filename);
4528: }
1.232 www 4529: # --------------------------------------------------- Is a resource on the map?
4530:
4531: sub is_on_map {
1.710 albertel 4532: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 4533: #Trying to find the conditional for the file
1.620 albertel 4534: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 4535: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 4536: if ($match) {
1.289 bowersj2 4537: return (1,$1);
4538: } else {
1.434 www 4539: return (0,0);
1.289 bowersj2 4540: }
1.12 www 4541: }
4542:
1.427 www 4543: # --------------------------------------------------------- Get symb from alias
4544:
4545: sub get_symb_from_alias {
4546: my $symb=shift;
4547: my ($map,$resid,$url)=&decode_symb($symb);
4548: # Already is a symb
4549: if ($url) { return $symb; }
4550: # Must be an alias
4551: my $aliassymb='';
4552: my %bighash;
1.620 albertel 4553: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 4554: &GDBM_READER(),0640)) {
4555: my $rid=$bighash{'mapalias_'.$symb};
4556: if ($rid) {
4557: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 4558: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
4559: $resid,$bighash{'src_'.$rid});
1.427 www 4560: }
4561: untie %bighash;
4562: }
4563: return $aliassymb;
4564: }
4565:
1.12 www 4566: # ----------------------------------------------------------------- Define Role
4567:
4568: sub definerole {
4569: if (allowed('mcr','/')) {
4570: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 4571: foreach my $role (split(':',$sysrole)) {
4572: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4573: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
4574: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
4575: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4576: return "refused:s:$crole&$cqual";
4577: }
4578: }
1.191 harris41 4579: }
1.800 albertel 4580: foreach my $role (split(':',$domrole)) {
4581: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4582: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
4583: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
4584: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 4585: return "refused:d:$crole&$cqual";
4586: }
4587: }
1.191 harris41 4588: }
1.800 albertel 4589: foreach my $role (split(':',$courole)) {
4590: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4591: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
4592: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
4593: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4594: return "refused:c:$crole&$cqual";
4595: }
4596: }
1.191 harris41 4597: }
1.620 albertel 4598: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4599: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 4600: "rolesdef_$rolename=".
4601: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 4602: return reply($command,$env{'user.home'});
1.12 www 4603: } else {
4604: return 'refused';
4605: }
1.105 harris41 4606: }
4607:
4608: # ---------------- Make a metadata query against the network of library servers
4609:
4610: sub metadata_query {
1.244 matthew 4611: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 4612: my %rhash;
1.845 albertel 4613: my %libserv = &all_library();
1.244 matthew 4614: my @server_list = (defined($server_array) ? @$server_array
4615: : keys(%libserv) );
4616: for my $server (@server_list) {
1.118 harris41 4617: unless ($custom or $customshow) {
4618: my $reply=&reply("querysend:".&escape($query),$server);
4619: $rhash{$server}=$reply;
4620: }
4621: else {
4622: my $reply=&reply("querysend:".&escape($query).':'.
4623: &escape($custom).':'.&escape($customshow),
4624: $server);
4625: $rhash{$server}=$reply;
4626: }
1.112 harris41 4627: }
1.118 harris41 4628: return \%rhash;
1.240 www 4629: }
4630:
4631: # ----------------------------------------- Send log queries and wait for reply
4632:
4633: sub log_query {
4634: my ($uname,$udom,$query,%filters)=@_;
4635: my $uhome=&homeserver($uname,$udom);
4636: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 4637: my $uhost=&hostname($uhome);
1.800 albertel 4638: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 4639: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
4640: $uhome);
1.479 albertel 4641: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 4642: return get_query_reply($queryid);
4643: }
4644:
1.818 raeburn 4645: # -------------------------- Update MySQL table for portfolio file
4646:
4647: sub update_portfolio_table {
1.821 raeburn 4648: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818 raeburn 4649: my $homeserver = &homeserver($uname,$udom);
4650: my $queryid=
1.821 raeburn 4651: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
4652: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 4653: my $reply = &get_query_reply($queryid);
4654: return $reply;
4655: }
4656:
1.899 raeburn 4657: # -------------------------- Update MySQL allusers table
4658:
4659: sub update_allusers_table {
4660: my ($uname,$udom,$names) = @_;
4661: my $homeserver = &homeserver($uname,$udom);
4662: my $queryid=
4663: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
4664: 'lastname='.&escape($names->{'lastname'}).'%%'.
4665: 'firstname='.&escape($names->{'firstname'}).'%%'.
4666: 'middlename='.&escape($names->{'middlename'}).'%%'.
4667: 'generation='.&escape($names->{'generation'}).'%%'.
4668: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
4669: 'id='.&escape($names->{'id'}),$homeserver);
4670: my $reply = &get_query_reply($queryid);
4671: return $reply;
4672: }
4673:
1.508 raeburn 4674: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 4675:
4676: sub fetch_enrollment_query {
1.511 raeburn 4677: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 4678: my $homeserver;
1.547 raeburn 4679: my $maxtries = 1;
1.508 raeburn 4680: if ($context eq 'automated') {
4681: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 4682: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 4683: } else {
4684: $homeserver = &homeserver($cnum,$dom);
4685: }
1.838 albertel 4686: my $host=&hostname($homeserver);
1.506 raeburn 4687: my $cmd = '';
1.800 albertel 4688: foreach my $affiliate (keys %{$affiliatesref}) {
4689: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 4690: }
4691: $cmd =~ s/%%$//;
4692: $cmd = &escape($cmd);
4693: my $query = 'fetchenrollment';
1.620 albertel 4694: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 4695: unless ($queryid=~/^\Q$host\E\_/) {
4696: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
4697: return 'error: '.$queryid;
4698: }
1.506 raeburn 4699: my $reply = &get_query_reply($queryid);
1.547 raeburn 4700: my $tries = 1;
4701: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4702: $reply = &get_query_reply($queryid);
4703: $tries ++;
4704: }
1.526 raeburn 4705: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 4706: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 4707: } else {
1.901 albertel 4708: my @responses = split(/:/,$reply);
1.515 raeburn 4709: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 4710: foreach my $line (@responses) {
4711: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 4712: $$replyref{$key} = $value;
4713: }
4714: } else {
1.506 raeburn 4715: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 4716: foreach my $line (@responses) {
4717: my ($key,$value) = split(/=/,$line);
1.506 raeburn 4718: $$replyref{$key} = $value;
4719: if ($value > 0) {
1.800 albertel 4720: foreach my $item (@{$$affiliatesref{$key}}) {
4721: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 4722: my $destname = $pathname.'/'.$filename;
4723: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 4724: if ($xml_classlist =~ /^error/) {
4725: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
4726: } else {
1.506 raeburn 4727: if ( open(FILE,">$destname") ) {
4728: print FILE &unescape($xml_classlist);
4729: close(FILE);
1.526 raeburn 4730: } else {
4731: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 4732: }
4733: }
4734: }
4735: }
4736: }
4737: }
4738: return 'ok';
4739: }
4740: return 'error';
4741: }
4742:
1.242 www 4743: sub get_query_reply {
4744: my $queryid=shift;
1.240 www 4745: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
4746: my $reply='';
4747: for (1..100) {
4748: sleep 2;
4749: if (-e $replyfile.'.end') {
1.448 albertel 4750: if (open(my $fh,$replyfile)) {
1.904 albertel 4751: $reply = join('',<$fh>);
4752: close($fh);
1.240 www 4753: } else { return 'error: reply_file_error'; }
1.242 www 4754: return &unescape($reply);
4755: }
1.240 www 4756: }
1.242 www 4757: return 'timeout:'.$queryid;
1.240 www 4758: }
4759:
4760: sub courselog_query {
1.241 www 4761: #
4762: # possible filters:
4763: # url: url or symb
4764: # username
4765: # domain
4766: # action: view, submit, grade
4767: # start: timestamp
4768: # end: timestamp
4769: #
1.240 www 4770: my (%filters)=@_;
1.620 albertel 4771: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 4772: if ($filters{'url'}) {
4773: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
4774: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
4775: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
4776: }
1.620 albertel 4777: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4778: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 4779: return &log_query($cname,$cdom,'courselog',%filters);
4780: }
4781:
4782: sub userlog_query {
1.858 raeburn 4783: #
4784: # possible filters:
4785: # action: log check role
4786: # start: timestamp
4787: # end: timestamp
4788: #
1.240 www 4789: my ($uname,$udom,%filters)=@_;
4790: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 4791: }
4792:
1.506 raeburn 4793: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
4794:
4795: sub auto_run {
1.508 raeburn 4796: my ($cnum,$cdom) = @_;
1.876 raeburn 4797: my $response = 0;
4798: my $settings;
4799: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
4800: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
4801: $settings = $domconfig{'autoenroll'};
4802: if ($settings->{'run'} eq '1') {
4803: $response = 1;
4804: }
4805: } else {
4806: my $homeserver = &homeserver($cnum,$cdom);
4807: $response = &reply('autorun:'.$cdom,$homeserver);
4808: }
1.506 raeburn 4809: return $response;
4810: }
1.776 albertel 4811:
1.506 raeburn 4812: sub auto_get_sections {
1.508 raeburn 4813: my ($cnum,$cdom,$inst_coursecode) = @_;
4814: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 4815: my @secs = ();
1.511 raeburn 4816: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 4817: unless ($response eq 'refused') {
1.901 albertel 4818: @secs = split(/:/,$response);
1.506 raeburn 4819: }
4820: return @secs;
4821: }
1.776 albertel 4822:
1.506 raeburn 4823: sub auto_new_course {
1.508 raeburn 4824: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
4825: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 4826: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 4827: return $response;
4828: }
1.776 albertel 4829:
1.506 raeburn 4830: sub auto_validate_courseID {
1.508 raeburn 4831: my ($cnum,$cdom,$inst_course_id) = @_;
4832: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 4833: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 4834: return $response;
4835: }
1.776 albertel 4836:
1.506 raeburn 4837: sub auto_create_password {
1.873 raeburn 4838: my ($cnum,$cdom,$authparam,$udom) = @_;
4839: my ($homeserver,$response);
1.506 raeburn 4840: my $create_passwd = 0;
4841: my $authchk = '';
1.873 raeburn 4842: if ($udom =~ /^$match_domain$/) {
4843: $homeserver = &domain($udom,'primary');
4844: }
4845: if ($homeserver eq '') {
4846: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
4847: $homeserver = &homeserver($cnum,$cdom);
4848: }
4849: }
4850: if ($homeserver eq '') {
4851: $authchk = 'nodomain';
1.506 raeburn 4852: } else {
1.873 raeburn 4853: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
4854: if ($response eq 'refused') {
4855: $authchk = 'refused';
4856: } else {
1.901 albertel 4857: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 4858: }
1.506 raeburn 4859: }
4860: return ($authparam,$create_passwd,$authchk);
4861: }
4862:
1.706 raeburn 4863: sub auto_photo_permission {
4864: my ($cnum,$cdom,$students) = @_;
4865: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 4866: my ($outcome,$perm_reqd,$conditions) =
4867: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 4868: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4869: return (undef,undef);
4870: }
1.706 raeburn 4871: return ($outcome,$perm_reqd,$conditions);
4872: }
4873:
4874: sub auto_checkphotos {
4875: my ($uname,$udom,$pid) = @_;
4876: my $homeserver = &homeserver($uname,$udom);
4877: my ($result,$resulttype);
4878: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 4879: &escape($uname).':'.&escape($pid),
4880: $homeserver));
1.709 albertel 4881: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4882: return (undef,undef);
4883: }
1.706 raeburn 4884: if ($outcome) {
4885: ($result,$resulttype) = split(/:/,$outcome);
4886: }
4887: return ($result,$resulttype);
4888: }
4889:
4890: sub auto_photochoice {
4891: my ($cnum,$cdom) = @_;
4892: my $homeserver = &homeserver($cnum,$cdom);
4893: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 4894: &escape($cdom),
4895: $homeserver)));
1.709 albertel 4896: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4897: return (undef,undef);
4898: }
1.706 raeburn 4899: return ($update,$comment);
4900: }
4901:
4902: sub auto_photoupdate {
4903: my ($affiliatesref,$dom,$cnum,$photo) = @_;
4904: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 4905: my $host=&hostname($homeserver);
1.706 raeburn 4906: my $cmd = '';
4907: my $maxtries = 1;
1.800 albertel 4908: foreach my $affiliate (keys(%{$affiliatesref})) {
4909: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 4910: }
4911: $cmd =~ s/%%$//;
4912: $cmd = &escape($cmd);
4913: my $query = 'institutionalphotos';
4914: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
4915: unless ($queryid=~/^\Q$host\E\_/) {
4916: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
4917: return 'error: '.$queryid;
4918: }
4919: my $reply = &get_query_reply($queryid);
4920: my $tries = 1;
4921: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4922: $reply = &get_query_reply($queryid);
4923: $tries ++;
4924: }
4925: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
4926: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
4927: } else {
4928: my @responses = split(/:/,$reply);
4929: my $outcome = shift(@responses);
4930: foreach my $item (@responses) {
4931: my ($key,$value) = split(/=/,$item);
4932: $$photo{$key} = $value;
4933: }
4934: return $outcome;
4935: }
4936: return 'error';
4937: }
4938:
1.521 raeburn 4939: sub auto_instcode_format {
1.793 albertel 4940: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
4941: $cat_order) = @_;
1.521 raeburn 4942: my $courses = '';
1.772 raeburn 4943: my @homeservers;
1.521 raeburn 4944: if ($caller eq 'global') {
1.841 albertel 4945: my %servers = &get_servers($codedom,'library');
4946: foreach my $tryserver (keys(%servers)) {
4947: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4948: push(@homeservers,$tryserver);
4949: }
1.584 raeburn 4950: }
1.521 raeburn 4951: } else {
1.772 raeburn 4952: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 4953: }
1.793 albertel 4954: foreach my $code (keys(%{$instcodes})) {
4955: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 4956: }
4957: chop($courses);
1.772 raeburn 4958: my $ok_response = 0;
4959: my $response;
4960: while (@homeservers > 0 && $ok_response == 0) {
4961: my $server = shift(@homeservers);
4962: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
4963: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
4964: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 4965: split(/:/,$response);
1.772 raeburn 4966: %{$codes} = (%{$codes},&str2hash($codes_str));
4967: push(@{$codetitles},&str2array($codetitles_str));
4968: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
4969: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
4970: $ok_response = 1;
4971: }
4972: }
4973: if ($ok_response) {
1.521 raeburn 4974: return 'ok';
1.772 raeburn 4975: } else {
4976: return $response;
1.521 raeburn 4977: }
4978: }
4979:
1.792 raeburn 4980: sub auto_instcode_defaults {
4981: my ($domain,$returnhash,$code_order) = @_;
4982: my @homeservers;
1.841 albertel 4983:
4984: my %servers = &get_servers($domain,'library');
4985: foreach my $tryserver (keys(%servers)) {
4986: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4987: push(@homeservers,$tryserver);
4988: }
1.792 raeburn 4989: }
1.841 albertel 4990:
1.792 raeburn 4991: my $response;
1.841 albertel 4992: foreach my $server (@homeservers) {
1.792 raeburn 4993: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 4994: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
4995:
4996: foreach my $pair (split(/\&/,$response)) {
4997: my ($name,$value)=split(/\=/,$pair);
4998: if ($name eq 'code_order') {
4999: @{$code_order} = split(/\&/,&unescape($value));
5000: } else {
5001: $returnhash->{&unescape($name)}=&unescape($value);
5002: }
5003: }
5004: return 'ok';
1.792 raeburn 5005: }
1.841 albertel 5006:
5007: return $response;
1.792 raeburn 5008: }
5009:
1.777 albertel 5010: sub auto_validate_class_sec {
1.918 raeburn 5011: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 5012: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 5013: my $ownerlist;
5014: if (ref($owners) eq 'ARRAY') {
5015: $ownerlist = join(',',@{$owners});
5016: } else {
5017: $ownerlist = $owners;
5018: }
1.773 raeburn 5019: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 5020: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 5021: return $response;
5022: }
5023:
1.679 raeburn 5024: # ------------------------------------------------------- Course Group routines
5025:
5026: sub get_coursegroups {
1.809 raeburn 5027: my ($cdom,$cnum,$group,$namespace) = @_;
5028: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 5029: }
5030:
1.679 raeburn 5031: sub modify_coursegroup {
5032: my ($cdom,$cnum,$groupsettings) = @_;
5033: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
5034: }
5035:
1.809 raeburn 5036: sub toggle_coursegroup_status {
5037: my ($cdom,$cnum,$group,$action) = @_;
5038: my ($from_namespace,$to_namespace);
5039: if ($action eq 'delete') {
5040: $from_namespace = 'coursegroups';
5041: $to_namespace = 'deleted_groups';
5042: } else {
5043: $from_namespace = 'deleted_groups';
5044: $to_namespace = 'coursegroups';
5045: }
5046: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 5047: if (my $tmp = &error(%curr_group)) {
5048: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
5049: return ('read error',$tmp);
5050: } else {
5051: my %savedsettings = %curr_group;
1.809 raeburn 5052: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 5053: my $deloutcome;
5054: if ($result eq 'ok') {
1.809 raeburn 5055: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 5056: } else {
5057: return ('write error',$result);
5058: }
5059: if ($deloutcome eq 'ok') {
5060: return 'ok';
5061: } else {
5062: return ('delete error',$deloutcome);
5063: }
5064: }
5065: }
5066:
1.679 raeburn 5067: sub modify_group_roles {
5068: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
5069: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
5070: my $role = 'gr/'.&escape($userprivs);
5071: my ($uname,$udom) = split(/:/,$user);
5072: my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684 raeburn 5073: if ($result eq 'ok') {
5074: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
5075: }
1.679 raeburn 5076: return $result;
5077: }
5078:
5079: sub modify_coursegroup_membership {
5080: my ($cdom,$cnum,$membership) = @_;
5081: my $result = &put('groupmembership',$membership,$cdom,$cnum);
5082: return $result;
5083: }
5084:
1.682 raeburn 5085: sub get_active_groups {
5086: my ($udom,$uname,$cdom,$cnum) = @_;
5087: my $now = time;
5088: my %groups = ();
5089: foreach my $key (keys(%env)) {
1.811 albertel 5090: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 5091: my ($start,$end) = split(/\./,$env{$key});
5092: if (($end!=0) && ($end<$now)) { next; }
5093: if (($start!=0) && ($start>$now)) { next; }
5094: if ($1 eq $cdom && $2 eq $cnum) {
5095: $groups{$3} = $env{$key} ;
5096: }
5097: }
5098: }
5099: return %groups;
5100: }
5101:
1.683 raeburn 5102: sub get_group_membership {
5103: my ($cdom,$cnum,$group) = @_;
5104: return(&dump('groupmembership',$cdom,$cnum,$group));
5105: }
5106:
5107: sub get_users_groups {
5108: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 5109: my @usersgroups;
1.683 raeburn 5110: my $cachetime=1800;
5111:
5112: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 5113: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
5114: if (defined($cached)) {
1.734 albertel 5115: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 5116: } else {
5117: $grouplist = '';
1.816 raeburn 5118: my $courseurl = &courseid_to_courseurl($courseid);
5119: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 5120: my $access_end = $env{'course.'.$courseid.
5121: '.default_enrollment_end_date'};
5122: my $now = time;
5123: foreach my $key (keys(%roleshash)) {
5124: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
5125: my $group = $1;
5126: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
5127: my $start = $2;
5128: my $end = $1;
5129: if ($start == -1) { next; } # deleted from group
5130: if (($start!=0) && ($start>$now)) { next; }
5131: if (($end!=0) && ($end<$now)) {
5132: if ($access_end && $access_end < $now) {
5133: if ($access_end - $end < 86400) {
5134: push(@usersgroups,$group);
1.733 raeburn 5135: }
5136: }
1.817 raeburn 5137: next;
1.733 raeburn 5138: }
1.817 raeburn 5139: push(@usersgroups,$group);
1.683 raeburn 5140: }
5141: }
5142: }
1.817 raeburn 5143: @usersgroups = &sort_course_groups($courseid,@usersgroups);
5144: $grouplist = join(':',@usersgroups);
5145: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 5146: }
1.733 raeburn 5147: return @usersgroups;
1.683 raeburn 5148: }
5149:
5150: sub devalidate_getgroups_cache {
5151: my ($udom,$uname,$cdom,$cnum)=@_;
5152: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 5153:
1.683 raeburn 5154: my $hashid="$udom:$uname:$courseid";
5155: &devalidate_cache_new('getgroups',$hashid);
5156: }
5157:
1.12 www 5158: # ------------------------------------------------------------------ Plain Text
5159:
5160: sub plaintext {
1.742 raeburn 5161: my ($short,$type,$cid) = @_;
1.758 albertel 5162: if ($short =~ /^cr/) {
5163: return (split('/',$short))[-1];
5164: }
1.742 raeburn 5165: if (!defined($cid)) {
5166: $cid = $env{'request.course.id'};
5167: }
5168: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
5169: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
5170: '.plaintext'});
5171: }
5172: my %rolenames = (
5173: Course => 'std',
5174: Group => 'alt1',
5175: );
5176: if (defined($type) &&
5177: defined($rolenames{$type}) &&
5178: defined($prp{$short}{$rolenames{$type}})) {
5179: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
5180: } else {
5181: return &Apache::lonlocal::mt($prp{$short}{'std'});
5182: }
1.12 www 5183: }
5184:
5185: # ----------------------------------------------------------------- Assign Role
5186:
5187: sub assignrole {
1.357 www 5188: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21 www 5189: my $mrole;
5190: if ($role =~ /^cr\//) {
1.393 www 5191: my $cwosec=$url;
1.811 albertel 5192: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 5193: unless (&allowed('ccr',$cwosec)) {
1.104 www 5194: &logthis('Refused custom assignrole: '.
5195: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 5196: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 5197: return 'refused';
5198: }
1.21 www 5199: $mrole='cr';
1.678 raeburn 5200: } elsif ($role =~ /^gr\//) {
5201: my $cwogrp=$url;
1.811 albertel 5202: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 5203: unless (&allowed('mdg',$cwogrp)) {
5204: &logthis('Refused group assignrole: '.
5205: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
5206: $env{'user.name'}.' at '.$env{'user.domain'});
5207: return 'refused';
5208: }
5209: $mrole='gr';
1.21 www 5210: } else {
1.82 www 5211: my $cwosec=$url;
1.811 albertel 5212: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373 www 5213: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
1.104 www 5214: &logthis('Refused assignrole: '.
5215: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 5216: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 5217: return 'refused';
5218: }
1.21 www 5219: $mrole=$role;
5220: }
1.620 albertel 5221: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5222: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 5223: if ($end) { $command.='_'.$end; }
1.21 www 5224: if ($start) {
5225: if ($end) {
1.81 www 5226: $command.='_'.$start;
1.21 www 5227: } else {
1.81 www 5228: $command.='_0_'.$start;
1.21 www 5229: }
5230: }
1.739 raeburn 5231: my $origstart = $start;
5232: my $origend = $end;
1.357 www 5233: # actually delete
5234: if ($deleteflag) {
1.373 www 5235: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 5236: # modify command to delete the role
1.620 albertel 5237: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 5238: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 5239: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 5240: # set start and finish to negative values for userrolelog
5241: $start=-1;
5242: $end=-1;
5243: }
5244: }
5245: # send command
1.349 www 5246: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 5247: # log new user role if status is ok
1.349 www 5248: if ($answer eq 'ok') {
1.663 raeburn 5249: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 5250: # for course roles, perform group memberships changes triggered by role change.
5251: unless ($role =~ /^gr/) {
5252: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
5253: $origstart);
5254: }
1.349 www 5255: }
5256: return $answer;
1.169 harris41 5257: }
5258:
5259: # -------------------------------------------------- Modify user authentication
1.197 www 5260: # Overrides without validation
5261:
1.169 harris41 5262: sub modifyuserauth {
5263: my ($udom,$uname,$umode,$upass)=@_;
5264: my $uhome=&homeserver($uname,$udom);
1.197 www 5265: unless (&allowed('mau',$udom)) { return 'refused'; }
5266: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 5267: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5268: ' in domain '.$env{'request.role.domain'});
1.169 harris41 5269: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
5270: &escape($upass),$uhome);
1.620 albertel 5271: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 5272: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
5273: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
5274: &log($udom,,$uname,$uhome,
1.620 albertel 5275: 'Authentication changed by '.$env{'user.domain'}.', '.
5276: $env{'user.name'}.', '.$umode.
1.197 www 5277: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 5278: unless ($reply eq 'ok') {
1.197 www 5279: &logthis('Authentication mode error: '.$reply);
1.169 harris41 5280: return 'error: '.$reply;
5281: }
1.170 harris41 5282: return 'ok';
1.80 www 5283: }
5284:
1.81 www 5285: # --------------------------------------------------------------- Modify a user
1.80 www 5286:
1.81 www 5287: sub modifyuser {
1.206 matthew 5288: my ($udom, $uname, $uid,
5289: $umode, $upass, $first,
5290: $middle, $last, $gene,
1.387 www 5291: $forceid, $desiredhome, $email)=@_;
1.807 albertel 5292: $udom= &LONCAPA::clean_domain($udom);
5293: $uname=&LONCAPA::clean_username($uname);
1.81 www 5294: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 5295: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 5296: $last.', '.$gene.'(forceid: '.$forceid.')'.
5297: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
5298: ' desiredhome not specified').
1.620 albertel 5299: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5300: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 5301: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 5302: # ----------------------------------------------------------------- Create User
1.406 albertel 5303: if (($uhome eq 'no_host') &&
5304: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 5305: my $unhome='';
1.844 albertel 5306: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 5307: $unhome = $desiredhome;
1.620 albertel 5308: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
5309: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 5310: } else { # load balancing routine for determining $unhome
1.81 www 5311: my $loadm=10000000;
1.841 albertel 5312: my %servers = &get_servers($udom,'library');
5313: foreach my $tryserver (keys(%servers)) {
5314: my $answer=reply('load',$tryserver);
5315: if (($answer=~/\d+/) && ($answer<$loadm)) {
5316: $loadm=$answer;
5317: $unhome=$tryserver;
5318: }
1.80 www 5319: }
5320: }
5321: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 5322: return 'error: unable to find a home server for '.$uname.
5323: ' in domain '.$udom;
1.80 www 5324: }
5325: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
5326: &escape($upass),$unhome);
5327: unless ($reply eq 'ok') {
5328: return 'error: '.$reply;
5329: }
1.230 stredwic 5330: $uhome=&homeserver($uname,$udom,'true');
1.80 www 5331: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 5332: return 'error: unable verify users home machine.';
1.80 www 5333: }
1.209 matthew 5334: } # End of creation of new user
1.80 www 5335: # ---------------------------------------------------------------------- Add ID
5336: if ($uid) {
5337: $uid=~tr/A-Z/a-z/;
5338: my %uidhash=&idrget($udom,$uname);
1.196 www 5339: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
5340: && (!$forceid)) {
1.80 www 5341: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 5342: return 'error: user id "'.$uid.'" does not match '.
5343: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 5344: }
5345: } else {
5346: &idput($udom,($uname => $uid));
5347: }
5348: }
5349: # -------------------------------------------------------------- Add names, etc
1.313 matthew 5350: my @tmp=&get('environment',
1.899 raeburn 5351: ['firstname','middlename','lastname','generation','id',
5352: 'permanentemail'],
1.134 albertel 5353: $udom,$uname);
1.313 matthew 5354: my %names;
5355: if ($tmp[0] =~ m/^error:.*/) {
5356: %names=();
5357: } else {
5358: %names = @tmp;
5359: }
1.388 www 5360: #
5361: # Make sure to not trash student environment if instructor does not bother
5362: # to supply name and email information
5363: #
5364: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 5365: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 5366: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 5367: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 5368: if ($email) {
5369: $email=~s/[^\w\@\.\-\,]//gs;
5370: if ($email=~/\@/) { $names{'notification'} = $email;
5371: $names{'critnotification'} = $email;
5372: $names{'permanentemail'} = $email; }
5373: }
1.899 raeburn 5374: if ($uid) { $names{'id'} = $uid; }
1.134 albertel 5375: my $reply = &put('environment', \%names, $udom,$uname);
5376: if ($reply ne 'ok') { return 'error: '.$reply; }
1.899 raeburn 5377: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680 www 5378: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81 www 5379: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 5380: $umode.', '.$first.', '.$middle.', '.
5381: $last.', '.$gene.' by '.
1.620 albertel 5382: $env{'user.name'}.' at '.$env{'user.domain'});
1.134 albertel 5383: return 'ok';
1.80 www 5384: }
5385:
1.81 www 5386: # -------------------------------------------------------------- Modify student
1.80 www 5387:
1.81 www 5388: sub modifystudent {
5389: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515 raeburn 5390: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455 albertel 5391: if (!$cid) {
1.620 albertel 5392: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5393: return 'not_in_class';
5394: }
1.80 www 5395: }
5396: # --------------------------------------------------------------- Make the user
1.81 www 5397: my $reply=&modifyuser
1.209 matthew 5398: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 5399: $desiredhome,$email);
1.80 www 5400: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 5401: # This will cause &modify_student_enrollment to get the uid from the
5402: # students environment
5403: $uid = undef if (!$forceid);
1.455 albertel 5404: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515 raeburn 5405: $gene,$usec,$end,$start,$type,$locktype,$cid);
1.297 matthew 5406: return $reply;
5407: }
5408:
5409: sub modify_student_enrollment {
1.515 raeburn 5410: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455 albertel 5411: my ($cdom,$cnum,$chome);
5412: if (!$cid) {
1.620 albertel 5413: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5414: return 'not_in_class';
5415: }
1.620 albertel 5416: $cdom=$env{'course.'.$cid.'.domain'};
5417: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 5418: } else {
5419: ($cdom,$cnum)=split(/_/,$cid);
5420: }
1.620 albertel 5421: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 5422: if (!$chome) {
1.457 raeburn 5423: $chome=&homeserver($cnum,$cdom);
1.297 matthew 5424: }
1.455 albertel 5425: if (!$chome) { return 'unknown_course'; }
1.297 matthew 5426: # Make sure the user exists
1.81 www 5427: my $uhome=&homeserver($uname,$udom);
5428: if (($uhome eq '') || ($uhome eq 'no_host')) {
5429: return 'error: no such user';
5430: }
1.297 matthew 5431: # Get student data if we were not given enough information
5432: if (!defined($first) || $first eq '' ||
5433: !defined($last) || $last eq '' ||
5434: !defined($uid) || $uid eq '' ||
5435: !defined($middle) || $middle eq '' ||
5436: !defined($gene) || $gene eq '') {
1.294 matthew 5437: # They did not supply us with enough data to enroll the student, so
5438: # we need to pick up more information.
1.297 matthew 5439: my %tmp = &get('environment',
1.294 matthew 5440: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 5441: ,$udom,$uname);
5442:
1.800 albertel 5443: #foreach my $key (keys(%tmp)) {
5444: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 5445: #}
1.294 matthew 5446: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
5447: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
5448: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 5449: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 5450: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
5451: }
1.556 albertel 5452: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 5453: my $reply=cput('classlist',
5454: {"$uname:$udom" =>
1.515 raeburn 5455: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 5456: $cdom,$cnum);
1.81 www 5457: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
5458: return 'error: '.$reply;
1.652 albertel 5459: } else {
5460: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 5461: }
1.297 matthew 5462: # Add student role to user
1.83 www 5463: my $uurl='/'.$cid;
1.81 www 5464: $uurl=~s/\_/\//g;
5465: if ($usec) {
5466: $uurl.='/'.$usec;
5467: }
5468: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21 www 5469: }
5470:
1.556 albertel 5471: sub format_name {
5472: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
5473: my $name;
5474: if ($first ne 'lastname') {
5475: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
5476: } else {
5477: if ($lastname=~/\S/) {
5478: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
5479: $name=~s/\s+,/,/;
5480: } else {
5481: $name.= $firstname.' '.$middlename.' '.$generation;
5482: }
5483: }
5484: $name=~s/^\s+//;
5485: $name=~s/\s+$//;
5486: $name=~s/\s+/ /g;
5487: return $name;
5488: }
5489:
1.84 www 5490: # ------------------------------------------------- Write to course preferences
5491:
5492: sub writecoursepref {
5493: my ($courseid,%prefs)=@_;
5494: $courseid=~s/^\///;
5495: $courseid=~s/\_/\//g;
5496: my ($cdomain,$cnum)=split(/\//,$courseid);
5497: my $chome=homeserver($cnum,$cdomain);
5498: if (($chome eq '') || ($chome eq 'no_host')) {
5499: return 'error: no such course';
5500: }
5501: my $cstring='';
1.800 albertel 5502: foreach my $pref (keys(%prefs)) {
5503: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 5504: }
1.84 www 5505: $cstring=~s/\&$//;
5506: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
5507: }
5508:
5509: # ---------------------------------------------------------- Make/modify course
5510:
5511: sub createcourse {
1.741 raeburn 5512: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
5513: $course_owner,$crstype)=@_;
1.84 www 5514: $url=&declutter($url);
5515: my $cid='';
1.264 matthew 5516: unless (&allowed('ccc',$udom)) {
1.84 www 5517: return 'refused';
5518: }
5519: # ------------------------------------------------------------------- Create ID
1.674 www 5520: my $uname=int(1+rand(9)).
5521: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
5522: substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84 www 5523: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
5524: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 5525: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 5526: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5527: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
5528: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 5529: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5530: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5531: return 'error: unable to generate unique course-ID';
5532: }
5533: }
1.264 matthew 5534: # ------------------------------------------------ Check supplied server name
1.620 albertel 5535: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845 albertel 5536: if (! &is_library($course_server)) {
1.264 matthew 5537: return 'error:bad server name '.$course_server;
5538: }
1.84 www 5539: # ------------------------------------------------------------- Make the course
5540: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 5541: $course_server);
1.84 www 5542: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 5543: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5544: if (($uhome eq '') || ($uhome eq 'no_host')) {
5545: return 'error: no such course';
5546: }
1.271 www 5547: # ----------------------------------------------------------------- Course made
1.516 raeburn 5548: # log existence
1.918 raeburn 5549: my $newcourse = {
5550: $udom.'_'.$uname => {
5551: description => &escape($description),
5552: inst_code => &escape($inst_code),
5553: owner => &escape($course_owner),
5554: type => &escape($crstype),
5555: },
5556: };
5557: &courseidput($udom,$newcourse);
1.358 www 5558: &flushcourselogs();
5559: # set toplevel url
1.271 www 5560: my $topurl=$url;
5561: unless ($nonstandard) {
5562: # ------------------------------------------ For standard courses, make top url
5563: my $mapurl=&clutter($url);
1.278 www 5564: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 5565: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 5566: <map>
5567: <resource id="1" type="start"></resource>
5568: <resource id="2" src="$mapurl"></resource>
5569: <resource id="3" type="finish"></resource>
5570: <link index="1" from="1" to="2"></link>
5571: <link index="2" from="2" to="3"></link>
5572: </map>
5573: ENDINITMAP
5574: $topurl=&declutter(
1.638 albertel 5575: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 5576: );
5577: }
5578: # ----------------------------------------------------------- Write preferences
1.84 www 5579: &writecoursepref($udom.'_'.$uname,
5580: ('description' => $description,
1.271 www 5581: 'url' => $topurl));
1.84 www 5582: return '/'.$udom.'/'.$uname;
5583: }
5584:
1.813 albertel 5585: sub is_course {
5586: my ($cdom,$cnum) = @_;
5587: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.918 raeburn 5588: undef,'.',undef,1);
1.813 albertel 5589: if (exists($courses{$cdom.'_'.$cnum})) {
5590: return 1;
5591: }
5592: return 0;
5593: }
5594:
1.21 www 5595: # ---------------------------------------------------------- Assign Custom Role
5596:
5597: sub assigncustomrole {
1.357 www 5598: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21 www 5599: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357 www 5600: $end,$start,$deleteflag);
1.21 www 5601: }
5602:
5603: # ----------------------------------------------------------------- Revoke Role
5604:
5605: sub revokerole {
1.357 www 5606: my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21 www 5607: my $now=time;
1.357 www 5608: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21 www 5609: }
5610:
5611: # ---------------------------------------------------------- Revoke Custom Role
5612:
5613: sub revokecustomrole {
1.357 www 5614: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21 www 5615: my $now=time;
1.357 www 5616: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
5617: $deleteflag);
1.17 www 5618: }
5619:
1.533 banghart 5620: # ------------------------------------------------------------ Disk usage
1.535 albertel 5621: sub diskusage {
1.533 banghart 5622: my ($udom,$uname,$directoryRoot)=@_;
5623: $directoryRoot =~ s/\/$//;
1.535 albertel 5624: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514 albertel 5625: return $listing;
1.512 banghart 5626: }
5627:
1.566 banghart 5628: sub is_locked {
5629: my ($file_name, $domain, $user) = @_;
5630: my @check;
5631: my $is_locked;
5632: push @check, $file_name;
1.613 albertel 5633: my %locked = &get('file_permissions',\@check,
1.620 albertel 5634: $env{'user.domain'},$env{'user.name'});
1.615 albertel 5635: my ($tmp)=keys(%locked);
5636: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 5637:
1.566 banghart 5638: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 5639: $is_locked = 'false';
5640: foreach my $entry (@{$locked{$file_name}}) {
5641: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 5642: $is_locked = 'true';
5643: last;
1.745 raeburn 5644: }
5645: }
1.566 banghart 5646: } else {
5647: $is_locked = 'false';
5648: }
5649: }
5650:
1.759 albertel 5651: sub declutter_portfile {
5652: my ($file) = @_;
1.833 albertel 5653: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 5654: return $file;
5655: }
5656:
1.559 banghart 5657: # ------------------------------------------------------------- Mark as Read Only
5658:
5659: sub mark_as_readonly {
5660: my ($domain,$user,$files,$what) = @_;
1.613 albertel 5661: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5662: my ($tmp)=keys(%current_permissions);
5663: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 5664: foreach my $file (@{$files}) {
1.759 albertel 5665: $file = &declutter_portfile($file);
1.561 banghart 5666: push(@{$current_permissions{$file}},$what);
1.559 banghart 5667: }
1.613 albertel 5668: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 5669: return;
5670: }
5671:
1.572 banghart 5672: # ------------------------------------------------------------Save Selected Files
5673:
5674: sub save_selected_files {
5675: my ($user, $path, @files) = @_;
5676: my $filename = $user."savedfiles";
1.573 banghart 5677: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 5678: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 5679: foreach my $file (@files) {
1.620 albertel 5680: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 5681: }
5682: foreach my $file (@other_files) {
1.574 banghart 5683: print (OUT $file."\n");
1.572 banghart 5684: }
1.574 banghart 5685: close (OUT);
1.572 banghart 5686: return 'ok';
5687: }
5688:
1.574 banghart 5689: sub clear_selected_files {
5690: my ($user) = @_;
5691: my $filename = $user."savedfiles";
5692: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5693: print (OUT undef);
5694: close (OUT);
5695: return ("ok");
5696: }
5697:
1.572 banghart 5698: sub files_in_path {
5699: my ($user, $path) = @_;
5700: my $filename = $user."savedfiles";
5701: my %return_files;
1.574 banghart 5702: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 5703: while (my $line_in = <IN>) {
1.574 banghart 5704: chomp ($line_in);
5705: my @paths_and_file = split (m!/!, $line_in);
5706: my $file_part = pop (@paths_and_file);
5707: my $path_part = join ('/', @paths_and_file);
1.573 banghart 5708: $path_part.='/';
5709: my $path_and_file = $path_part.$file_part;
5710: if ($path_part eq $path) {
5711: $return_files{$file_part}= 'selected';
5712: }
5713: }
1.574 banghart 5714: close (IN);
5715: return (\%return_files);
1.572 banghart 5716: }
5717:
5718: # called in portfolio select mode, to show files selected NOT in current directory
5719: sub files_not_in_path {
5720: my ($user, $path) = @_;
5721: my $filename = $user."savedfiles";
5722: my @return_files;
5723: my $path_part;
1.800 albertel 5724: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5725: while (my $line = <IN>) {
1.572 banghart 5726: #ok, I know it's clunky, but I want it to work
1.800 albertel 5727: my @paths_and_file = split(m|/|, $line);
5728: my $file_part = pop(@paths_and_file);
5729: chomp($file_part);
5730: my $path_part = join('/', @paths_and_file);
1.572 banghart 5731: $path_part .= '/';
5732: my $path_and_file = $path_part.$file_part;
5733: if ($path_part ne $path) {
1.800 albertel 5734: push(@return_files, ($path_and_file));
1.572 banghart 5735: }
5736: }
1.800 albertel 5737: close(OUT);
1.574 banghart 5738: return (@return_files);
1.572 banghart 5739: }
5740:
1.745 raeburn 5741: #----------------------------------------------Get portfolio file permissions
1.629 banghart 5742:
1.745 raeburn 5743: sub get_portfile_permissions {
5744: my ($domain,$user) = @_;
1.613 albertel 5745: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5746: my ($tmp)=keys(%current_permissions);
5747: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 5748: return \%current_permissions;
5749: }
5750:
5751: #---------------------------------------------Get portfolio file access controls
5752:
1.749 raeburn 5753: sub get_access_controls {
1.745 raeburn 5754: my ($current_permissions,$group,$file) = @_;
1.769 albertel 5755: my %access;
5756: my $real_file = $file;
5757: $file =~ s/\.meta$//;
1.745 raeburn 5758: if (defined($file)) {
1.749 raeburn 5759: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
5760: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 5761: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 5762: }
5763: }
1.745 raeburn 5764: } else {
1.749 raeburn 5765: foreach my $key (keys(%{$current_permissions})) {
5766: if ($key =~ /\0accesscontrol$/) {
5767: if (defined($group)) {
5768: if ($key !~ m-^\Q$group\E/-) {
5769: next;
5770: }
5771: }
5772: my ($fullpath) = split(/\0/,$key);
5773: if (ref($$current_permissions{$key}) eq 'HASH') {
5774: foreach my $control (keys(%{$$current_permissions{$key}})) {
5775: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
5776: }
5777: }
5778: }
5779: }
5780: }
5781: return %access;
5782: }
5783:
5784: sub modify_access_controls {
5785: my ($file_name,$changes,$domain,$user)=@_;
5786: my ($outcome,$deloutcome);
5787: my %store_permissions;
5788: my %new_values;
5789: my %new_control;
5790: my %translation;
5791: my @deletions = ();
5792: my $now = time;
5793: if (exists($$changes{'activate'})) {
5794: if (ref($$changes{'activate'}) eq 'HASH') {
5795: my @newitems = sort(keys(%{$$changes{'activate'}}));
5796: my $numnew = scalar(@newitems);
5797: for (my $i=0; $i<$numnew; $i++) {
5798: my $newkey = $newitems[$i];
5799: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 5800: if ($newkey =~ /^\d+:/) {
5801: $newkey =~ s/^(\d+)/$newid/;
5802: $translation{$1} = $newid;
5803: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
5804: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
5805: $translation{$1} = $newid;
5806: }
1.749 raeburn 5807: $new_values{$file_name."\0".$newkey} =
5808: $$changes{'activate'}{$newitems[$i]};
5809: $new_control{$newkey} = $now;
5810: }
5811: }
5812: }
5813: my %todelete;
5814: my %changed_items;
5815: foreach my $action ('delete','update') {
5816: if (exists($$changes{$action})) {
5817: if (ref($$changes{$action}) eq 'HASH') {
5818: foreach my $key (keys(%{$$changes{$action}})) {
5819: my ($itemnum) = ($key =~ /^([^:]+):/);
5820: if ($action eq 'delete') {
5821: $todelete{$itemnum} = 1;
5822: } else {
5823: $changed_items{$itemnum} = $key;
5824: }
5825: }
1.745 raeburn 5826: }
5827: }
1.749 raeburn 5828: }
5829: # get lock on access controls for file.
5830: my $lockhash = {
5831: $file_name."\0".'locked_access_records' => $env{'user.name'}.
5832: ':'.$env{'user.domain'},
5833: };
5834: my $tries = 0;
5835: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5836:
5837: while (($gotlock ne 'ok') && $tries <3) {
5838: $tries ++;
5839: sleep 1;
5840: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5841: }
5842: if ($gotlock eq 'ok') {
5843: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
5844: my ($tmp)=keys(%curr_permissions);
5845: if ($tmp=~/^error:/) { undef(%curr_permissions); }
5846: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
5847: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
5848: if (ref($curr_controls) eq 'HASH') {
5849: foreach my $control_item (keys(%{$curr_controls})) {
5850: my ($itemnum) = ($control_item =~ /^([^:]+):/);
5851: if (defined($todelete{$itemnum})) {
5852: push(@deletions,$file_name."\0".$control_item);
5853: } else {
5854: if (defined($changed_items{$itemnum})) {
5855: $new_control{$changed_items{$itemnum}} = $now;
5856: push(@deletions,$file_name."\0".$control_item);
5857: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
5858: } else {
5859: $new_control{$control_item} = $$curr_controls{$control_item};
5860: }
5861: }
1.745 raeburn 5862: }
5863: }
5864: }
1.749 raeburn 5865: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
5866: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
5867: $outcome = &put('file_permissions',\%new_values,$domain,$user);
5868: # remove lock
5869: my @del_lock = ($file_name."\0".'locked_access_records');
5870: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 5871: my ($file,$group);
5872: if (&is_course($domain,$user)) {
5873: ($group,$file) = split(/\//,$file_name,2);
5874: } else {
5875: $file = $file_name;
5876: }
5877: my $sqlresult =
5878: &update_portfolio_table($user,$domain,$file,'portfolio_access',
5879: $group);
1.749 raeburn 5880: } else {
5881: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 5882: }
1.749 raeburn 5883: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 5884: }
5885:
1.827 raeburn 5886: sub make_public_indefinitely {
5887: my ($requrl) = @_;
5888: my $now = time;
5889: my $action = 'activate';
5890: my $aclnum = 0;
5891: if (&is_portfolio_url($requrl)) {
5892: my (undef,$udom,$unum,$file_name,$group) =
5893: &parse_portfolio_url($requrl);
5894: my $current_perms = &get_portfile_permissions($udom,$unum);
5895: my %access_controls = &get_access_controls($current_perms,
5896: $group,$file_name);
5897: foreach my $key (keys(%{$access_controls{$file_name}})) {
5898: my ($num,$scope,$end,$start) =
5899: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5900: if ($scope eq 'public') {
5901: if ($start <= $now && $end == 0) {
5902: $action = 'none';
5903: } else {
5904: $action = 'update';
5905: $aclnum = $num;
5906: }
5907: last;
5908: }
5909: }
5910: if ($action eq 'none') {
5911: return 'ok';
5912: } else {
5913: my %changes;
5914: my $newend = 0;
5915: my $newstart = $now;
5916: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
5917: $changes{$action}{$newkey} = {
5918: type => 'public',
5919: time => {
5920: start => $newstart,
5921: end => $newend,
5922: },
5923: };
5924: my ($outcome,$deloutcome,$new_values,$translation) =
5925: &modify_access_controls($file_name,\%changes,$udom,$unum);
5926: return $outcome;
5927: }
5928: } else {
5929: return 'invalid';
5930: }
5931: }
5932:
1.745 raeburn 5933: #------------------------------------------------------Get Marked as Read Only
5934:
5935: sub get_marked_as_readonly {
5936: my ($domain,$user,$what,$group) = @_;
5937: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 5938: my @readonly_files;
1.629 banghart 5939: my $cmp1=$what;
5940: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 5941: while (my ($file_name,$value) = each(%{$current_permissions})) {
5942: if (defined($group)) {
5943: if ($file_name !~ m-^\Q$group\E/-) {
5944: next;
5945: }
5946: }
1.561 banghart 5947: if (ref($value) eq "ARRAY"){
5948: foreach my $stored_what (@{$value}) {
1.629 banghart 5949: my $cmp2=$stored_what;
1.759 albertel 5950: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 5951: $cmp2=join('',@{$stored_what});
1.745 raeburn 5952: }
1.629 banghart 5953: if ($cmp1 eq $cmp2) {
1.561 banghart 5954: push(@readonly_files, $file_name);
1.745 raeburn 5955: last;
1.563 banghart 5956: } elsif (!defined($what)) {
5957: push(@readonly_files, $file_name);
1.745 raeburn 5958: last;
1.561 banghart 5959: }
5960: }
1.745 raeburn 5961: }
1.561 banghart 5962: }
5963: return @readonly_files;
5964: }
1.577 banghart 5965: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 5966:
1.577 banghart 5967: sub get_marked_as_readonly_hash {
1.745 raeburn 5968: my ($current_permissions,$group,$what) = @_;
1.577 banghart 5969: my %readonly_files;
1.745 raeburn 5970: while (my ($file_name,$value) = each(%{$current_permissions})) {
5971: if (defined($group)) {
5972: if ($file_name !~ m-^\Q$group\E/-) {
5973: next;
5974: }
5975: }
1.577 banghart 5976: if (ref($value) eq "ARRAY"){
5977: foreach my $stored_what (@{$value}) {
1.745 raeburn 5978: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 5979: foreach my $lock_descriptor(@{$stored_what}) {
5980: if ($lock_descriptor eq 'graded') {
5981: $readonly_files{$file_name} = 'graded';
5982: } elsif ($lock_descriptor eq 'handback') {
5983: $readonly_files{$file_name} = 'handback';
5984: } else {
5985: if (!exists($readonly_files{$file_name})) {
5986: $readonly_files{$file_name} = 'locked';
5987: }
5988: }
1.745 raeburn 5989: }
1.750 banghart 5990: }
1.577 banghart 5991: }
5992: }
5993: }
5994: return %readonly_files;
5995: }
1.559 banghart 5996: # ------------------------------------------------------------ Unmark as Read Only
5997:
5998: sub unmark_as_readonly {
1.629 banghart 5999: # unmarks $file_name (if $file_name is defined), or all files locked by $what
6000: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 6001: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 6002: $file_name = &declutter_portfile($file_name);
1.634 albertel 6003: my $symb_crs = $what;
6004: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 6005: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 6006: my ($tmp)=keys(%current_permissions);
6007: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6008: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 6009: foreach my $file (@readonly_files) {
1.759 albertel 6010: my $clean_file = &declutter_portfile($file);
6011: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 6012: my $current_locks = $current_permissions{$file};
1.563 banghart 6013: my @new_locks;
6014: my @del_keys;
6015: if (ref($current_locks) eq "ARRAY"){
6016: foreach my $locker (@{$current_locks}) {
1.632 albertel 6017: my $compare=$locker;
1.749 raeburn 6018: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 6019: $compare=join('',@{$locker});
1.746 raeburn 6020: if ($compare ne $symb_crs) {
6021: push(@new_locks, $locker);
6022: }
1.563 banghart 6023: }
6024: }
1.650 albertel 6025: if (scalar(@new_locks) > 0) {
1.563 banghart 6026: $current_permissions{$file} = \@new_locks;
6027: } else {
6028: push(@del_keys, $file);
1.613 albertel 6029: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 6030: delete($current_permissions{$file});
1.563 banghart 6031: }
6032: }
1.561 banghart 6033: }
1.613 albertel 6034: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6035: return;
6036: }
1.512 banghart 6037:
1.17 www 6038: # ------------------------------------------------------------ Directory lister
6039:
6040: sub dirlist {
1.253 stredwic 6041: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
6042:
1.18 www 6043: $uri=~s/^\///;
6044: $uri=~s/\/$//;
1.253 stredwic 6045: my ($udom, $uname);
6046: (undef,$udom,$uname)=split(/\//,$uri);
6047: if(defined($userdomain)) {
6048: $udom = $userdomain;
6049: }
6050: if(defined($username)) {
6051: $uname = $username;
6052: }
6053:
6054: my $dirRoot = $perlvar{'lonDocRoot'};
6055: if(defined($alternateDirectoryRoot)) {
6056: $dirRoot = $alternateDirectoryRoot;
6057: $dirRoot =~ s/\/$//;
1.751 banghart 6058: }
1.253 stredwic 6059:
6060: if($udom) {
6061: if($uname) {
1.800 albertel 6062: my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
6063: &homeserver($uname,$udom));
1.605 matthew 6064: my @listing_results;
6065: if ($listing eq 'unknown_cmd') {
1.800 albertel 6066: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
6067: &homeserver($uname,$udom));
1.605 matthew 6068: @listing_results = split(/:/,$listing);
6069: } else {
6070: @listing_results = map { &unescape($_); } split(/:/,$listing);
6071: }
6072: return @listing_results;
1.253 stredwic 6073: } elsif(!defined($alternateDirectoryRoot)) {
1.800 albertel 6074: my %allusers;
1.841 albertel 6075: my %servers = &get_servers($udom,'library');
6076: foreach my $tryserver (keys(%servers)) {
6077: my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
6078: $udom, $tryserver);
6079: my @listing_results;
6080: if ($listing eq 'unknown_cmd') {
6081: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
6082: $udom, $tryserver);
6083: @listing_results = split(/:/,$listing);
6084: } else {
6085: @listing_results =
6086: map { &unescape($_); } split(/:/,$listing);
6087: }
6088: if ($listing_results[0] ne 'no_such_dir' &&
6089: $listing_results[0] ne 'empty' &&
6090: $listing_results[0] ne 'con_lost') {
6091: foreach my $line (@listing_results) {
6092: my ($entry) = split(/&/,$line,2);
6093: $allusers{$entry} = 1;
6094: }
6095: }
1.253 stredwic 6096: }
6097: my $alluserstr='';
1.800 albertel 6098: foreach my $user (sort(keys(%allusers))) {
6099: $alluserstr.=$user.'&user:';
1.253 stredwic 6100: }
6101: $alluserstr=~s/:$//;
6102: return split(/:/,$alluserstr);
6103: } else {
1.800 albertel 6104: return ('missing user name');
1.253 stredwic 6105: }
6106: } elsif(!defined($alternateDirectoryRoot)) {
1.841 albertel 6107: my @all_domains = sort(&all_domains());
6108: foreach my $domain (@all_domains) {
6109: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
6110: }
6111: return @all_domains;
6112: } else {
1.800 albertel 6113: return ('missing domain');
1.275 stredwic 6114: }
6115: }
6116:
6117: # --------------------------------------------- GetFileTimestamp
6118: # This function utilizes dirlist and returns the date stamp for
6119: # when it was last modified. It will also return an error of -1
6120: # if an error occurs
6121:
1.410 matthew 6122: ##
6123: ## FIXME: This subroutine assumes its caller knows something about the
6124: ## directory structure of the home server for the student ($root).
6125: ## Not a good assumption to make. Since this is for looking up files
6126: ## in user directories, the full path should be constructed by lond, not
6127: ## whatever machine we request data from.
6128: ##
1.275 stredwic 6129: sub GetFileTimestamp {
6130: my ($studentDomain,$studentName,$filename,$root)=@_;
1.807 albertel 6131: $studentDomain = &LONCAPA::clean_domain($studentDomain);
6132: $studentName = &LONCAPA::clean_username($studentName);
1.275 stredwic 6133: my $subdir=$studentName.'__';
6134: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
6135: my $proname="$studentDomain/$subdir/$studentName";
6136: $proname .= '/'.$filename;
1.375 matthew 6137: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
6138: $studentName, $root);
1.275 stredwic 6139: my @stats = split('&', $fileStat);
6140: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 6141: # @stats contains first the filename, then the stat output
6142: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 6143: } else {
6144: return -1;
1.253 stredwic 6145: }
1.26 www 6146: }
6147:
1.712 albertel 6148: sub stat_file {
6149: my ($uri) = @_;
1.787 albertel 6150: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 6151:
1.712 albertel 6152: my ($udom,$uname,$file,$dir);
6153: if ($uri =~ m-^/(uploaded|editupload)/-) {
6154: ($udom,$uname,$file) =
1.811 albertel 6155: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 6156: $file = 'userfiles/'.$file;
1.740 www 6157: $dir = &propath($udom,$uname);
1.712 albertel 6158: }
6159: if ($uri =~ m-^/res/-) {
6160: ($udom,$uname) =
1.807 albertel 6161: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 6162: $file = $uri;
6163: }
6164:
6165: if (!$udom || !$uname || !$file) {
6166: # unable to handle the uri
6167: return ();
6168: }
6169:
6170: my ($result) = &dirlist($file,$udom,$uname,$dir);
6171: my @stats = split('&', $result);
1.721 banghart 6172:
1.712 albertel 6173: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
6174: shift(@stats); #filename is first
6175: return @stats;
6176: }
6177: return ();
6178: }
6179:
1.26 www 6180: # -------------------------------------------------------- Value of a Condition
6181:
1.713 albertel 6182: # gets the value of a specific preevaluated condition
6183: # stored in the string $env{user.state.<cid>}
6184: # or looks up a condition reference in the bighash and if if hasn't
6185: # already been evaluated recurses into docondval to get the value of
6186: # the condition, then memoizing it to
6187: # $env{user.state.<cid>.<condition>}
1.40 www 6188: sub directcondval {
6189: my $number=shift;
1.620 albertel 6190: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 6191: &Apache::lonuserstate::evalstate();
6192: }
1.713 albertel 6193: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
6194: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
6195: } elsif ($number =~ /^_/) {
6196: my $sub_condition;
6197: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6198: &GDBM_READER(),0640)) {
6199: $sub_condition=$bighash{'conditions'.$number};
6200: untie(%bighash);
6201: }
6202: my $value = &docondval($sub_condition);
6203: &appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
6204: return $value;
6205: }
1.620 albertel 6206: if ($env{'user.state.'.$env{'request.course.id'}}) {
6207: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 6208: } else {
6209: return 2;
6210: }
6211: }
6212:
1.713 albertel 6213: # get the collection of conditions for this resource
1.26 www 6214: sub condval {
6215: my $condidx=shift;
1.54 www 6216: my $allpathcond='';
1.713 albertel 6217: foreach my $cond (split(/\|/,$condidx)) {
6218: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
6219: $allpathcond.=
6220: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
6221: }
1.191 harris41 6222: }
1.54 www 6223: $allpathcond=~s/\|$//;
1.713 albertel 6224: return &docondval($allpathcond);
6225: }
6226:
6227: #evaluates an expression of conditions
6228: sub docondval {
6229: my ($allpathcond) = @_;
6230: my $result=0;
6231: if ($env{'request.course.id'}
6232: && defined($allpathcond)) {
6233: my $operand='|';
6234: my @stack;
6235: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
6236: if ($chunk eq '(') {
6237: push @stack,($operand,$result);
6238: } elsif ($chunk eq ')') {
6239: my $before=pop @stack;
6240: if (pop @stack eq '&') {
6241: $result=$result>$before?$before:$result;
6242: } else {
6243: $result=$result>$before?$result:$before;
6244: }
6245: } elsif (($chunk eq '&') || ($chunk eq '|')) {
6246: $operand=$chunk;
6247: } else {
6248: my $new=directcondval($chunk);
6249: if ($operand eq '&') {
6250: $result=$result>$new?$new:$result;
6251: } else {
6252: $result=$result>$new?$result:$new;
6253: }
6254: }
6255: }
1.26 www 6256: }
6257: return $result;
1.421 albertel 6258: }
6259:
6260: # ---------------------------------------------------- Devalidate courseresdata
6261:
6262: sub devalidatecourseresdata {
6263: my ($coursenum,$coursedomain)=@_;
6264: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6265: &devalidate_cache_new('courseres',$hashid);
1.28 www 6266: }
6267:
1.763 www 6268:
1.200 www 6269: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 6270: #
6271: # Parameters:
6272: # $coursenum - Number of the course.
6273: # $coursedomain - Domain at which the course was created.
6274: # Returns:
6275: # A hash of the course parameters along (I think) with timestamps
6276: # and version info.
1.877 foxr 6277:
1.624 albertel 6278: sub get_courseresdata {
6279: my ($coursenum,$coursedomain)=@_;
1.200 www 6280: my $coursehom=&homeserver($coursenum,$coursedomain);
6281: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6282: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 6283: my %dumpreply;
1.417 albertel 6284: unless (defined($cached)) {
1.624 albertel 6285: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 6286: $result=\%dumpreply;
1.251 albertel 6287: my ($tmp) = keys(%dumpreply);
6288: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 6289: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 6290: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
6291: return $tmp;
1.416 albertel 6292: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 6293: $result=undef;
1.599 albertel 6294: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 6295: }
6296: }
1.624 albertel 6297: return $result;
6298: }
6299:
1.633 albertel 6300: sub devalidateuserresdata {
6301: my ($uname,$udom)=@_;
6302: my $hashid="$udom:$uname";
6303: &devalidate_cache_new('userres',$hashid);
6304: }
6305:
1.624 albertel 6306: sub get_userresdata {
6307: my ($uname,$udom)=@_;
6308: #most student don\'t have any data set, check if there is some data
6309: if (&EXT_cache_status($udom,$uname)) { return undef; }
6310:
6311: my $hashid="$udom:$uname";
6312: my ($result,$cached)=&is_cached_new('userres',$hashid);
6313: if (!defined($cached)) {
6314: my %resourcedata=&dump('resourcedata',$udom,$uname);
6315: $result=\%resourcedata;
6316: &do_cache_new('userres',$hashid,$result,600);
6317: }
6318: my ($tmp)=keys(%$result);
6319: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
6320: return $result;
6321: }
6322: #error 2 occurs when the .db doesn't exist
6323: if ($tmp!~/error: 2 /) {
1.672 albertel 6324: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 6325: " Trying to get resource data for ".
6326: $uname." at ".$udom.": ".
6327: $tmp."</font>");
6328: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 6329: #&EXT_cache_set($udom,$uname);
6330: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 6331: undef($tmp); # not really an error so don't send it back
1.624 albertel 6332: }
6333: return $tmp;
6334: }
1.879 foxr 6335: #----------------------------------------------- resdata - return resource data
6336: # Purpose:
6337: # Return resource data for either users or for a course.
6338: # Parameters:
6339: # $name - Course/user name.
6340: # $domain - Name of the domain the user/course is registered on.
6341: # $type - Type of thing $name is (must be 'course' or 'user'
6342: # @which - Array of names of resources desired.
6343: # Returns:
6344: # The value of the first reasource in @which that is found in the
6345: # resource hash.
6346: # Exceptional Conditions:
6347: # If the $type passed in is not valid (not the string 'course' or
6348: # 'user', an undefined reference is returned.
6349: # If none of the resources are found, an undef is returned
1.624 albertel 6350: sub resdata {
6351: my ($name,$domain,$type,@which)=@_;
6352: my $result;
6353: if ($type eq 'course') {
6354: $result=&get_courseresdata($name,$domain);
6355: } elsif ($type eq 'user') {
6356: $result=&get_userresdata($name,$domain);
6357: }
6358: if (!ref($result)) { return $result; }
1.251 albertel 6359: foreach my $item (@which) {
1.417 albertel 6360: if (defined($result->{$item})) {
6361: return $result->{$item};
1.251 albertel 6362: }
1.250 albertel 6363: }
1.291 albertel 6364: return undef;
1.200 www 6365: }
6366:
1.379 matthew 6367: #
6368: # EXT resource caching routines
6369: #
6370:
6371: sub clear_EXT_cache_status {
1.383 albertel 6372: &delenv('cache.EXT.');
1.379 matthew 6373: }
6374:
6375: sub EXT_cache_status {
6376: my ($target_domain,$target_user) = @_;
1.383 albertel 6377: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 6378: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 6379: # We know already the user has no data
6380: return 1;
6381: } else {
6382: return 0;
6383: }
6384: }
6385:
6386: sub EXT_cache_set {
6387: my ($target_domain,$target_user) = @_;
1.383 albertel 6388: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633 albertel 6389: #&appenv($cachename => time);
1.379 matthew 6390: }
6391:
1.28 www 6392: # --------------------------------------------------------- Value of a Variable
1.58 www 6393: sub EXT {
1.715 albertel 6394:
1.395 albertel 6395: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 6396: unless ($varname) { return ''; }
1.218 albertel 6397: #get real user name/domain, courseid and symb
6398: my $courseid;
1.359 albertel 6399: my $publicuser;
1.427 www 6400: if ($symbparm) {
6401: $symbparm=&get_symb_from_alias($symbparm);
6402: }
1.218 albertel 6403: if (!($uname && $udom)) {
1.790 albertel 6404: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 6405: if (!$symbparm) { $symbparm=$cursymb; }
6406: } else {
1.620 albertel 6407: $courseid=$env{'request.course.id'};
1.218 albertel 6408: }
1.48 www 6409: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
6410: my $rest;
1.320 albertel 6411: if (defined($therest[0])) {
1.48 www 6412: $rest=join('.',@therest);
6413: } else {
6414: $rest='';
6415: }
1.320 albertel 6416:
1.57 www 6417: my $qualifierrest=$qualifier;
6418: if ($rest) { $qualifierrest.='.'.$rest; }
6419: my $spacequalifierrest=$space;
6420: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 6421: if ($realm eq 'user') {
1.48 www 6422: # --------------------------------------------------------------- user.resource
6423: if ($space eq 'resource') {
1.651 albertel 6424: if ( (defined($Apache::lonhomework::parsing_a_problem)
6425: || defined($Apache::lonhomework::parsing_a_task))
6426: &&
1.744 albertel 6427: ($symbparm eq &symbread()) ) {
6428: # if we are in the middle of processing the resource the
6429: # get the value we are planning on committing
6430: if (defined($Apache::lonhomework::results{$qualifierrest})) {
6431: return $Apache::lonhomework::results{$qualifierrest};
6432: } else {
6433: return $Apache::lonhomework::history{$qualifierrest};
6434: }
1.335 albertel 6435: } else {
1.359 albertel 6436: my %restored;
1.620 albertel 6437: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 6438: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
6439: } else {
6440: %restored=&restore($symbparm,$courseid,$udom,$uname);
6441: }
1.335 albertel 6442: return $restored{$qualifierrest};
6443: }
1.48 www 6444: # ----------------------------------------------------------------- user.access
6445: } elsif ($space eq 'access') {
1.218 albertel 6446: # FIXME - not supporting calls for a specific user
1.48 www 6447: return &allowed($qualifier,$rest);
6448: # ------------------------------------------ user.preferences, user.environment
6449: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 6450: if (($uname eq $env{'user.name'}) &&
6451: ($udom eq $env{'user.domain'})) {
6452: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 6453: } else {
1.359 albertel 6454: my %returnhash;
6455: if (!$publicuser) {
6456: %returnhash=&userenvironment($udom,$uname,
6457: $qualifierrest);
6458: }
1.218 albertel 6459: return $returnhash{$qualifierrest};
6460: }
1.48 www 6461: # ----------------------------------------------------------------- user.course
6462: } elsif ($space eq 'course') {
1.218 albertel 6463: # FIXME - not supporting calls for a specific user
1.620 albertel 6464: return $env{join('.',('request.course',$qualifier))};
1.48 www 6465: # ------------------------------------------------------------------- user.role
6466: } elsif ($space eq 'role') {
1.218 albertel 6467: # FIXME - not supporting calls for a specific user
1.620 albertel 6468: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 6469: if ($qualifier eq 'value') {
6470: return $role;
6471: } elsif ($qualifier eq 'extent') {
6472: return $where;
6473: }
6474: # ----------------------------------------------------------------- user.domain
6475: } elsif ($space eq 'domain') {
1.218 albertel 6476: return $udom;
1.48 www 6477: # ------------------------------------------------------------------- user.name
6478: } elsif ($space eq 'name') {
1.218 albertel 6479: return $uname;
1.48 www 6480: # ---------------------------------------------------- Any other user namespace
1.29 www 6481: } else {
1.359 albertel 6482: my %reply;
6483: if (!$publicuser) {
6484: %reply=&get($space,[$qualifierrest],$udom,$uname);
6485: }
6486: return $reply{$qualifierrest};
1.48 www 6487: }
1.236 www 6488: } elsif ($realm eq 'query') {
6489: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 6490: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
6491: [$spacequalifierrest]);
1.620 albertel 6492: return $env{'form.'.$spacequalifierrest};
1.236 www 6493: } elsif ($realm eq 'request') {
1.48 www 6494: # ------------------------------------------------------------- request.browser
6495: if ($space eq 'browser') {
1.430 www 6496: if ($qualifier eq 'textremote') {
1.676 albertel 6497: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 6498: return 1;
6499: } else {
6500: return 0;
6501: }
6502: } else {
1.620 albertel 6503: return $env{'browser.'.$qualifier};
1.430 www 6504: }
1.57 www 6505: # ------------------------------------------------------------ request.filename
6506: } else {
1.620 albertel 6507: return $env{'request.'.$spacequalifierrest};
1.29 www 6508: }
1.28 www 6509: } elsif ($realm eq 'course') {
1.48 www 6510: # ---------------------------------------------------------- course.description
1.620 albertel 6511: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 6512: } elsif ($realm eq 'resource') {
1.165 www 6513:
1.620 albertel 6514: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 6515: if (!$symbparm) { $symbparm=&symbread(); }
6516: }
1.693 albertel 6517:
6518: if ($space eq 'title') {
6519: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
6520: return &gettitle($symbparm);
6521: }
6522:
6523: if ($space eq 'map') {
6524: my ($map) = &decode_symb($symbparm);
6525: return &symbread($map);
6526: }
1.905 albertel 6527: if ($space eq 'filename') {
6528: if ($symbparm) {
6529: return &clutter((&decode_symb($symbparm))[2]);
6530: }
6531: return &hreflocation('',$env{'request.filename'});
6532: }
1.693 albertel 6533:
6534: my ($section, $group, @groups);
1.593 albertel 6535: my ($courselevelm,$courselevel);
1.539 albertel 6536: if ($symbparm && defined($courseid) &&
1.620 albertel 6537: $courseid eq $env{'request.course.id'}) {
1.165 www 6538:
1.218 albertel 6539: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 6540:
1.60 www 6541: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 6542: my $symbp=$symbparm;
1.735 albertel 6543: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 6544:
6545: my $symbparm=$symbp.'.'.$spacequalifierrest;
6546: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
6547:
1.620 albertel 6548: if (($env{'user.name'} eq $uname) &&
6549: ($env{'user.domain'} eq $udom)) {
6550: $section=$env{'request.course.sec'};
1.733 raeburn 6551: @groups = split(/:/,$env{'request.course.groups'});
6552: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 6553: } else {
1.539 albertel 6554: if (! defined($usection)) {
1.551 albertel 6555: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 6556: } else {
6557: $section = $usection;
6558: }
1.733 raeburn 6559: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 6560: }
6561:
6562: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
6563: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
6564: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
6565:
1.593 albertel 6566: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 6567: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 6568: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 6569:
1.60 www 6570: # ----------------------------------------------------------- first, check user
1.624 albertel 6571:
6572: my $userreply=&resdata($uname,$udom,'user',
6573: ($courselevelr,$courselevelm,
6574: $courselevel));
6575: if (defined($userreply)) { return $userreply; }
1.95 www 6576:
1.594 albertel 6577: # ------------------------------------------------ second, check some of course
1.684 raeburn 6578: my $coursereply;
1.691 raeburn 6579: if (@groups > 0) {
6580: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
6581: $mapparm,$spacequalifierrest);
1.684 raeburn 6582: if (defined($coursereply)) { return $coursereply; }
6583: }
1.96 www 6584:
1.684 raeburn 6585: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624 albertel 6586: $env{'course.'.$courseid.'.domain'},
6587: 'course',
6588: ($seclevelr,$seclevelm,$seclevel,
6589: $courselevelr));
1.287 albertel 6590: if (defined($coursereply)) { return $coursereply; }
1.200 www 6591:
1.60 www 6592: # ------------------------------------------------------ third, check map parms
1.218 albertel 6593: my %parmhash=();
6594: my $thisparm='';
6595: if (tie(%parmhash,'GDBM_File',
1.620 albertel 6596: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 6597: &GDBM_READER(),0640)) {
1.218 albertel 6598: $thisparm=$parmhash{$symbparm};
6599: untie(%parmhash);
6600: }
6601: if ($thisparm) { return $thisparm; }
6602: }
1.594 albertel 6603: # ------------------------------------------ fourth, look in resource metadata
1.71 www 6604:
1.218 albertel 6605: $spacequalifierrest=~s/\./\_/;
1.282 albertel 6606: my $filename;
6607: if (!$symbparm) { $symbparm=&symbread(); }
6608: if ($symbparm) {
1.409 www 6609: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 6610: } else {
1.620 albertel 6611: $filename=$env{'request.filename'};
1.282 albertel 6612: }
6613: my $metadata=&metadata($filename,$spacequalifierrest);
1.288 albertel 6614: if (defined($metadata)) { return $metadata; }
1.282 albertel 6615: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288 albertel 6616: if (defined($metadata)) { return $metadata; }
1.142 www 6617:
1.594 albertel 6618: # ---------------------------------------------- fourth, look in rest pf course
1.593 albertel 6619: if ($symbparm && defined($courseid) &&
1.620 albertel 6620: $courseid eq $env{'request.course.id'}) {
1.624 albertel 6621: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
6622: $env{'course.'.$courseid.'.domain'},
6623: 'course',
6624: ($courselevelm,$courselevel));
1.593 albertel 6625: if (defined($coursereply)) { return $coursereply; }
6626: }
1.145 www 6627: # ------------------------------------------------------------------ Cascade up
1.218 albertel 6628: unless ($space eq '0') {
1.336 albertel 6629: my @parts=split(/_/,$space);
6630: my $id=pop(@parts);
6631: my $part=join('_',@parts);
6632: if ($part eq '') { $part='0'; }
6633: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 6634: $symbparm,$udom,$uname,$section,1);
1.337 albertel 6635: if (defined($partgeneral)) { return $partgeneral; }
1.218 albertel 6636: }
1.395 albertel 6637: if ($recurse) { return undef; }
6638: my $pack_def=&packages_tab_default($filename,$varname);
6639: if (defined($pack_def)) { return $pack_def; }
1.71 www 6640:
1.48 www 6641: # ---------------------------------------------------- Any other user namespace
6642: } elsif ($realm eq 'environment') {
6643: # ----------------------------------------------------------------- environment
1.620 albertel 6644: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
6645: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 6646: } else {
1.770 albertel 6647: if ($uname eq 'anonymous' && $udom eq '') {
6648: return '';
6649: }
1.219 albertel 6650: my %returnhash=&userenvironment($udom,$uname,
6651: $spacequalifierrest);
6652: return $returnhash{$spacequalifierrest};
6653: }
1.28 www 6654: } elsif ($realm eq 'system') {
1.48 www 6655: # ----------------------------------------------------------------- system.time
6656: if ($space eq 'time') {
6657: return time;
6658: }
1.696 albertel 6659: } elsif ($realm eq 'server') {
6660: # ----------------------------------------------------------------- system.time
6661: if ($space eq 'name') {
6662: return $ENV{'SERVER_NAME'};
6663: }
1.28 www 6664: }
1.48 www 6665: return '';
1.61 www 6666: }
6667:
1.691 raeburn 6668: sub check_group_parms {
6669: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
6670: my @groupitems = ();
6671: my $resultitem;
6672: my @levels = ($symbparm,$mapparm,$what);
6673: foreach my $group (@{$groups}) {
6674: foreach my $level (@levels) {
6675: my $item = $courseid.'.['.$group.'].'.$level;
6676: push(@groupitems,$item);
6677: }
6678: }
6679: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
6680: $env{'course.'.$courseid.'.domain'},
6681: 'course',@groupitems);
6682: return $coursereply;
6683: }
6684:
6685: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 6686: my ($courseid,@groups) = @_;
6687: @groups = sort(@groups);
1.691 raeburn 6688: return @groups;
6689: }
6690:
1.395 albertel 6691: sub packages_tab_default {
6692: my ($uri,$varname)=@_;
6693: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 6694:
6695: my (@extension,@specifics,$do_default);
6696: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 6697: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 6698: if ($pack_type eq 'default') {
6699: $do_default=1;
6700: } elsif ($pack_type eq 'extension') {
6701: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 6702: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 6703: # only look at packages defaults for packages that this id is
1.738 albertel 6704: push(@specifics,[$package,$pack_type,$pack_part]);
6705: }
6706: }
6707: # first look for a package that matches the requested part id
6708: foreach my $package (@specifics) {
6709: my (undef,$pack_type,$pack_part)=@{$package};
6710: next if ($pack_part ne $part);
6711: if (defined($packagetab{"$pack_type&$name&default"})) {
6712: return $packagetab{"$pack_type&$name&default"};
6713: }
6714: }
6715: # look for any possible matching non extension_ package
6716: foreach my $package (@specifics) {
6717: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 6718: if (defined($packagetab{"$pack_type&$name&default"})) {
6719: return $packagetab{"$pack_type&$name&default"};
6720: }
1.585 albertel 6721: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 6722: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
6723: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 6724: }
6725: }
1.738 albertel 6726: # look for any posible extension_ match
6727: foreach my $package (@extension) {
6728: my ($package,$pack_type)=@{$package};
6729: if (defined($packagetab{"$pack_type&$name&default"})) {
6730: return $packagetab{"$pack_type&$name&default"};
6731: }
6732: if (defined($packagetab{$package."&$name&default"})) {
6733: return $packagetab{$package."&$name&default"};
6734: }
6735: }
6736: # look for a global default setting
6737: if ($do_default && defined($packagetab{"default&$name&default"})) {
6738: return $packagetab{"default&$name&default"};
6739: }
1.395 albertel 6740: return undef;
6741: }
6742:
1.334 albertel 6743: sub add_prefix_and_part {
6744: my ($prefix,$part)=@_;
6745: my $keyroot;
6746: if (defined($prefix) && $prefix !~ /^__/) {
6747: # prefix that has a part already
6748: $keyroot=$prefix;
6749: } elsif (defined($prefix)) {
6750: # prefix that is missing a part
6751: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
6752: } else {
6753: # no prefix at all
6754: if (defined($part)) { $keyroot='_'.$part; }
6755: }
6756: return $keyroot;
6757: }
6758:
1.71 www 6759: # ---------------------------------------------------------------- Get metadata
6760:
1.599 albertel 6761: my %metaentry;
1.71 www 6762: sub metadata {
1.176 www 6763: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 6764: $uri=&declutter($uri);
1.288 albertel 6765: # if it is a non metadata possible uri return quickly
1.529 albertel 6766: if (($uri eq '') ||
6767: (($uri =~ m|^/*adm/|) &&
1.698 albertel 6768: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423 albertel 6769: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807 albertel 6770: ($uri =~ m|home/$match_username/public_html/|)) {
1.468 albertel 6771: return undef;
1.288 albertel 6772: }
1.73 www 6773: my $filename=$uri;
6774: $uri=~s/\.meta$//;
1.172 www 6775: #
6776: # Is the metadata already cached?
1.177 www 6777: # Look at timestamp of caching
1.172 www 6778: # Everything is cached by the main uri, libraries are never directly cached
6779: #
1.428 albertel 6780: if (!defined($liburi)) {
1.599 albertel 6781: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 6782: if (defined($cached)) { return $result->{':'.$what}; }
6783: }
6784: {
1.172 www 6785: #
6786: # Is this a recursive call for a library?
6787: #
1.599 albertel 6788: # if (! exists($metacache{$uri})) {
6789: # $metacache{$uri}={};
6790: # }
1.171 www 6791: if ($liburi) {
6792: $liburi=&declutter($liburi);
6793: $filename=$liburi;
1.401 bowersj2 6794: } else {
1.599 albertel 6795: &devalidate_cache_new('meta',$uri);
6796: undef(%metaentry);
1.401 bowersj2 6797: }
1.140 www 6798: my %metathesekeys=();
1.73 www 6799: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 6800: my $metastring;
1.768 albertel 6801: if ($uri !~ m -^(editupload)/-) {
1.543 albertel 6802: my $file=&filelocation('',&clutter($filename));
1.599 albertel 6803: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 6804: $metastring=&getfile($file);
1.489 albertel 6805: }
1.208 albertel 6806: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 6807: my $token;
1.140 www 6808: undef %metathesekeys;
1.71 www 6809: while ($token=$parser->get_token) {
1.339 albertel 6810: if ($token->[0] eq 'S') {
6811: if (defined($token->[2]->{'package'})) {
1.172 www 6812: #
6813: # This is a package - get package info
6814: #
1.339 albertel 6815: my $package=$token->[2]->{'package'};
6816: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6817: if (defined($token->[2]->{'id'})) {
6818: $keyroot.='_'.$token->[2]->{'id'};
6819: }
1.599 albertel 6820: if ($metaentry{':packages'}) {
6821: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 6822: } else {
1.599 albertel 6823: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 6824: }
1.736 albertel 6825: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 6826: my $part=$keyroot;
6827: $part=~s/^\_//;
1.736 albertel 6828: if ($pack_entry=~/^\Q$package\E\&/ ||
6829: $pack_entry=~/^\Q$package\E_0\&/) {
6830: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 6831: # ignore package.tab specified default values
6832: # here &package_tab_default() will fetch those
6833: if ($subp eq 'default') { next; }
1.736 albertel 6834: my $value=$packagetab{$pack_entry};
1.432 albertel 6835: my $unikey;
6836: if ($pack =~ /_0$/) {
6837: $unikey='parameter_0_'.$name;
6838: $part=0;
6839: } else {
6840: $unikey='parameter'.$keyroot.'_'.$name;
6841: }
1.339 albertel 6842: if ($subp eq 'display') {
6843: $value.=' [Part: '.$part.']';
6844: }
1.599 albertel 6845: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 6846: $metathesekeys{$unikey}=1;
1.599 albertel 6847: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6848: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 6849: }
1.599 albertel 6850: if (defined($metaentry{':'.$unikey.'.default'})) {
6851: $metaentry{':'.$unikey}=
6852: $metaentry{':'.$unikey.'.default'};
1.356 albertel 6853: }
1.339 albertel 6854: }
6855: }
6856: } else {
1.172 www 6857: #
6858: # This is not a package - some other kind of start tag
1.339 albertel 6859: #
6860: my $entry=$token->[1];
6861: my $unikey;
6862: if ($entry eq 'import') {
6863: $unikey='';
6864: } else {
6865: $unikey=$entry;
6866: }
6867: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6868:
6869: if (defined($token->[2]->{'id'})) {
6870: $unikey.='_'.$token->[2]->{'id'};
6871: }
1.175 www 6872:
1.339 albertel 6873: if ($entry eq 'import') {
1.175 www 6874: #
6875: # Importing a library here
1.339 albertel 6876: #
6877: if ($depthcount<20) {
6878: my $location=$parser->get_text('/import');
6879: my $dir=$filename;
6880: $dir=~s|[^/]*$||;
6881: $location=&filelocation($dir,$location);
1.736 albertel 6882: my $metadata =
6883: &metadata($uri,'keys', $location,$unikey,
6884: $depthcount+1);
6885: foreach my $meta (split(',',$metadata)) {
6886: $metaentry{':'.$meta}=$metaentry{':'.$meta};
6887: $metathesekeys{$meta}=1;
1.339 albertel 6888: }
6889: }
6890: } else {
6891:
6892: if (defined($token->[2]->{'name'})) {
6893: $unikey.='_'.$token->[2]->{'name'};
6894: }
6895: $metathesekeys{$unikey}=1;
1.736 albertel 6896: foreach my $param (@{$token->[3]}) {
6897: $metaentry{':'.$unikey.'.'.$param} =
6898: $token->[2]->{$param};
1.339 albertel 6899: }
6900: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 6901: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 6902: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
6903: # only ws inside the tag, and not in default, so use default
6904: # as value
1.599 albertel 6905: $metaentry{':'.$unikey}=$default;
1.908 albertel 6906: } elsif ( $internaltext =~ /\S/ ) {
6907: # something interesting inside the tag
6908: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 6909: } else {
1.908 albertel 6910: # no interesting values, don't set a default
1.339 albertel 6911: }
1.172 www 6912: # end of not-a-package not-a-library import
1.339 albertel 6913: }
1.172 www 6914: # end of not-a-package start tag
1.339 albertel 6915: }
1.172 www 6916: # the next is the end of "start tag"
1.339 albertel 6917: }
6918: }
1.483 albertel 6919: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 6920: $extension = lc($extension);
6921: if ($extension eq 'htm') { $extension='html'; }
6922:
1.737 albertel 6923: foreach my $key (keys(%packagetab)) {
1.483 albertel 6924: #no specific packages #how's our extension
6925: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 6926: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 6927: \%metathesekeys);
6928: }
1.883 albertel 6929:
6930: if (!exists($metaentry{':packages'})
6931: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 6932: foreach my $key (keys(%packagetab)) {
1.483 albertel 6933: #no specific packages well let's get default then
6934: if ($key!~/^default&/) { next; }
1.488 albertel 6935: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 6936: \%metathesekeys);
6937: }
6938: }
1.338 www 6939: # are there custom rights to evaluate
1.599 albertel 6940: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 6941:
1.338 www 6942: #
6943: # Importing a rights file here
1.339 albertel 6944: #
6945: unless ($depthcount) {
1.599 albertel 6946: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 6947: my $dir=$filename;
6948: $dir=~s|[^/]*$||;
6949: $location=&filelocation($dir,$location);
1.736 albertel 6950: my $rights_metadata =
6951: &metadata($uri,'keys',$location,'_rights',
6952: $depthcount+1);
6953: foreach my $rights (split(',',$rights_metadata)) {
6954: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
6955: $metathesekeys{$rights}=1;
1.339 albertel 6956: }
6957: }
6958: }
1.737 albertel 6959: # uniqifiy package listing
6960: my %seen;
6961: my @uniq_packages =
6962: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
6963: $metaentry{':packages'} = join(',',@uniq_packages);
6964:
6965: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 6966: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
6967: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699 albertel 6968: &do_cache_new('meta',$uri,\%metaentry,60*60);
1.177 www 6969: # this is the end of "was not already recently cached
1.71 www 6970: }
1.599 albertel 6971: return $metaentry{':'.$what};
1.261 albertel 6972: }
6973:
1.488 albertel 6974: sub metadata_create_package_def {
1.483 albertel 6975: my ($uri,$key,$package,$metathesekeys)=@_;
6976: my ($pack,$name,$subp)=split(/\&/,$key);
6977: if ($subp eq 'default') { next; }
6978:
1.599 albertel 6979: if (defined($metaentry{':packages'})) {
6980: $metaentry{':packages'}.=','.$package;
1.483 albertel 6981: } else {
1.599 albertel 6982: $metaentry{':packages'}=$package;
1.483 albertel 6983: }
6984: my $value=$packagetab{$key};
6985: my $unikey;
6986: $unikey='parameter_0_'.$name;
1.599 albertel 6987: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 6988: $$metathesekeys{$unikey}=1;
1.599 albertel 6989: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6990: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 6991: }
1.599 albertel 6992: if (defined($metaentry{':'.$unikey.'.default'})) {
6993: $metaentry{':'.$unikey}=
6994: $metaentry{':'.$unikey.'.default'};
1.483 albertel 6995: }
6996: }
6997:
1.261 albertel 6998: sub metadata_generate_part0 {
6999: my ($metadata,$metacache,$uri) = @_;
7000: my %allnames;
1.737 albertel 7001: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 7002: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 7003: my $part=$$metacache{':'.$metakey.'.part'};
7004: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 7005: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 7006: $allnames{$name}=$part;
7007: }
7008: }
7009: }
7010: foreach my $name (keys(%allnames)) {
7011: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 7012: my $key=":parameter_0_$name";
1.261 albertel 7013: $$metacache{"$key.part"}='0';
7014: $$metacache{"$key.name"}=$name;
1.428 albertel 7015: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 7016: $allnames{$name}.'_'.$name.
7017: '.type'};
1.428 albertel 7018: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 7019: '.display'};
1.644 www 7020: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 7021: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 7022: $$metacache{"$key.display"}=$olddis;
7023: }
1.71 www 7024: }
7025:
1.764 albertel 7026: # ------------------------------------------------------ Devalidate title cache
7027:
7028: sub devalidate_title_cache {
7029: my ($url)=@_;
7030: if (!$env{'request.course.id'}) { return; }
7031: my $symb=&symbread($url);
7032: if (!$symb) { return; }
7033: my $key=$env{'request.course.id'}."\0".$symb;
7034: &devalidate_cache_new('title',$key);
7035: }
7036:
1.301 www 7037: # ------------------------------------------------- Get the title of a resource
7038:
7039: sub gettitle {
7040: my $urlsymb=shift;
7041: my $symb=&symbread($urlsymb);
1.534 albertel 7042: if ($symb) {
1.620 albertel 7043: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 7044: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 7045: if (defined($cached)) {
7046: return $result;
7047: }
1.534 albertel 7048: my ($map,$resid,$url)=&decode_symb($symb);
7049: my $title='';
1.907 albertel 7050: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
7051: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
7052: } else {
7053: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7054: &GDBM_READER(),0640)) {
7055: my $mapid=$bighash{'map_pc_'.&clutter($map)};
7056: $title=$bighash{'title_'.$mapid.'.'.$resid};
7057: untie(%bighash);
7058: }
1.534 albertel 7059: }
7060: $title=~s/\&colon\;/\:/gs;
7061: if ($title) {
1.599 albertel 7062: return &do_cache_new('title',$key,$title,600);
1.534 albertel 7063: }
7064: $urlsymb=$url;
7065: }
7066: my $title=&metadata($urlsymb,'title');
7067: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
7068: return $title;
1.301 www 7069: }
1.613 albertel 7070:
1.614 albertel 7071: sub get_slot {
7072: my ($which,$cnum,$cdom)=@_;
7073: if (!$cnum || !$cdom) {
1.790 albertel 7074: (undef,my $courseid)=&whichuser();
1.620 albertel 7075: $cdom=$env{'course.'.$courseid.'.domain'};
7076: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 7077: }
1.703 albertel 7078: my $key=join("\0",'slots',$cdom,$cnum,$which);
7079: my %slotinfo;
7080: if (exists($remembered{$key})) {
7081: $slotinfo{$which} = $remembered{$key};
7082: } else {
7083: %slotinfo=&get('slots',[$which],$cdom,$cnum);
7084: &Apache::lonhomework::showhash(%slotinfo);
7085: my ($tmp)=keys(%slotinfo);
7086: if ($tmp=~/^error:/) { return (); }
7087: $remembered{$key} = $slotinfo{$which};
7088: }
1.616 albertel 7089: if (ref($slotinfo{$which}) eq 'HASH') {
7090: return %{$slotinfo{$which}};
7091: }
7092: return $slotinfo{$which};
1.614 albertel 7093: }
1.31 www 7094: # ------------------------------------------------- Update symbolic store links
7095:
7096: sub symblist {
7097: my ($mapname,%newhash)=@_;
1.438 www 7098: $mapname=&deversion(&declutter($mapname));
1.31 www 7099: my %hash;
1.620 albertel 7100: if (($env{'request.course.fn'}) && (%newhash)) {
7101: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7102: &GDBM_WRCREAT(),0640)) {
1.711 albertel 7103: foreach my $url (keys %newhash) {
7104: next if ($url eq 'last_known'
7105: && $env{'form.no_update_last_known'});
7106: $hash{declutter($url)}=&encode_symb($mapname,
7107: $newhash{$url}->[1],
7108: $newhash{$url}->[0]);
1.191 harris41 7109: }
1.31 www 7110: if (untie(%hash)) {
7111: return 'ok';
7112: }
7113: }
7114: }
7115: return 'error';
1.212 www 7116: }
7117:
7118: # --------------------------------------------------------------- Verify a symb
7119:
7120: sub symbverify {
1.510 www 7121: my ($symb,$thisurl)=@_;
7122: my $thisfn=$thisurl;
1.439 www 7123: $thisfn=&declutter($thisfn);
1.215 www 7124: # direct jump to resource in page or to a sequence - will construct own symbs
7125: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
7126: # check URL part
1.409 www 7127: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 7128:
1.431 www 7129: unless ($url eq $thisfn) { return 0; }
1.213 www 7130:
1.216 www 7131: $symb=&symbclean($symb);
1.510 www 7132: $thisurl=&deversion($thisurl);
1.439 www 7133: $thisfn=&deversion($thisfn);
1.213 www 7134:
7135: my %bighash;
7136: my $okay=0;
1.431 www 7137:
1.620 albertel 7138: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7139: &GDBM_READER(),0640)) {
1.510 www 7140: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 7141: unless ($ids) {
1.510 www 7142: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 7143: }
7144: if ($ids) {
7145: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 7146: foreach my $id (split(/\,/,$ids)) {
7147: my ($mapid,$resid)=split(/\./,$id);
1.216 www 7148: if (
7149: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
7150: eq $symb) {
1.620 albertel 7151: if (($env{'request.role.adv'}) ||
1.800 albertel 7152: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 7153: $okay=1;
7154: }
7155: }
1.216 www 7156: }
7157: }
1.213 www 7158: untie(%bighash);
7159: }
7160: return $okay;
1.31 www 7161: }
7162:
1.210 www 7163: # --------------------------------------------------------------- Clean-up symb
7164:
7165: sub symbclean {
7166: my $symb=shift;
1.568 albertel 7167: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 7168: # remove version from map
7169: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 7170:
1.210 www 7171: # remove version from URL
7172: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 7173:
1.507 www 7174: # remove wrapper
7175:
1.510 www 7176: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 7177: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 7178: return $symb;
1.409 www 7179: }
7180:
7181: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 7182:
7183: sub encode_symb {
7184: my ($map,$resid,$url)=@_;
7185: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
7186: }
1.409 www 7187:
7188: sub decode_symb {
1.568 albertel 7189: my $symb=shift;
7190: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
7191: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 7192: return (&fixversion($map),$resid,&fixversion($url));
7193: }
7194:
7195: sub fixversion {
7196: my $fn=shift;
1.609 banghart 7197: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 7198: my %bighash;
7199: my $uri=&clutter($fn);
1.620 albertel 7200: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 7201: # is this cached?
1.599 albertel 7202: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 7203: if (defined($cached)) { return $result; }
7204: # unfortunately not cached, or expired
1.620 albertel 7205: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 7206: &GDBM_READER(),0640)) {
7207: if ($bighash{'version_'.$uri}) {
7208: my $version=$bighash{'version_'.$uri};
1.444 www 7209: unless (($version eq 'mostrecent') ||
7210: ($version==&getversion($uri))) {
1.440 www 7211: $uri=~s/\.(\w+)$/\.$version\.$1/;
7212: }
7213: }
7214: untie %bighash;
1.413 www 7215: }
1.599 albertel 7216: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 7217: }
7218:
7219: sub deversion {
7220: my $url=shift;
7221: $url=~s/\.\d+\.(\w+)$/\.$1/;
7222: return $url;
1.210 www 7223: }
7224:
1.31 www 7225: # ------------------------------------------------------ Return symb list entry
7226:
7227: sub symbread {
1.249 www 7228: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 7229: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 7230: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 7231: # no filename provided? try from environment
1.44 www 7232: unless ($thisfn) {
1.620 albertel 7233: if ($env{'request.symb'}) {
7234: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 7235: }
1.620 albertel 7236: $thisfn=$env{'request.filename'};
1.44 www 7237: }
1.569 albertel 7238: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 7239: # is that filename actually a symb? Verify, clean, and return
7240: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 7241: if (&symbverify($thisfn,$1)) {
1.620 albertel 7242: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 7243: }
1.242 www 7244: }
1.44 www 7245: $thisfn=declutter($thisfn);
1.31 www 7246: my %hash;
1.37 www 7247: my %bighash;
7248: my $syval='';
1.620 albertel 7249: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 7250: my $targetfn = $thisfn;
1.609 banghart 7251: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 7252: $targetfn = 'adm/wrapper/'.$thisfn;
7253: }
1.687 albertel 7254: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
7255: $targetfn=$1;
7256: }
1.620 albertel 7257: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7258: &GDBM_READER(),0640)) {
1.481 raeburn 7259: $syval=$hash{$targetfn};
1.37 www 7260: untie(%hash);
7261: }
7262: # ---------------------------------------------------------- There was an entry
7263: if ($syval) {
1.601 albertel 7264: #unless ($syval=~/\_\d+$/) {
1.620 albertel 7265: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601 albertel 7266: #&appenv('request.ambiguous' => $thisfn);
1.620 albertel 7267: #return $env{$cache_str}='';
1.601 albertel 7268: #}
7269: #$syval.=$1;
7270: #}
1.37 www 7271: } else {
7272: # ------------------------------------------------------- Was not in symb table
1.620 albertel 7273: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7274: &GDBM_READER(),0640)) {
1.37 www 7275: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 7276: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 7277: unless ($ids) {
7278: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 7279: }
7280: unless ($ids) {
7281: # alias?
7282: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 7283: }
1.37 www 7284: if ($ids) {
7285: # ------------------------------------------------------------------- Has ID(s)
7286: my @possibilities=split(/\,/,$ids);
1.39 www 7287: if ($#possibilities==0) {
7288: # ----------------------------------------------- There is only one possibility
1.37 www 7289: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 7290: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7291: $resid,$thisfn);
1.249 www 7292: } elsif (!$donotrecurse) {
1.39 www 7293: # ------------------------------------------ There is more than one possibility
7294: my $realpossible=0;
1.800 albertel 7295: foreach my $id (@possibilities) {
7296: my $file=$bighash{'src_'.$id};
1.39 www 7297: if (&allowed('bre',$file)) {
1.800 albertel 7298: my ($mapid,$resid)=split(/\./,$id);
1.39 www 7299: if ($bighash{'map_type_'.$mapid} ne 'page') {
7300: $realpossible++;
1.626 albertel 7301: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7302: $resid,$thisfn);
1.39 www 7303: }
7304: }
1.191 harris41 7305: }
1.39 www 7306: if ($realpossible!=1) { $syval=''; }
1.249 www 7307: } else {
7308: $syval='';
1.37 www 7309: }
7310: }
7311: untie(%bighash)
1.481 raeburn 7312: }
1.31 www 7313: }
1.62 www 7314: if ($syval) {
1.620 albertel 7315: return $env{$cache_str}=$syval;
1.62 www 7316: }
1.31 www 7317: }
1.44 www 7318: &appenv('request.ambiguous' => $thisfn);
1.620 albertel 7319: return $env{$cache_str}='';
1.31 www 7320: }
7321:
7322: # ---------------------------------------------------------- Return random seed
7323:
1.32 www 7324: sub numval {
7325: my $txt=shift;
7326: $txt=~tr/A-J/0-9/;
7327: $txt=~tr/a-j/0-9/;
7328: $txt=~tr/K-T/0-9/;
7329: $txt=~tr/k-t/0-9/;
7330: $txt=~tr/U-Z/0-5/;
7331: $txt=~tr/u-z/0-5/;
7332: $txt=~s/\D//g;
1.564 albertel 7333: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 7334: return int($txt);
1.368 albertel 7335: }
7336:
1.484 albertel 7337: sub numval2 {
7338: my $txt=shift;
7339: $txt=~tr/A-J/0-9/;
7340: $txt=~tr/a-j/0-9/;
7341: $txt=~tr/K-T/0-9/;
7342: $txt=~tr/k-t/0-9/;
7343: $txt=~tr/U-Z/0-5/;
7344: $txt=~tr/u-z/0-5/;
7345: $txt=~s/\D//g;
7346: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7347: my $total;
7348: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 7349: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 7350: return int($total);
7351: }
7352:
1.575 albertel 7353: sub numval3 {
7354: use integer;
7355: my $txt=shift;
7356: $txt=~tr/A-J/0-9/;
7357: $txt=~tr/a-j/0-9/;
7358: $txt=~tr/K-T/0-9/;
7359: $txt=~tr/k-t/0-9/;
7360: $txt=~tr/U-Z/0-5/;
7361: $txt=~tr/u-z/0-5/;
7362: $txt=~s/\D//g;
7363: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7364: my $total;
7365: foreach my $val (@txts) { $total+=$val; }
7366: if ($_64bit) { $total=(($total<<32)>>32); }
7367: return $total;
7368: }
7369:
1.675 albertel 7370: sub digest {
7371: my ($data)=@_;
7372: my $digest=&Digest::MD5::md5($data);
7373: my ($a,$b,$c,$d)=unpack("iiii",$digest);
7374: my ($e,$f);
7375: {
7376: use integer;
7377: $e=($a+$b);
7378: $f=($c+$d);
7379: if ($_64bit) {
7380: $e=(($e<<32)>>32);
7381: $f=(($f<<32)>>32);
7382: }
7383: }
7384: if (wantarray) {
7385: return ($e,$f);
7386: } else {
7387: my $g;
7388: {
7389: use integer;
7390: $g=($e+$f);
7391: if ($_64bit) {
7392: $g=(($g<<32)>>32);
7393: }
7394: }
7395: return $g;
7396: }
7397: }
7398:
1.368 albertel 7399: sub latest_rnd_algorithm_id {
1.675 albertel 7400: return '64bit5';
1.366 albertel 7401: }
1.32 www 7402:
1.503 albertel 7403: sub get_rand_alg {
7404: my ($courseid)=@_;
1.790 albertel 7405: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 7406: if ($courseid) {
1.620 albertel 7407: return $env{"course.$courseid.rndseed"};
1.503 albertel 7408: }
7409: return &latest_rnd_algorithm_id();
7410: }
7411:
1.562 albertel 7412: sub validCODE {
7413: my ($CODE)=@_;
7414: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
7415: return 0;
7416: }
7417:
1.491 albertel 7418: sub getCODE {
1.620 albertel 7419: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 7420: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
7421: defined($Apache::lonhomework::parsing_a_task) ) &&
7422: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 7423: return $Apache::lonhomework::history{'resource.CODE'};
7424: }
7425: return undef;
7426: }
7427:
1.31 www 7428: sub rndseed {
1.155 albertel 7429: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 7430: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 7431: if (!defined($symb)) {
1.366 albertel 7432: unless ($symb=$wsymb) { return time; }
7433: }
7434: if (!$courseid) { $courseid=$wcourseid; }
7435: if (!$domain) { $domain=$wdomain; }
7436: if (!$username) { $username=$wusername }
1.503 albertel 7437: my $which=&get_rand_alg();
1.803 albertel 7438:
1.491 albertel 7439: if (defined(&getCODE())) {
1.675 albertel 7440: if ($which eq '64bit5') {
7441: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
7442: } elsif ($which eq '64bit4') {
1.575 albertel 7443: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
7444: } else {
7445: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
7446: }
1.675 albertel 7447: } elsif ($which eq '64bit5') {
7448: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 7449: } elsif ($which eq '64bit4') {
7450: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 7451: } elsif ($which eq '64bit3') {
7452: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 7453: } elsif ($which eq '64bit2') {
7454: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 7455: } elsif ($which eq '64bit') {
7456: return &rndseed_64bit($symb,$courseid,$domain,$username);
7457: }
7458: return &rndseed_32bit($symb,$courseid,$domain,$username);
7459: }
7460:
7461: sub rndseed_32bit {
7462: my ($symb,$courseid,$domain,$username)=@_;
7463: {
7464: use integer;
7465: my $symbchck=unpack("%32C*",$symb) << 27;
7466: my $symbseed=numval($symb) << 22;
7467: my $namechck=unpack("%32C*",$username) << 17;
7468: my $nameseed=numval($username) << 12;
7469: my $domainseed=unpack("%32C*",$domain) << 7;
7470: my $courseseed=unpack("%32C*",$courseid);
7471: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 7472: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7473: #&logthis("rndseed :$num:$symb");
1.564 albertel 7474: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 7475: return $num;
7476: }
7477: }
7478:
7479: sub rndseed_64bit {
7480: my ($symb,$courseid,$domain,$username)=@_;
7481: {
7482: use integer;
7483: my $symbchck=unpack("%32S*",$symb) << 21;
7484: my $symbseed=numval($symb) << 10;
7485: my $namechck=unpack("%32S*",$username);
7486:
7487: my $nameseed=numval($username) << 21;
7488: my $domainseed=unpack("%32S*",$domain) << 10;
7489: my $courseseed=unpack("%32S*",$courseid);
7490:
7491: my $num1=$symbchck+$symbseed+$namechck;
7492: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7493: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7494: #&logthis("rndseed :$num:$symb");
1.564 albertel 7495: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 7496: return "$num1,$num2";
1.155 albertel 7497: }
1.366 albertel 7498: }
7499:
1.443 albertel 7500: sub rndseed_64bit2 {
7501: my ($symb,$courseid,$domain,$username)=@_;
7502: {
7503: use integer;
7504: # strings need to be an even # of cahracters long, it it is odd the
7505: # last characters gets thrown away
7506: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7507: my $symbseed=numval($symb) << 10;
7508: my $namechck=unpack("%32S*",$username.' ');
7509:
7510: my $nameseed=numval($username) << 21;
1.501 albertel 7511: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7512: my $courseseed=unpack("%32S*",$courseid.' ');
7513:
7514: my $num1=$symbchck+$symbseed+$namechck;
7515: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7516: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7517: #&logthis("rndseed :$num:$symb");
1.803 albertel 7518: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 7519: return "$num1,$num2";
7520: }
7521: }
7522:
7523: sub rndseed_64bit3 {
7524: my ($symb,$courseid,$domain,$username)=@_;
7525: {
7526: use integer;
7527: # strings need to be an even # of cahracters long, it it is odd the
7528: # last characters gets thrown away
7529: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7530: my $symbseed=numval2($symb) << 10;
7531: my $namechck=unpack("%32S*",$username.' ');
7532:
7533: my $nameseed=numval2($username) << 21;
1.443 albertel 7534: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7535: my $courseseed=unpack("%32S*",$courseid.' ');
7536:
7537: my $num1=$symbchck+$symbseed+$namechck;
7538: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7539: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7540: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 7541: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7542:
1.503 albertel 7543: return "$num1:$num2";
1.443 albertel 7544: }
7545: }
7546:
1.575 albertel 7547: sub rndseed_64bit4 {
7548: my ($symb,$courseid,$domain,$username)=@_;
7549: {
7550: use integer;
7551: # strings need to be an even # of cahracters long, it it is odd the
7552: # last characters gets thrown away
7553: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7554: my $symbseed=numval3($symb) << 10;
7555: my $namechck=unpack("%32S*",$username.' ');
7556:
7557: my $nameseed=numval3($username) << 21;
7558: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7559: my $courseseed=unpack("%32S*",$courseid.' ');
7560:
7561: my $num1=$symbchck+$symbseed+$namechck;
7562: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7563: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7564: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 7565: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7566:
7567: return "$num1:$num2";
7568: }
7569: }
7570:
1.675 albertel 7571: sub rndseed_64bit5 {
7572: my ($symb,$courseid,$domain,$username)=@_;
7573: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
7574: return "$num1:$num2";
7575: }
7576:
1.366 albertel 7577: sub rndseed_CODE_64bit {
7578: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 7579: {
1.366 albertel 7580: use integer;
1.443 albertel 7581: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 7582: my $symbseed=numval2($symb);
1.491 albertel 7583: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7584: my $CODEseed=numval(&getCODE());
1.443 albertel 7585: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 7586: my $num1=$symbseed+$CODEchck;
7587: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7588: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7589: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 7590: if ($_64bit) { $num1=(($num1<<32)>>32); }
7591: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 7592: return "$num1:$num2";
1.366 albertel 7593: }
7594: }
7595:
1.575 albertel 7596: sub rndseed_CODE_64bit4 {
7597: my ($symb,$courseid,$domain,$username)=@_;
7598: {
7599: use integer;
7600: my $symbchck=unpack("%32S*",$symb.' ') << 16;
7601: my $symbseed=numval3($symb);
7602: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7603: my $CODEseed=numval3(&getCODE());
7604: my $courseseed=unpack("%32S*",$courseid.' ');
7605: my $num1=$symbseed+$CODEchck;
7606: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7607: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7608: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 7609: if ($_64bit) { $num1=(($num1<<32)>>32); }
7610: if ($_64bit) { $num2=(($num2<<32)>>32); }
7611: return "$num1:$num2";
7612: }
7613: }
7614:
1.675 albertel 7615: sub rndseed_CODE_64bit5 {
7616: my ($symb,$courseid,$domain,$username)=@_;
7617: my $code = &getCODE();
7618: my ($num1,$num2)=&digest("$symb,$courseid,$code");
7619: return "$num1:$num2";
7620: }
7621:
1.366 albertel 7622: sub setup_random_from_rndseed {
7623: my ($rndseed)=@_;
1.503 albertel 7624: if ($rndseed =~/([,:])/) {
7625: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 7626: &Math::Random::random_set_seed(abs($num1),abs($num2));
7627: } else {
7628: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 7629: }
1.36 albertel 7630: }
7631:
1.474 albertel 7632: sub latest_receipt_algorithm_id {
1.835 albertel 7633: return 'receipt3';
1.474 albertel 7634: }
7635:
1.480 www 7636: sub recunique {
7637: my $fucourseid=shift;
7638: my $unique;
1.835 albertel 7639: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
7640: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7641: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 7642: } else {
7643: $unique=$perlvar{'lonReceipt'};
7644: }
7645: return unpack("%32C*",$unique);
7646: }
7647:
7648: sub recprefix {
7649: my $fucourseid=shift;
7650: my $prefix;
1.835 albertel 7651: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
7652: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7653: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 7654: } else {
7655: $prefix=$perlvar{'lonHostID'};
7656: }
7657: return unpack("%32C*",$prefix);
7658: }
7659:
1.76 www 7660: sub ireceipt {
1.474 albertel 7661: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 7662:
7663: my $return =&recprefix($fucourseid).'-';
7664:
7665: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
7666: $env{'request.state'} eq 'construct') {
7667: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
7668: return $return;
7669: }
7670:
1.76 www 7671: my $cuname=unpack("%32C*",$funame);
7672: my $cudom=unpack("%32C*",$fudom);
7673: my $cucourseid=unpack("%32C*",$fucourseid);
7674: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 7675: my $cunique=&recunique($fucourseid);
1.474 albertel 7676: my $cpart=unpack("%32S*",$part);
1.835 albertel 7677: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
7678:
1.790 albertel 7679: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 7680:
7681: $return.= ($cunique%$cuname+
7682: $cunique%$cudom+
7683: $cusymb%$cuname+
7684: $cusymb%$cudom+
7685: $cucourseid%$cuname+
7686: $cucourseid%$cudom+
7687: $cpart%$cuname+
7688: $cpart%$cudom);
7689: } else {
7690: $return.= ($cunique%$cuname+
7691: $cunique%$cudom+
7692: $cusymb%$cuname+
7693: $cusymb%$cudom+
7694: $cucourseid%$cuname+
7695: $cucourseid%$cudom);
7696: }
7697: return $return;
1.76 www 7698: }
7699:
7700: sub receipt {
1.474 albertel 7701: my ($part)=@_;
1.790 albertel 7702: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 7703: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 7704: }
1.260 ng 7705:
1.790 albertel 7706: sub whichuser {
7707: my ($passedsymb)=@_;
7708: my ($symb,$courseid,$domain,$name,$publicuser);
7709: if (defined($env{'form.grade_symb'})) {
7710: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
7711: my $allowed=&allowed('vgr',$tmp_courseid);
7712: if (!$allowed &&
7713: exists($env{'request.course.sec'}) &&
7714: $env{'request.course.sec'} !~ /^\s*$/) {
7715: $allowed=&allowed('vgr',$tmp_courseid.
7716: '/'.$env{'request.course.sec'});
7717: }
7718: if ($allowed) {
7719: ($symb)=&get_env_multiple('form.grade_symb');
7720: $courseid=$tmp_courseid;
7721: ($domain)=&get_env_multiple('form.grade_domain');
7722: ($name)=&get_env_multiple('form.grade_username');
7723: return ($symb,$courseid,$domain,$name,$publicuser);
7724: }
7725: }
7726: if (!$passedsymb) {
7727: $symb=&symbread();
7728: } else {
7729: $symb=$passedsymb;
7730: }
7731: $courseid=$env{'request.course.id'};
7732: $domain=$env{'user.domain'};
7733: $name=$env{'user.name'};
7734: if ($name eq 'public' && $domain eq 'public') {
7735: if (!defined($env{'form.username'})) {
7736: $env{'form.username'}.=time.rand(10000000);
7737: }
7738: $name.=$env{'form.username'};
7739: }
7740: return ($symb,$courseid,$domain,$name,$publicuser);
7741:
7742: }
7743:
1.36 albertel 7744: # ------------------------------------------------------------ Serves up a file
1.472 albertel 7745: # returns either the contents of the file or
7746: # -1 if the file doesn't exist
1.481 raeburn 7747: #
7748: # if the target is a file that was uploaded via DOCS,
7749: # a check will be made to see if a current copy exists on the local server,
7750: # if it does this will be served, otherwise a copy will be retrieved from
7751: # the home server for the course and stored in /home/httpd/html/userfiles on
7752: # the local server.
1.472 albertel 7753:
1.36 albertel 7754: sub getfile {
1.538 albertel 7755: my ($file) = @_;
1.609 banghart 7756: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 7757: &repcopy($file);
7758: return &readfile($file);
7759: }
7760:
7761: sub repcopy_userfile {
7762: my ($file)=@_;
1.609 banghart 7763: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 7764: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 7765: my ($cdom,$cnum,$filename) =
1.811 albertel 7766: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 7767: my $uri="/uploaded/$cdom/$cnum/$filename";
7768: if (-e "$file") {
1.828 www 7769: # we already have a local copy, check it out
1.538 albertel 7770: my @fileinfo = stat($file);
1.828 www 7771: my $rtncode;
7772: my $info;
1.538 albertel 7773: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 7774: if ($lwpresp ne 'ok') {
1.828 www 7775: # there is no such file anymore, even though we had a local copy
1.482 albertel 7776: if ($rtncode eq '404') {
1.538 albertel 7777: unlink($file);
1.482 albertel 7778: }
7779: return -1;
7780: }
7781: if ($info < $fileinfo[9]) {
1.828 www 7782: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 7783: return 'ok';
1.828 www 7784: } else {
7785: # the file is outdated, get rid of it
7786: unlink($file);
1.482 albertel 7787: }
1.828 www 7788: }
7789: # one way or the other, at this point, we don't have the file
7790: # construct the correct path for the file
7791: my @parts = ($cdom,$cnum);
7792: if ($filename =~ m|^(.+)/[^/]+$|) {
7793: push @parts, split(/\//,$1);
7794: }
7795: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
7796: foreach my $part (@parts) {
7797: $path .= '/'.$part;
7798: if (!-e $path) {
7799: mkdir($path,0770);
1.482 albertel 7800: }
7801: }
1.828 www 7802: # now the path exists for sure
7803: # get a user agent
7804: my $ua=new LWP::UserAgent;
7805: my $transferfile=$file.'.in.transfer';
7806: # FIXME: this should flock
7807: if (-e $transferfile) { return 'ok'; }
7808: my $request;
7809: $uri=~s/^\///;
1.838 albertel 7810: $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828 www 7811: my $response=$ua->request($request,$transferfile);
7812: # did it work?
7813: if ($response->is_error()) {
7814: unlink($transferfile);
7815: &logthis("Userfile repcopy failed for $uri");
7816: return -1;
7817: }
7818: # worked, rename the transfer file
7819: rename($transferfile,$file);
1.607 raeburn 7820: return 'ok';
1.481 raeburn 7821: }
7822:
1.517 albertel 7823: sub tokenwrapper {
7824: my $uri=shift;
1.552 albertel 7825: $uri=~s|^http\://([^/]+)||;
7826: $uri=~s|^/||;
1.620 albertel 7827: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 7828: my $token=$1;
1.552 albertel 7829: my (undef,$udom,$uname,$file)=split('/',$uri,4);
7830: if ($udom && $uname && $file) {
7831: $file=~s|(\?\.*)*$||;
1.620 albertel 7832: &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838 albertel 7833: return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517 albertel 7834: (($uri=~/\?/)?'&':'?').'token='.$token.
7835: '&tokenissued='.$perlvar{'lonHostID'};
7836: } else {
7837: return '/adm/notfound.html';
7838: }
7839: }
7840:
1.828 www 7841: # call with reqtype HEAD: get last modification time
7842: # call with reqtype GET: get the file contents
7843: # Do not call this with reqtype GET for large files! It loads everything into memory
7844: #
1.481 raeburn 7845: sub getuploaded {
7846: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
7847: $uri=~s/^\///;
1.838 albertel 7848: $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481 raeburn 7849: my $ua=new LWP::UserAgent;
7850: my $request=new HTTP::Request($reqtype,$uri);
7851: my $response=$ua->request($request);
7852: $$rtncode = $response->code;
1.482 albertel 7853: if (! $response->is_success()) {
7854: return 'failed';
7855: }
7856: if ($reqtype eq 'HEAD') {
1.486 www 7857: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 7858: } elsif ($reqtype eq 'GET') {
7859: $$info = $response->content;
1.472 albertel 7860: }
1.482 albertel 7861: return 'ok';
1.36 albertel 7862: }
7863:
1.481 raeburn 7864: sub readfile {
7865: my $file = shift;
7866: if ( (! -e $file ) || ($file eq '') ) { return -1; };
7867: my $fh;
7868: open($fh,"<$file");
7869: my $a='';
1.800 albertel 7870: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 7871: return $a;
7872: }
7873:
1.36 albertel 7874: sub filelocation {
1.590 banghart 7875: my ($dir,$file) = @_;
7876: my $location;
7877: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 7878:
7879: if ($file =~ m-^/adm/-) {
7880: $file=~s-^/adm/wrapper/-/-;
7881: $file=~s-^/adm/coursedocs/showdoc/-/-;
7882: }
1.882 albertel 7883:
1.590 banghart 7884: if ($file=~m:^/~:) { # is a contruction space reference
7885: $location = $file;
7886: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 7887: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 7888: # is a correct contruction space reference
7889: $location = $file;
1.609 banghart 7890: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 7891: my ($udom,$uname,$filename)=
1.811 albertel 7892: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 7893: my $home=&homeserver($uname,$udom);
7894: my $is_me=0;
7895: my @ids=¤t_machine_ids();
7896: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
7897: if ($is_me) {
1.740 www 7898: $location=&propath($udom,$uname).
1.590 banghart 7899: '/userfiles/'.$filename;
7900: } else {
7901: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
7902: $udom.'/'.$uname.'/'.$filename;
7903: }
1.882 albertel 7904: } elsif ($file =~ m-^/adm/-) {
7905: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 7906: } else {
7907: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
7908: $file=~s:^/res/:/:;
7909: if ( !( $file =~ m:^/:) ) {
7910: $location = $dir. '/'.$file;
7911: } else {
7912: $location = '/home/httpd/html/res'.$file;
7913: }
1.59 albertel 7914: }
1.590 banghart 7915: $location=~s://+:/:g; # remove duplicate /
7916: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
7917: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
7918: return $location;
1.46 www 7919: }
1.36 albertel 7920:
1.46 www 7921: sub hreflocation {
7922: my ($dir,$file)=@_;
1.460 albertel 7923: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666 albertel 7924: $file=filelocation($dir,$file);
1.700 albertel 7925: } elsif ($file=~m-^/adm/-) {
7926: $file=~s-^/adm/wrapper/-/-;
7927: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 7928: }
7929: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
7930: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 7931: } elsif ($file=~m-/home/($match_username)/public_html/-) {
7932: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 7933: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 7934: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 7935: -/uploaded/$1/$2/-x;
1.46 www 7936: }
1.913 albertel 7937: if ($file=~ m{^/userfiles/}) {
7938: $file =~ s{^/userfiles/}{/uploaded/};
7939: }
1.462 albertel 7940: return $file;
1.465 albertel 7941: }
7942:
7943: sub current_machine_domains {
1.853 albertel 7944: return &machine_domains(&hostname($perlvar{'lonHostID'}));
7945: }
7946:
7947: sub machine_domains {
7948: my ($hostname) = @_;
1.465 albertel 7949: my @domains;
1.838 albertel 7950: my %hostname = &all_hostnames();
1.465 albertel 7951: while( my($id, $name) = each(%hostname)) {
1.467 matthew 7952: # &logthis("-$id-$name-$hostname-");
1.465 albertel 7953: if ($hostname eq $name) {
1.844 albertel 7954: push(@domains,&host_domain($id));
1.465 albertel 7955: }
7956: }
7957: return @domains;
7958: }
7959:
7960: sub current_machine_ids {
1.853 albertel 7961: return &machine_ids(&hostname($perlvar{'lonHostID'}));
7962: }
7963:
7964: sub machine_ids {
7965: my ($hostname) = @_;
7966: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 7967: my @ids;
1.888 albertel 7968: my %name_to_host = &all_names();
1.889 albertel 7969: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
7970: return @{ $name_to_host{$hostname} };
7971: }
7972: return;
1.31 www 7973: }
7974:
1.824 raeburn 7975: sub additional_machine_domains {
7976: my @domains;
7977: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
7978: while( my $line = <$fh>) {
7979: $line =~ s/\s//g;
7980: push(@domains,$line);
7981: }
7982: return @domains;
7983: }
7984:
7985: sub default_login_domain {
7986: my $domain = $perlvar{'lonDefDomain'};
7987: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
7988: foreach my $posdom (¤t_machine_domains(),
7989: &additional_machine_domains()) {
7990: if (lc($posdom) eq lc($testdomain)) {
7991: $domain=$posdom;
7992: last;
7993: }
7994: }
7995: return $domain;
7996: }
7997:
1.31 www 7998: # ------------------------------------------------------------- Declutters URLs
7999:
8000: sub declutter {
8001: my $thisfn=shift;
1.569 albertel 8002: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 8003: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 8004: $thisfn=~s/^\///;
1.697 albertel 8005: $thisfn=~s|^adm/wrapper/||;
8006: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 8007: $thisfn=~s/^res\///;
1.235 www 8008: $thisfn=~s/\?.+$//;
1.268 www 8009: return $thisfn;
8010: }
8011:
8012: # ------------------------------------------------------------- Clutter up URLs
8013:
8014: sub clutter {
8015: my $thisfn='/'.&declutter(shift);
1.887 albertel 8016: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 8017: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 8018: $thisfn='/res'.$thisfn;
8019: }
1.694 albertel 8020: if ($thisfn !~m|/adm|) {
1.695 albertel 8021: if ($thisfn =~ m|/ext/|) {
1.694 albertel 8022: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 8023: } else {
8024: my ($ext) = ($thisfn =~ /\.(\w+)$/);
8025: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 8026: if ($embstyle eq 'ssi'
8027: || ($embstyle eq 'hdn')
8028: || ($embstyle eq 'rat')
8029: || ($embstyle eq 'prv')
8030: || ($embstyle eq 'ign')) {
8031: #do nothing with these
8032: } elsif (($embstyle eq 'img')
1.695 albertel 8033: || ($embstyle eq 'emb')
8034: || ($embstyle eq 'wrp')) {
8035: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 8036: } elsif ($embstyle eq 'unk'
8037: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 8038: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 8039: } else {
1.718 www 8040: # &logthis("Got a blank emb style");
1.695 albertel 8041: }
1.694 albertel 8042: }
8043: }
1.31 www 8044: return $thisfn;
1.12 www 8045: }
8046:
1.787 albertel 8047: sub clutter_with_no_wrapper {
8048: my $uri = &clutter(shift);
8049: if ($uri =~ m-^/adm/-) {
8050: $uri =~ s-^/adm/wrapper/-/-;
8051: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
8052: }
8053: return $uri;
8054: }
8055:
1.557 albertel 8056: sub freeze_escape {
8057: my ($value)=@_;
8058: if (ref($value)) {
8059: $value=&nfreeze($value);
8060: return '__FROZEN__'.&escape($value);
8061: }
8062: return &escape($value);
8063: }
8064:
1.11 www 8065:
1.557 albertel 8066: sub thaw_unescape {
8067: my ($value)=@_;
8068: if ($value =~ /^__FROZEN__/) {
8069: substr($value,0,10,undef);
8070: $value=&unescape($value);
8071: return &thaw($value);
8072: }
8073: return &unescape($value);
8074: }
8075:
1.436 albertel 8076: sub correct_line_ends {
8077: my ($result)=@_;
8078: $$result =~s/\r\n/\n/mg;
8079: $$result =~s/\r/\n/mg;
1.415 albertel 8080: }
1.1 albertel 8081: # ================================================================ Main Program
8082:
1.184 www 8083: sub goodbye {
1.204 albertel 8084: &logthis("Starting Shut down");
1.443 albertel 8085: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 8086: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 8087: #converted
1.599 albertel 8088: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 8089: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
8090: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
8091: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 8092: #1.1 only
1.870 albertel 8093: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
8094: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
8095: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
8096: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
8097: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 8098: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
8099: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 8100: &flushcourselogs();
8101: &logthis("Shutting down");
8102: }
8103:
1.852 albertel 8104: sub get_dns {
1.869 albertel 8105: my ($url,$func,$ignore_cache) = @_;
8106: if (!$ignore_cache) {
8107: my ($content,$cached)=
8108: &Apache::lonnet::is_cached_new('dns',$url);
8109: if ($cached) {
8110: &$func($content);
8111: return;
8112: }
8113: }
8114:
8115: my %alldns;
1.852 albertel 8116: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8117: foreach my $dns (<$config>) {
8118: next if ($dns !~ /^\^(\S*)/x);
1.869 albertel 8119: $alldns{$1} = 1;
8120: }
8121: while (%alldns) {
8122: my ($dns) = keys(%alldns);
8123: delete($alldns{$dns});
1.852 albertel 8124: my $ua=new LWP::UserAgent;
8125: my $request=new HTTP::Request('GET',"http://$dns$url");
8126: my $response=$ua->request($request);
8127: next if ($response->is_error());
8128: my @content = split("\n",$response->content);
1.869 albertel 8129: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 8130: &$func(\@content);
1.869 albertel 8131: return;
1.852 albertel 8132: }
8133: close($config);
1.871 albertel 8134: my $which = (split('/',$url))[3];
8135: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
8136: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 8137: my @content = <$config>;
8138: &$func(\@content);
8139: return;
1.852 albertel 8140: }
1.327 albertel 8141: # ------------------------------------------------------------ Read domain file
8142: {
1.852 albertel 8143: my $loaded;
1.846 albertel 8144: my %domain;
8145:
1.852 albertel 8146: sub parse_domain_tab {
8147: my ($lines) = @_;
8148: foreach my $line (@$lines) {
8149: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 8150:
1.846 albertel 8151: chomp($line);
1.852 albertel 8152: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 8153: my %this_domain;
8154: foreach my $field ('description', 'auth_def', 'auth_arg_def',
8155: 'lang_def', 'city', 'longi', 'lati',
8156: 'primary') {
8157: $this_domain{$field} = shift(@elements);
8158: }
8159: $domain{$name} = \%this_domain;
1.852 albertel 8160: }
8161: }
1.864 albertel 8162:
8163: sub reset_domain_info {
8164: undef($loaded);
8165: undef(%domain);
8166: }
8167:
1.852 albertel 8168: sub load_domain_tab {
1.869 albertel 8169: my ($ignore_cache) = @_;
8170: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 8171: my $fh;
8172: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
8173: my @lines = <$fh>;
8174: &parse_domain_tab(\@lines);
1.448 albertel 8175: }
1.852 albertel 8176: close($fh);
8177: $loaded = 1;
1.327 albertel 8178: }
1.846 albertel 8179:
8180: sub domain {
1.852 albertel 8181: &load_domain_tab() if (!$loaded);
8182:
1.846 albertel 8183: my ($name,$what) = @_;
8184: return if ( !exists($domain{$name}) );
8185:
8186: if (!$what) {
8187: return $domain{$name}{'description'};
8188: }
8189: return $domain{$name}{$what};
8190: }
1.327 albertel 8191: }
8192:
8193:
1.1 albertel 8194: # ------------------------------------------------------------- Read hosts file
8195: {
1.838 albertel 8196: my %hostname;
1.844 albertel 8197: my %hostdom;
1.845 albertel 8198: my %libserv;
1.852 albertel 8199: my $loaded;
1.888 albertel 8200: my %name_to_host;
1.852 albertel 8201:
8202: sub parse_hosts_tab {
8203: my ($file) = @_;
8204: foreach my $configline (@$file) {
8205: next if ($configline =~ /^(\#|\s*$ )/x);
8206: next if ($configline =~ /^\^/);
8207: chomp($configline);
8208: my ($id,$domain,$role,$name)=split(/:/,$configline);
8209: $name=~s/\s//g;
8210: if ($id && $domain && $role && $name) {
8211: $hostname{$id}=$name;
1.888 albertel 8212: push(@{$name_to_host{$name}}, $id);
1.852 albertel 8213: $hostdom{$id}=$domain;
8214: if ($role eq 'library') { $libserv{$id}=$name; }
8215: }
8216: }
8217: }
1.864 albertel 8218:
8219: sub reset_hosts_info {
1.897 albertel 8220: &purge_remembered();
1.864 albertel 8221: &reset_domain_info();
8222: &reset_hosts_ip_info();
1.892 albertel 8223: undef(%name_to_host);
1.864 albertel 8224: undef(%hostname);
8225: undef(%hostdom);
8226: undef(%libserv);
8227: undef($loaded);
8228: }
1.1 albertel 8229:
1.852 albertel 8230: sub load_hosts_tab {
1.869 albertel 8231: my ($ignore_cache) = @_;
8232: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 8233: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8234: my @config = <$config>;
8235: &parse_hosts_tab(\@config);
8236: close($config);
8237: $loaded=1;
1.1 albertel 8238: }
1.852 albertel 8239:
1.838 albertel 8240: sub hostname {
1.852 albertel 8241: &load_hosts_tab() if (!$loaded);
8242:
1.838 albertel 8243: my ($lonid) = @_;
8244: return $hostname{$lonid};
8245: }
1.845 albertel 8246:
1.838 albertel 8247: sub all_hostnames {
1.852 albertel 8248: &load_hosts_tab() if (!$loaded);
8249:
1.838 albertel 8250: return %hostname;
8251: }
1.845 albertel 8252:
1.888 albertel 8253: sub all_names {
8254: &load_hosts_tab() if (!$loaded);
8255:
8256: return %name_to_host;
8257: }
8258:
1.845 albertel 8259: sub is_library {
1.852 albertel 8260: &load_hosts_tab() if (!$loaded);
8261:
1.845 albertel 8262: return exists($libserv{$_[0]});
8263: }
8264:
8265: sub all_library {
1.852 albertel 8266: &load_hosts_tab() if (!$loaded);
8267:
1.845 albertel 8268: return %libserv;
8269: }
8270:
1.841 albertel 8271: sub get_servers {
1.852 albertel 8272: &load_hosts_tab() if (!$loaded);
8273:
1.841 albertel 8274: my ($domain,$type) = @_;
8275: my %possible_hosts = ($type eq 'library') ? %libserv
8276: : %hostname;
8277: my %result;
1.842 albertel 8278: if (ref($domain) eq 'ARRAY') {
8279: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 8280: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 8281: $result{$host} = $hostname;
8282: }
8283: }
8284: } else {
8285: while ( my ($host,$hostname) = each(%possible_hosts)) {
8286: if ($hostdom{$host} eq $domain) {
8287: $result{$host} = $hostname;
8288: }
1.841 albertel 8289: }
8290: }
8291: return %result;
8292: }
1.845 albertel 8293:
1.844 albertel 8294: sub host_domain {
1.852 albertel 8295: &load_hosts_tab() if (!$loaded);
8296:
1.844 albertel 8297: my ($lonid) = @_;
8298: return $hostdom{$lonid};
8299: }
8300:
1.841 albertel 8301: sub all_domains {
1.852 albertel 8302: &load_hosts_tab() if (!$loaded);
8303:
1.841 albertel 8304: my %seen;
8305: my @uniq = grep(!$seen{$_}++, values(%hostdom));
8306: return @uniq;
8307: }
1.1 albertel 8308: }
8309:
1.847 albertel 8310: {
8311: my %iphost;
1.856 albertel 8312: my %name_to_ip;
8313: my %lonid_to_ip;
1.869 albertel 8314:
1.847 albertel 8315: sub get_hosts_from_ip {
8316: my ($ip) = @_;
8317: my %iphosts = &get_iphost();
8318: if (ref($iphosts{$ip})) {
8319: return @{$iphosts{$ip}};
8320: }
8321: return;
1.839 albertel 8322: }
1.864 albertel 8323:
8324: sub reset_hosts_ip_info {
8325: undef(%iphost);
8326: undef(%name_to_ip);
8327: undef(%lonid_to_ip);
8328: }
1.856 albertel 8329:
8330: sub get_host_ip {
8331: my ($lonid) = @_;
8332: if (exists($lonid_to_ip{$lonid})) {
8333: return $lonid_to_ip{$lonid};
8334: }
8335: my $name=&hostname($lonid);
8336: my $ip = gethostbyname($name);
8337: return if (!$ip || length($ip) ne 4);
8338: $ip=inet_ntoa($ip);
8339: $name_to_ip{$name} = $ip;
8340: $lonid_to_ip{$lonid} = $ip;
8341: return $ip;
8342: }
1.847 albertel 8343:
8344: sub get_iphost {
1.869 albertel 8345: my ($ignore_cache) = @_;
1.894 albertel 8346:
1.869 albertel 8347: if (!$ignore_cache) {
8348: if (%iphost) {
8349: return %iphost;
8350: }
8351: my ($ip_info,$cached)=
8352: &Apache::lonnet::is_cached_new('iphost','iphost');
8353: if ($cached) {
8354: %iphost = %{$ip_info->[0]};
8355: %name_to_ip = %{$ip_info->[1]};
8356: %lonid_to_ip = %{$ip_info->[2]};
8357: return %iphost;
8358: }
8359: }
1.894 albertel 8360:
8361: # get yesterday's info for fallback
8362: my %old_name_to_ip;
8363: my ($ip_info,$cached)=
8364: &Apache::lonnet::is_cached_new('iphost','iphost');
8365: if ($cached) {
8366: %old_name_to_ip = %{$ip_info->[1]};
8367: }
8368:
1.888 albertel 8369: my %name_to_host = &all_names();
8370: foreach my $name (keys(%name_to_host)) {
1.847 albertel 8371: my $ip;
8372: if (!exists($name_to_ip{$name})) {
8373: $ip = gethostbyname($name);
8374: if (!$ip || length($ip) ne 4) {
1.894 albertel 8375: if (defined($old_name_to_ip{$name})) {
8376: $ip = $old_name_to_ip{$name};
8377: &logthis("Can't find $name defaulting to old $ip");
8378: } else {
8379: &logthis("Name $name no IP found");
8380: next;
8381: }
8382: } else {
8383: $ip=inet_ntoa($ip);
1.847 albertel 8384: }
8385: $name_to_ip{$name} = $ip;
8386: } else {
8387: $ip = $name_to_ip{$name};
1.653 albertel 8388: }
1.888 albertel 8389: foreach my $id (@{ $name_to_host{$name} }) {
8390: $lonid_to_ip{$id} = $ip;
8391: }
8392: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 8393: }
1.869 albertel 8394: &Apache::lonnet::do_cache_new('iphost','iphost',
8395: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 8396: 48*60*60);
1.869 albertel 8397:
1.847 albertel 8398: return %iphost;
1.598 albertel 8399: }
8400: }
8401:
1.862 albertel 8402: BEGIN {
8403:
8404: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
8405: unless ($readit) {
8406: {
8407: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
8408: %perlvar = (%perlvar,%{$configvars});
8409: }
8410:
8411:
1.1 albertel 8412: # ------------------------------------------------------ Read spare server file
8413: {
1.448 albertel 8414: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 8415:
8416: while (my $configline=<$config>) {
8417: chomp($configline);
1.284 matthew 8418: if ($configline) {
1.784 albertel 8419: my ($host,$type) = split(':',$configline,2);
1.785 albertel 8420: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 8421: push(@{ $spareid{$type} }, $host);
1.1 albertel 8422: }
8423: }
1.448 albertel 8424: close($config);
1.1 albertel 8425: }
1.11 www 8426: # ------------------------------------------------------------ Read permissions
8427: {
1.448 albertel 8428: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 8429:
8430: while (my $configline=<$config>) {
1.448 albertel 8431: chomp($configline);
8432: if ($configline) {
8433: my ($role,$perm)=split(/ /,$configline);
8434: if ($perm ne '') { $pr{$role}=$perm; }
8435: }
1.11 www 8436: }
1.448 albertel 8437: close($config);
1.11 www 8438: }
8439:
8440: # -------------------------------------------- Read plain texts for permissions
8441: {
1.448 albertel 8442: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 8443:
8444: while (my $configline=<$config>) {
1.448 albertel 8445: chomp($configline);
8446: if ($configline) {
1.742 raeburn 8447: my ($short,@plain)=split(/:/,$configline);
8448: %{$prp{$short}} = ();
8449: if (@plain > 0) {
8450: $prp{$short}{'std'} = $plain[0];
8451: for (my $i=1; $i<@plain; $i++) {
8452: $prp{$short}{'alt'.$i} = $plain[$i];
8453: }
8454: }
1.448 albertel 8455: }
1.135 www 8456: }
1.448 albertel 8457: close($config);
1.135 www 8458: }
8459:
8460: # ---------------------------------------------------------- Read package table
8461: {
1.448 albertel 8462: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 8463:
8464: while (my $configline=<$config>) {
1.483 albertel 8465: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 8466: chomp($configline);
8467: my ($short,$plain)=split(/:/,$configline);
8468: my ($pack,$name)=split(/\&/,$short);
8469: if ($plain ne '') {
8470: $packagetab{$pack.'&'.$name.'&name'}=$name;
8471: $packagetab{$short}=$plain;
8472: }
1.11 www 8473: }
1.448 albertel 8474: close($config);
1.329 matthew 8475: }
8476:
8477: # ------------- set up temporary directory
8478: {
8479: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
8480:
1.11 www 8481: }
8482:
1.794 albertel 8483: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
8484: 'compress_threshold'=> 20_000,
8485: });
1.185 www 8486:
1.281 www 8487: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 8488: $dumpcount=0;
1.22 www 8489:
1.163 harris41 8490: &logtouch();
1.672 albertel 8491: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 8492: $readit=1;
1.564 albertel 8493: {
8494: use integer;
8495: my $test=(2**32)+1;
1.568 albertel 8496: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 8497: &logthis(" Detected 64bit platform ($_64bit)");
8498: }
1.195 www 8499: }
1.1 albertel 8500: }
1.179 www 8501:
1.1 albertel 8502: 1;
1.191 harris41 8503: __END__
8504:
1.243 albertel 8505: =pod
8506:
1.191 harris41 8507: =head1 NAME
8508:
1.243 albertel 8509: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 8510:
8511: =head1 SYNOPSIS
8512:
1.243 albertel 8513: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 8514:
8515: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
8516:
1.243 albertel 8517: Common parameters:
8518:
8519: =over 4
8520:
8521: =item *
8522:
8523: $uname : an internal username (if $cname expecting a course Id specifically)
8524:
8525: =item *
8526:
8527: $udom : a domain (if $cdom expecting a course's domain specifically)
8528:
8529: =item *
8530:
8531: $symb : a resource instance identifier
8532:
8533: =item *
8534:
8535: $namespace : the name of a .db file that contains the data needed or
8536: being set.
8537:
8538: =back
8539:
1.394 bowersj2 8540: =head1 OVERVIEW
1.191 harris41 8541:
1.394 bowersj2 8542: lonnet provides subroutines which interact with the
8543: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
8544: about classes, users, and resources.
1.243 albertel 8545:
8546: For many of these objects you can also use this to store data about
8547: them or modify them in various ways.
1.191 harris41 8548:
1.394 bowersj2 8549: =head2 Symbs
1.191 harris41 8550:
1.394 bowersj2 8551: To identify a specific instance of a resource, LON-CAPA uses symbols
8552: or "symbs"X<symb>. These identifiers are built from the URL of the
8553: map, the resource number of the resource in the map, and the URL of
8554: the resource itself. The latter is somewhat redundant, but might help
8555: if maps change.
8556:
8557: An example is
8558:
8559: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
8560:
8561: The respective map entry is
8562:
8563: <resource id="19" src="/res/msu/korte/tests/part12.problem"
8564: title="Problem 2">
8565: </resource>
8566:
8567: Symbs are used by the random number generator, as well as to store and
8568: restore data specific to a certain instance of for example a problem.
8569:
8570: =head2 Storing And Retrieving Data
8571:
8572: X<store()>X<cstore()>X<restore()>Three of the most important functions
8573: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
8574: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
8575: is is the non-critical message twin of cstore. These functions are for
8576: handlers to store a perl hash to a user's permanent data space in an
8577: easy manner, and to retrieve it again on another call. It is expected
8578: that a handler would use this once at the beginning to retrieve data,
8579: and then again once at the end to send only the new data back.
8580:
8581: The data is stored in the user's data directory on the user's
8582: homeserver under the ID of the course.
8583:
8584: The hash that is returned by restore will have all of the previous
8585: value for all of the elements of the hash.
8586:
8587: Example:
8588:
8589: #creating a hash
8590: my %hash;
8591: $hash{'foo'}='bar';
8592:
8593: #storing it
8594: &Apache::lonnet::cstore(\%hash);
8595:
8596: #changing a value
8597: $hash{'foo'}='notbar';
8598:
8599: #adding a new value
8600: $hash{'bar'}='foo';
8601: &Apache::lonnet::cstore(\%hash);
8602:
8603: #retrieving the hash
8604: my %history=&Apache::lonnet::restore();
8605:
8606: #print the hash
8607: foreach my $key (sort(keys(%history))) {
8608: print("\%history{$key} = $history{$key}");
8609: }
8610:
8611: Will print out:
1.191 harris41 8612:
1.394 bowersj2 8613: %history{1:foo} = bar
8614: %history{1:keys} = foo:timestamp
8615: %history{1:timestamp} = 990455579
8616: %history{2:bar} = foo
8617: %history{2:foo} = notbar
8618: %history{2:keys} = foo:bar:timestamp
8619: %history{2:timestamp} = 990455580
8620: %history{bar} = foo
8621: %history{foo} = notbar
8622: %history{timestamp} = 990455580
8623: %history{version} = 2
8624:
8625: Note that the special hash entries C<keys>, C<version> and
8626: C<timestamp> were added to the hash. C<version> will be equal to the
8627: total number of versions of the data that have been stored. The
8628: C<timestamp> attribute will be the UNIX time the hash was
8629: stored. C<keys> is available in every historical section to list which
8630: keys were added or changed at a specific historical revision of a
8631: hash.
8632:
8633: B<Warning>: do not store the hash that restore returns directly. This
8634: will cause a mess since it will restore the historical keys as if the
8635: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 8636:
1.394 bowersj2 8637: Calling convention:
1.191 harris41 8638:
1.394 bowersj2 8639: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
8640: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 8641:
1.394 bowersj2 8642: For more detailed information, see lonnet specific documentation.
1.191 harris41 8643:
1.394 bowersj2 8644: =head1 RETURN MESSAGES
1.191 harris41 8645:
1.394 bowersj2 8646: =over 4
1.191 harris41 8647:
1.394 bowersj2 8648: =item * B<con_lost>: unable to contact remote host
1.191 harris41 8649:
1.394 bowersj2 8650: =item * B<con_delayed>: unable to contact remote host, message will be delivered
8651: when the connection is brought back up
1.191 harris41 8652:
1.394 bowersj2 8653: =item * B<con_failed>: unable to contact remote host and unable to save message
8654: for later delivery
1.191 harris41 8655:
1.394 bowersj2 8656: =item * B<error:>: an error a occured, a description of the error follows the :
1.191 harris41 8657:
1.394 bowersj2 8658: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 8659: that was requested
1.191 harris41 8660:
1.243 albertel 8661: =back
1.191 harris41 8662:
1.243 albertel 8663: =head1 PUBLIC SUBROUTINES
1.191 harris41 8664:
1.243 albertel 8665: =head2 Session Environment Functions
1.191 harris41 8666:
1.243 albertel 8667: =over 4
1.191 harris41 8668:
1.394 bowersj2 8669: =item *
8670: X<appenv()>
8671: B<appenv(%hash)>: the value of %hash is written to
8672: the user envirnoment file, and will be restored for each access this
1.620 albertel 8673: user makes during this session, also modifies the %env for the current
1.394 bowersj2 8674: process
1.191 harris41 8675:
8676: =item *
1.394 bowersj2 8677: X<delenv()>
8678: B<delenv($regexp)>: removes all items from the session
8679: environment file that matches the regular expression in $regexp. The
1.620 albertel 8680: values are also delted from the current processes %env.
1.191 harris41 8681:
1.795 albertel 8682: =item * get_env_multiple($name)
8683:
8684: gets $name from the %env hash, it seemlessly handles the cases where multiple
8685: values may be defined and end up as an array ref.
8686:
8687: returns an array of values
8688:
1.243 albertel 8689: =back
8690:
8691: =head2 User Information
1.191 harris41 8692:
1.243 albertel 8693: =over 4
1.191 harris41 8694:
8695: =item *
1.394 bowersj2 8696: X<queryauthenticate()>
8697: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 8698: authentication scheme
8699:
8700: =item *
1.394 bowersj2 8701: X<authenticate()>
8702: B<authenticate($uname,$upass,$udom)>: try to
8703: authenticate user from domain's lib servers (first use the current
8704: one). C<$upass> should be the users password.
1.191 harris41 8705:
8706: =item *
1.394 bowersj2 8707: X<homeserver()>
8708: B<homeserver($uname,$udom)>: find the server which has
8709: the user's directory and files (there must be only one), this caches
8710: the answer, and also caches if there is a borken connection.
1.191 harris41 8711:
8712: =item *
1.394 bowersj2 8713: X<idget()>
8714: B<idget($udom,@ids)>: find the usernames behind a list of IDs
8715: (IDs are a unique resource in a domain, there must be only 1 ID per
8716: username, and only 1 username per ID in a specific domain) (returns
8717: hash: id=>name,id=>name)
1.191 harris41 8718:
8719: =item *
1.394 bowersj2 8720: X<idrget()>
8721: B<idrget($udom,@unames)>: find the IDs behind a list of
8722: usernames (returns hash: name=>id,name=>id)
1.191 harris41 8723:
8724: =item *
1.394 bowersj2 8725: X<idput()>
8726: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 8727:
8728: =item *
1.394 bowersj2 8729: X<rolesinit()>
8730: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 8731:
8732: =item *
1.551 albertel 8733: X<getsection()>
8734: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 8735: course $cname, return section name/number or '' for "not in course"
8736: and '-1' for "no section"
8737:
8738: =item *
1.394 bowersj2 8739: X<userenvironment()>
8740: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 8741: passed in @what from the requested user's environment, returns a hash
8742:
1.858 raeburn 8743: =item *
8744: X<userlog_query()>
1.859 albertel 8745: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
8746: activity.log file. %filters defines filters applied when parsing the
8747: log file. These can be start or end timestamps, or the type of action
8748: - log to look for Login or Logout events, check for Checkin or
8749: Checkout, role for role selection. The response is in the form
8750: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
8751: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 8752:
1.243 albertel 8753: =back
8754:
8755: =head2 User Roles
8756:
8757: =over 4
8758:
8759: =item *
8760:
1.810 raeburn 8761: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 8762: F: full access
8763: U,I,K: authentication modes (cxx only)
8764: '': forbidden
8765: 1: user needs to choose course
8766: 2: browse allowed
1.766 albertel 8767: A: passphrase authentication needed
1.243 albertel 8768:
8769: =item *
8770:
8771: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
8772: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
8773: and course level
8774:
8775: =item *
8776:
8777: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
8778: explanation of a user role term
8779:
1.832 raeburn 8780: =item *
8781:
1.858 raeburn 8782: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
8783: All arguments are optional. Returns a hash of a roles, either for
8784: co-author/assistant author roles for a user's Construction Space
1.906 albertel 8785: (default), or if $context is 'userroles', roles for the user himself,
1.858 raeburn 8786: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
8787: and value is set to colon-separated start and end times for the role.
8788: If no username and domain are specified, will default to current
8789: user/domain. Types, roles, and roledoms are references to arrays,
8790: of role statuses (active, future or previous), roles
8791: (e.g., cc,in, st etc.) and domains of the roles which can be used
8792: to restrict the list of roles reported. If no array ref is
8793: provided for types, will default to return only active roles.
1.834 albertel 8794:
1.243 albertel 8795: =back
8796:
8797: =head2 User Modification
8798:
8799: =over 4
8800:
8801: =item *
8802:
8803: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
8804: user for the level given by URL. Optional start and end dates (leave empty
8805: string or zero for "no date")
1.191 harris41 8806:
8807: =item *
8808:
1.243 albertel 8809: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
8810: change a users, password, possible return values are: ok,
8811: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
8812: refused
1.191 harris41 8813:
8814: =item *
8815:
1.243 albertel 8816: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 8817:
8818: =item *
8819:
1.243 albertel 8820: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
8821: modify user
1.191 harris41 8822:
8823: =item *
8824:
1.286 matthew 8825: modifystudent
8826:
8827: modify a students enrollment and identification information.
8828: The course id is resolved based on the current users environment.
8829: This means the envoking user must be a course coordinator or otherwise
8830: associated with a course.
8831:
1.297 matthew 8832: This call is essentially a wrapper for lonnet::modifyuser and
8833: lonnet::modify_student_enrollment
1.286 matthew 8834:
8835: Inputs:
8836:
8837: =over 4
8838:
8839: =item B<$udom> Students loncapa domain
8840:
8841: =item B<$uname> Students loncapa login name
8842:
8843: =item B<$uid> Students id/student number
8844:
8845: =item B<$umode> Students authentication mode
8846:
8847: =item B<$upass> Students password
8848:
8849: =item B<$first> Students first name
8850:
8851: =item B<$middle> Students middle name
8852:
8853: =item B<$last> Students last name
8854:
8855: =item B<$gene> Students generation
8856:
8857: =item B<$usec> Students section in course
8858:
8859: =item B<$end> Unix time of the roles expiration
8860:
8861: =item B<$start> Unix time of the roles start date
8862:
8863: =item B<$forceid> If defined, allow $uid to be changed
8864:
8865: =item B<$desiredhome> server to use as home server for student
8866:
8867: =back
1.297 matthew 8868:
8869: =item *
8870:
8871: modify_student_enrollment
8872:
8873: Change a students enrollment status in a class. The environment variable
8874: 'role.request.course' must be defined for this function to proceed.
8875:
8876: Inputs:
8877:
8878: =over 4
8879:
8880: =item $udom, students domain
8881:
8882: =item $uname, students name
8883:
8884: =item $uid, students user id
8885:
8886: =item $first, students first name
8887:
8888: =item $middle
8889:
8890: =item $last
8891:
8892: =item $gene
8893:
8894: =item $usec
8895:
8896: =item $end
8897:
8898: =item $start
8899:
8900: =back
8901:
1.191 harris41 8902:
8903: =item *
8904:
1.243 albertel 8905: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
8906: custom role; give a custom role to a user for the level given by URL. Specify
8907: name and domain of role author, and role name
1.191 harris41 8908:
8909: =item *
8910:
1.243 albertel 8911: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 8912:
8913: =item *
8914:
1.243 albertel 8915: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
8916:
8917: =back
8918:
8919: =head2 Course Infomation
8920:
8921: =over 4
1.191 harris41 8922:
8923: =item *
8924:
1.631 albertel 8925: coursedescription($courseid) : returns a hash of information about the
8926: specified course id, including all environment settings for the
8927: course, the description of the course will be in the hash under the
8928: key 'description'
1.191 harris41 8929:
8930: =item *
8931:
1.624 albertel 8932: resdata($name,$domain,$type,@which) : request for current parameter
8933: setting for a specific $type, where $type is either 'course' or 'user',
8934: @what should be a list of parameters to ask about. This routine caches
8935: answers for 5 minutes.
1.243 albertel 8936:
1.877 foxr 8937: =item *
8938:
8939: get_courseresdata($courseid, $domain) : dump the entire course resource
8940: data base, returning a hash that is keyed by the resource name and has
8941: values that are the resource value. I believe that the timestamps and
8942: versions are also returned.
8943:
8944:
1.243 albertel 8945: =back
8946:
8947: =head2 Course Modification
8948:
8949: =over 4
1.191 harris41 8950:
8951: =item *
8952:
1.243 albertel 8953: writecoursepref($courseid,%prefs) : write preferences (environment
8954: database) for a course
1.191 harris41 8955:
8956: =item *
8957:
1.243 albertel 8958: createcourse($udom,$description,$url) : make/modify course
8959:
8960: =back
8961:
8962: =head2 Resource Subroutines
8963:
8964: =over 4
1.191 harris41 8965:
8966: =item *
8967:
1.243 albertel 8968: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 8969:
8970: =item *
8971:
1.243 albertel 8972: repcopy($filename) : subscribes to the requested file, and attempts to
8973: replicate from the owning library server, Might return
1.607 raeburn 8974: 'unavailable', 'not_found', 'forbidden', 'ok', or
8975: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 8976: resource. Expects the local filesystem pathname
8977: (/home/httpd/html/res/....)
8978:
8979: =back
8980:
8981: =head2 Resource Information
8982:
8983: =over 4
1.191 harris41 8984:
8985: =item *
8986:
1.243 albertel 8987: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
8988: a vairety of different possible values, $varname should be a request
8989: string, and the other parameters can be used to specify who and what
8990: one is asking about.
8991:
8992: Possible values for $varname are environment.lastname (or other item
8993: from the envirnment hash), user.name (or someother aspect about the
8994: user), resource.0.maxtries (or some other part and parameter of a
8995: resource)
1.204 albertel 8996:
8997: =item *
8998:
1.243 albertel 8999: directcondval($number) : get current value of a condition; reads from a state
9000: string
1.204 albertel 9001:
9002: =item *
9003:
1.243 albertel 9004: condval($condidx) : value of condition index based on state
1.204 albertel 9005:
9006: =item *
9007:
1.243 albertel 9008: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
9009: resource's metadata, $what should be either a specific key, or either
9010: 'keys' (to get a list of possible keys) or 'packages' to get a list of
9011: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
9012:
9013: this function automatically caches all requests
1.191 harris41 9014:
9015: =item *
9016:
1.243 albertel 9017: metadata_query($query,$custom,$customshow) : make a metadata query against the
9018: network of library servers; returns file handle of where SQL and regex results
9019: will be stored for query
1.191 harris41 9020:
9021: =item *
9022:
1.243 albertel 9023: symbread($filename) : return symbolic list entry (filename argument optional);
9024: returns the data handle
1.191 harris41 9025:
9026: =item *
9027:
1.243 albertel 9028: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 9029: a possible symb for the URL in $thisfn, and if is an encryypted
9030: resource that the user accessed using /enc/ returns a 1 on success, 0
9031: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 9032: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 9033:
1.191 harris41 9034:
9035: =item *
9036:
1.243 albertel 9037: symbclean($symb) : removes versions numbers from a symb, returns the
9038: cleaned symb
1.191 harris41 9039:
9040: =item *
9041:
1.243 albertel 9042: is_on_map($uri) : checks if the $uri is somewhere on the current
9043: course map, user must be in a course for it to work.
1.191 harris41 9044:
9045: =item *
9046:
1.243 albertel 9047: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 9048:
9049: =item *
9050:
1.243 albertel 9051: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
9052: a random seed, all arguments are optional, if they aren't sent it uses the
9053: environment to derive them. Note: if symb isn't sent and it can't get one
9054: from &symbread it will use the current time as its return value
1.191 harris41 9055:
9056: =item *
9057:
1.243 albertel 9058: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
9059: unfakeable, receipt
1.191 harris41 9060:
9061: =item *
9062:
1.620 albertel 9063: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 9064:
9065: =item *
9066:
1.243 albertel 9067: countacc($url) : count the number of accesses to a given URL
1.191 harris41 9068:
9069: =item *
9070:
1.243 albertel 9071: 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 9072:
9073: =item *
9074:
1.243 albertel 9075: 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 9076:
9077: =item *
9078:
1.243 albertel 9079: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 9080:
9081: =item *
9082:
1.243 albertel 9083: devalidate($symb) : devalidate temporary spreadsheet calculations,
9084: forcing spreadsheet to reevaluate the resource scores next time.
9085:
9086: =back
9087:
9088: =head2 Storing/Retreiving Data
9089:
9090: =over 4
1.191 harris41 9091:
9092: =item *
9093:
1.243 albertel 9094: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
9095: for this url; hashref needs to be given and should be a \%hashname; the
9096: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 9097: be derived from the env
1.191 harris41 9098:
9099: =item *
9100:
1.243 albertel 9101: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
9102: uses critical subroutine
1.191 harris41 9103:
9104: =item *
9105:
1.243 albertel 9106: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
9107: all args are optional
1.191 harris41 9108:
9109: =item *
9110:
1.717 albertel 9111: dumpstore($namespace,$udom,$uname,$regexp,$range) :
9112: dumps the complete (or key matching regexp) namespace into a hash
9113: ($udom, $uname, $regexp, $range are optional) for a namespace that is
9114: normally &store()ed into
9115:
9116: $range should be either an integer '100' (give me the first 100
9117: matching records)
9118: or be two integers sperated by a - with no spaces
9119: '30-50' (give me the 30th through the 50th matching
9120: records)
9121:
9122:
9123: =item *
9124:
9125: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
9126: replaces a &store() version of data with a replacement set of data
9127: for a particular resource in a namespace passed in the $storehash hash
9128: reference
9129:
9130: =item *
9131:
1.243 albertel 9132: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
9133: works very similar to store/cstore, but all data is stored in a
9134: temporary location and can be reset using tmpreset, $storehash should
9135: be a hash reference, returns nothing on success
1.191 harris41 9136:
9137: =item *
9138:
1.243 albertel 9139: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
9140: similar to restore, but all data is stored in a temporary location and
9141: can be reset using tmpreset. Returns a hash of values on success,
9142: error string otherwise.
1.191 harris41 9143:
9144: =item *
9145:
1.243 albertel 9146: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
9147: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 9148:
9149: =item *
9150:
1.243 albertel 9151: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9152: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 9153:
9154: =item *
9155:
1.243 albertel 9156: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
9157: namesp ($udom and $uname are optional)
1.191 harris41 9158:
9159: =item *
9160:
1.702 albertel 9161: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 9162: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 9163: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 9164:
1.702 albertel 9165: $range should be either an integer '100' (give me the first 100
9166: matching records)
9167: or be two integers sperated by a - with no spaces
9168: '30-50' (give me the 30th through the 50th matching
9169: records)
1.449 matthew 9170: =item *
9171:
9172: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
9173: $store can be a scalar, an array reference, or if the amount to be
9174: incremented is > 1, a hash reference.
9175:
9176: ($udom and $uname are optional)
1.191 harris41 9177:
9178: =item *
9179:
1.243 albertel 9180: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
9181: ($udom and $uname are optional)
1.191 harris41 9182:
9183: =item *
9184:
1.243 albertel 9185: cput($namespace,$storehash,$udom,$uname) : critical put
9186: ($udom and $uname are optional)
1.191 harris41 9187:
9188: =item *
9189:
1.748 albertel 9190: newput($namespace,$storehash,$udom,$uname) :
9191:
9192: Attempts to store the items in the $storehash, but only if they don't
9193: currently exist, if this succeeds you can be certain that you have
9194: successfully created a new key value pair in the $namespace db.
9195:
9196:
9197: Args:
9198: $namespace: name of database to store values to
9199: $storehash: hashref to store to the db
9200: $udom: (optional) domain of user containing the db
9201: $uname: (optional) name of user caontaining the db
9202:
9203: Returns:
9204: 'ok' -> succeeded in storing all keys of $storehash
9205: 'key_exists: <key>' -> failed to anything out of $storehash, as at
9206: least <key> already existed in the db (other
9207: requested keys may also already exist)
9208: 'error: <msg>' -> unable to tie the DB or other erorr occured
9209: 'con_lost' -> unable to contact request server
9210: 'refused' -> action was not allowed by remote machine
9211:
9212:
9213: =item *
9214:
1.243 albertel 9215: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9216: reference filled in from namesp (encrypts the return communication)
9217: ($udom and $uname are optional)
1.191 harris41 9218:
9219: =item *
9220:
1.243 albertel 9221: log($udom,$name,$home,$message) : write to permanent log for user; use
9222: critical subroutine
9223:
1.806 raeburn 9224: =item *
9225:
1.860 raeburn 9226: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
9227: array reference filled in from namespace found in domain level on either
9228: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 9229:
9230: =item *
9231:
1.860 raeburn 9232: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
9233: domain level either on specified domain server ($uhome) or primary domain
9234: server ($udom and $uhome are optional)
1.806 raeburn 9235:
1.243 albertel 9236: =back
9237:
9238: =head2 Network Status Functions
9239:
9240: =over 4
1.191 harris41 9241:
9242: =item *
9243:
9244: dirlist($uri) : return directory list based on URI
9245:
9246: =item *
9247:
1.243 albertel 9248: spareserver() : find server with least workload from spare.tab
9249:
9250: =back
9251:
9252: =head2 Apache Request
9253:
9254: =over 4
1.191 harris41 9255:
9256: =item *
9257:
1.243 albertel 9258: ssi($url,%hash) : server side include, does a complete request cycle on url to
9259: localhost, posts hash
9260:
9261: =back
9262:
9263: =head2 Data to String to Data
9264:
9265: =over 4
1.191 harris41 9266:
9267: =item *
9268:
1.243 albertel 9269: hash2str(%hash) : convert a hash into a string complete with escaping and '='
9270: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 9271:
9272: =item *
9273:
1.243 albertel 9274: hashref2str($hashref) : convert a hashref into a string complete with
9275: escaping and '=' and '&' separators, supports elements that are
9276: arrayrefs and hashrefs
1.191 harris41 9277:
9278: =item *
9279:
1.243 albertel 9280: arrayref2str($arrayref) : convert an arrayref into a string complete
9281: with escaping and '&' separators, supports elements that are arrayrefs
9282: and hashrefs
1.191 harris41 9283:
9284: =item *
9285:
1.243 albertel 9286: str2hash($string) : convert string to hash using unescaping and
9287: splitting on '=' and '&', supports elements that are arrayrefs and
9288: hashrefs
1.191 harris41 9289:
9290: =item *
9291:
1.243 albertel 9292: str2array($string) : convert string to hash using unescaping and
9293: splitting on '&', supports elements that are arrayrefs and hashrefs
9294:
9295: =back
9296:
9297: =head2 Logging Routines
9298:
9299: =over 4
9300:
9301: These routines allow one to make log messages in the lonnet.log and
9302: lonnet.perm logfiles.
1.191 harris41 9303:
9304: =item *
9305:
1.243 albertel 9306: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 9307:
9308: =item *
9309:
1.243 albertel 9310: logthis() : append message to the normal lonnet.log file, it gets
9311: preiodically rolled over and deleted.
1.191 harris41 9312:
9313: =item *
9314:
1.243 albertel 9315: logperm() : append a permanent message to lonnet.perm.log, this log
9316: file never gets deleted by any automated portion of the system, only
9317: messages of critical importance should go in here.
9318:
9319: =back
9320:
9321: =head2 General File Helper Routines
9322:
9323: =over 4
1.191 harris41 9324:
9325: =item *
9326:
1.481 raeburn 9327: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
9328: (a) files in /uploaded
9329: (i) If a local copy of the file exists -
9330: compares modification date of local copy with last-modified date for
9331: definitive version stored on home server for course. If local copy is
9332: stale, requests a new version from the home server and stores it.
9333: If the original has been removed from the home server, then local copy
9334: is unlinked.
9335: (ii) If local copy does not exist -
9336: requests the file from the home server and stores it.
9337:
9338: If $caller is 'uploadrep':
9339: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
9340: for request for files originally uploaded via DOCS.
9341: - returns 'ok' if fresh local copy now available, -1 otherwise.
9342:
9343: Otherwise:
9344: This indicates a call from the content generation phase of the request.
9345: - returns the entire contents of the file or -1.
9346:
9347: (b) files in /res
9348: - returns the entire contents of a file or -1;
9349: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 9350:
1.712 albertel 9351:
9352: =item *
9353:
9354: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
9355: reference
9356:
9357: returns either a stat() list of data about the file or an empty list
9358: if the file doesn't exist or couldn't find out about it (connection
9359: problems or user unknown)
9360:
1.191 harris41 9361: =item *
9362:
1.243 albertel 9363: filelocation($dir,$file) : returns file system location of a file
9364: based on URI; meant to be "fairly clean" absolute reference, $dir is a
9365: directory that relative $file lookups are to looked in ($dir of /a/dir
9366: and a file of ../bob will become /a/bob)
1.191 harris41 9367:
9368: =item *
9369:
9370: hreflocation($dir,$file) : returns file system location or a URL; same as
9371: filelocation except for hrefs
9372:
9373: =item *
9374:
9375: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
9376:
1.243 albertel 9377: =back
9378:
1.608 albertel 9379: =head2 Usererfile file routines (/uploaded*)
9380:
9381: =over 4
9382:
9383: =item *
9384:
9385: userfileupload(): main rotine for putting a file in a user or course's
9386: filespace, arguments are,
9387:
1.620 albertel 9388: formname - required - this is the name of the element in $env where the
1.608 albertel 9389: filename, and the contents of the file to create/modifed exist
1.620 albertel 9390: the filename is in $env{'form.'.$formname.'.filename'} and the
9391: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 9392: coursedoc - if true, store the file in the course of the active role
9393: of the current user
9394: subdir - required - subdirectory to put the file in under ../userfiles/
9395: if undefined, it will be placed in "unknown"
9396:
9397: (This routine calls clean_filename() to remove any dangerous
9398: characters from the filename, and then calls finuserfileupload() to
9399: complete the transaction)
9400:
9401: returns either the url of the uploaded file (/uploaded/....) if successful
9402: and /adm/notfound.html if unsuccessful
9403:
9404: =item *
9405:
9406: clean_filename(): routine for cleaing a filename up for storage in
9407: userfile space, argument is:
9408:
9409: filename - proposed filename
9410:
9411: returns: the new clean filename
9412:
9413: =item *
9414:
9415: finishuserfileupload(): routine that creaes and sends the file to
9416: userspace, probably shouldn't be called directly
9417:
9418: docuname: username or courseid of destination for the file
9419: docudom: domain of user/course of destination for the file
9420: formname: same as for userfileupload()
9421: fname: filename (inculding subdirectories) for the file
9422:
9423: returns either the url of the uploaded file (/uploaded/....) if successful
9424: and /adm/notfound.html if unsuccessful
9425:
9426: =item *
9427:
9428: renameuserfile(): renames an existing userfile to a new name
9429:
9430: Args:
9431: docuname: username or courseid of destination for the file
9432: docudom: domain of user/course of destination for the file
9433: old: current file name (including any subdirs under userfiles)
9434: new: desired file name (including any subdirs under userfiles)
9435:
9436: =item *
9437:
9438: mkdiruserfile(): creates a directory is a userfiles dir
9439:
9440: Args:
9441: docuname: username or courseid of destination for the file
9442: docudom: domain of user/course of destination for the file
9443: dir: dir to create (including any subdirs under userfiles)
9444:
9445: =item *
9446:
9447: removeuserfile(): removes a file that exists in userfiles
9448:
9449: Args:
9450: docuname: username or courseid of destination for the file
9451: docudom: domain of user/course of destination for the file
9452: fname: filname to delete (including any subdirs under userfiles)
9453:
9454: =item *
9455:
9456: removeuploadedurl(): convience function for removeuserfile()
9457:
9458: Args:
9459: url: a full /uploaded/... url to delete
9460:
1.747 albertel 9461: =item *
9462:
9463: get_portfile_permissions():
9464: Args:
9465: domain: domain of user or course contain the portfolio files
9466: user: name of user or num of course contain the portfolio files
9467: Returns:
9468: hashref of a dump of the proper file_permissions.db
9469:
9470:
9471: =item *
9472:
9473: get_access_controls():
9474:
9475: Args:
9476: current_permissions: the hash ref returned from get_portfile_permissions()
9477: group: (optional) the group you want the files associated with
9478: file: (optional) the file you want access info on
9479:
9480: Returns:
1.749 raeburn 9481: a hash (keys are file names) of hashes containing
9482: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
9483: values are XML containing access control settings (see below)
1.747 albertel 9484:
9485: Internal notes:
9486:
1.749 raeburn 9487: access controls are stored in file_permissions.db as key=value pairs.
9488: key -> path to file/file_name\0uniqueID:scope_end_start
9489: where scope -> public,guest,course,group,domains or users.
9490: end -> UNIX time for end of access (0 -> no end date)
9491: start -> UNIX time for start of access
9492:
9493: value -> XML description of access control
9494: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
9495: <start></start>
9496: <end></end>
9497:
9498: <password></password> for scope type = guest
9499:
9500: <domain></domain> for scope type = course or group
9501: <number></number>
9502: <roles id="">
9503: <role></role>
9504: <access></access>
9505: <section></section>
9506: <group></group>
9507: </roles>
9508:
9509: <dom></dom> for scope type = domains
9510:
9511: <users> for scope type = users
9512: <user>
9513: <uname></uname>
9514: <udom></udom>
9515: </user>
9516: </users>
9517: </scope>
9518:
9519: Access data is also aggregated for each file in an additional key=value pair:
9520: key -> path to file/file_name\0accesscontrol
9521: value -> reference to hash
9522: hash contains key = value pairs
9523: where key = uniqueID:scope_end_start
9524: value = UNIX time record was last updated
9525:
9526: Used to improve speed of look-ups of access controls for each file.
9527:
9528: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
9529:
9530: modify_access_controls():
9531:
9532: Modifies access controls for a portfolio file
9533: Args
9534: 1. file name
9535: 2. reference to hash of required changes,
9536: 3. domain
9537: 4. username
9538: where domain,username are the domain of the portfolio owner
9539: (either a user or a course)
9540:
9541: Returns:
9542: 1. result of additions or updates ('ok' or 'error', with error message).
9543: 2. result of deletions ('ok' or 'error', with error message).
9544: 3. reference to hash of any new or updated access controls.
9545: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
9546: key = integer (inbound ID)
9547: value = uniqueID
1.747 albertel 9548:
1.608 albertel 9549: =back
9550:
1.243 albertel 9551: =head2 HTTP Helper Routines
9552:
9553: =over 4
9554:
1.191 harris41 9555: =item *
9556:
9557: escape() : unpack non-word characters into CGI-compatible hex codes
9558:
9559: =item *
9560:
9561: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
9562:
1.243 albertel 9563: =back
9564:
9565: =head1 PRIVATE SUBROUTINES
9566:
9567: =head2 Underlying communication routines (Shouldn't call)
9568:
9569: =over 4
9570:
9571: =item *
9572:
9573: subreply() : tries to pass a message to lonc, returns con_lost if incapable
9574:
9575: =item *
9576:
9577: reply() : uses subreply to send a message to remote machine, logs all failures
9578:
9579: =item *
9580:
9581: critical() : passes a critical message to another server; if cannot
9582: get through then place message in connection buffer directory and
9583: returns con_delayed, if incapable of saving message, returns
9584: con_failed
9585:
9586: =item *
9587:
9588: reconlonc() : tries to reconnect lonc client processes.
9589:
9590: =back
9591:
9592: =head2 Resource Access Logging
9593:
9594: =over 4
9595:
9596: =item *
9597:
9598: flushcourselogs() : flush (save) buffer logs and access logs
9599:
9600: =item *
9601:
9602: courselog($what) : save message for course in hash
9603:
9604: =item *
9605:
9606: courseacclog($what) : save message for course using &courselog(). Perform
9607: special processing for specific resource types (problems, exams, quizzes, etc).
9608:
1.191 harris41 9609: =item *
9610:
9611: goodbye() : flush course logs and log shutting down; it is called in srm.conf
9612: as a PerlChildExitHandler
1.243 albertel 9613:
9614: =back
9615:
9616: =head2 Other
9617:
9618: =over 4
9619:
9620: =item *
9621:
9622: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 9623:
9624: =back
9625:
9626: =cut
1.877 foxr 9627:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>