Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.962
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.962 ! raeburn 4: # $Id: lonnet.pm,v 1.961 2008/06/09 22:35:00 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.1 albertel 30: package Apache::lonnet;
31:
32: use strict;
1.8 www 33: use LWP::UserAgent();
1.486 www 34: use HTTP::Date;
35: # use Date::Parse;
1.871 albertel 36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
37: $_64bit %env);
38:
39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
40: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
41: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 42: %courseownerbuf, %coursetypebuf,$locknum);
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 {
1.957 raeburn 91: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
92: if (($cnum eq '') || ($cdom eq '')) {
93: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
94: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
95: }
1.729 www 96: $logid++;
1.957 raeburn 97: my $now = time();
98: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 99: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 100: { $id => {
101: 'exe_uname' => $env{'user.name'},
102: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 103: 'exe_time' => $now,
1.730 www 104: 'exe_ip' => $ENV{'REMOTE_ADDR'},
105: 'delflag' => $delflag,
106: 'logentry' => $storehash,
107: 'uname' => $uname,
108: 'udom' => $udom,
109: }
1.957 raeburn 110: },$cdom,$cnum);
1.729 www 111: }
112: }
1.1 albertel 113:
1.163 harris41 114: sub logtouch {
115: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 116: unless (-e "$execdir/logs/lonnet.log") {
117: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 118: close $fh;
119: }
120: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
121: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
122: }
123:
1.1 albertel 124: sub logthis {
125: my $message=shift;
126: my $execdir=$perlvar{'lonDaemons'};
127: my $now=time;
128: my $local=localtime($now);
1.448 albertel 129: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
130: print $fh "$local ($$): $message\n";
131: close($fh);
132: }
1.1 albertel 133: return 1;
134: }
135:
136: sub logperm {
137: my $message=shift;
138: my $execdir=$perlvar{'lonDaemons'};
139: my $now=time;
140: my $local=localtime($now);
1.448 albertel 141: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
142: print $fh "$now:$message:$local\n";
143: close($fh);
144: }
1.1 albertel 145: return 1;
146: }
147:
1.850 albertel 148: sub create_connection {
1.853 albertel 149: my ($hostname,$lonid) = @_;
1.851 albertel 150: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 151: Type => SOCK_STREAM,
152: Timeout => 10);
153: return 0 if (!$client);
1.890 albertel 154: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 155: my $result = <$client>;
156: chomp($result);
157: return 1 if ($result eq 'done');
158: return 0;
159: }
160:
161:
1.1 albertel 162: # -------------------------------------------------- Non-critical communication
163: sub subreply {
164: my ($cmd,$server)=@_;
1.838 albertel 165: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 166: #
167: # With loncnew process trimming, there's a timing hole between lonc server
168: # process exit and the master server picking up the listen on the AF_UNIX
169: # socket. In that time interval, a lock file will exist:
170:
171: my $lockfile=$peerfile.".lock";
172: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
173: sleep(1);
174: }
175: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 176: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 177: #
1.550 foxr 178: # We'll give the connection a few tries before abandoning it. If
179: # connection is not possible, we'll con_lost back to the client.
180: #
181: my $client;
182: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
183: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
184: Type => SOCK_STREAM,
185: Timeout => 10);
1.869 albertel 186: if ($client) {
1.550 foxr 187: last; # Connected!
1.850 albertel 188: } else {
1.853 albertel 189: &create_connection(&hostname($server),$server);
1.550 foxr 190: }
1.850 albertel 191: sleep(1); # Try again later if failed connection.
1.550 foxr 192: }
193: my $answer;
194: if ($client) {
1.704 albertel 195: print $client "sethost:$server:$cmd\n";
1.550 foxr 196: $answer=<$client>;
197: if (!$answer) { $answer="con_lost"; }
198: chomp($answer);
199: } else {
200: $answer = 'con_lost'; # Failed connection.
201: }
1.1 albertel 202: return $answer;
203: }
204:
205: sub reply {
206: my ($cmd,$server)=@_;
1.838 albertel 207: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 208: my $answer=subreply($cmd,$server);
1.65 www 209: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 210: &logthis("<font color=\"blue\">WARNING:".
1.12 www 211: " $cmd to $server returned $answer</font>");
212: }
1.1 albertel 213: return $answer;
214: }
215:
216: # ----------------------------------------------------------- Send USR1 to lonc
217:
218: sub reconlonc {
1.891 albertel 219: my ($lonid) = @_;
220: my $hostname = &hostname($lonid);
221: if ($lonid) {
222: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
223: if ($hostname && -e $peerfile) {
224: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
225: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
226: Type => SOCK_STREAM,
227: Timeout => 10);
228: if ($client) {
229: print $client ("reset_retries\n");
230: my $answer=<$client>;
231: #reset just this one.
232: }
233: }
234: return;
235: }
236:
1.836 www 237: &logthis("Trying to reconnect lonc");
1.1 albertel 238: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 239: if (open(my $fh,"<$loncfile")) {
1.1 albertel 240: my $loncpid=<$fh>;
241: chomp($loncpid);
242: if (kill 0 => $loncpid) {
243: &logthis("lonc at pid $loncpid responding, sending USR1");
244: kill USR1 => $loncpid;
245: sleep 1;
1.836 www 246: } else {
1.12 www 247: &logthis(
1.672 albertel 248: "<font color=\"blue\">WARNING:".
1.12 www 249: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 250: }
251: } else {
1.836 www 252: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 253: }
254: }
255:
256: # ------------------------------------------------------ Critical communication
1.12 www 257:
1.1 albertel 258: sub critical {
259: my ($cmd,$server)=@_;
1.838 albertel 260: unless (&hostname($server)) {
1.672 albertel 261: &logthis("<font color=\"blue\">WARNING:".
1.89 www 262: " Critical message to unknown server ($server)</font>");
263: return 'no_such_host';
264: }
1.1 albertel 265: my $answer=reply($cmd,$server);
266: if ($answer eq 'con_lost') {
267: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 268: my $answer=reply($cmd,$server);
1.1 albertel 269: if ($answer eq 'con_lost') {
270: my $now=time;
271: my $middlename=$cmd;
1.5 www 272: $middlename=substr($middlename,0,16);
1.1 albertel 273: $middlename=~s/\W//g;
274: my $dfilename=
1.305 www 275: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
276: $dumpcount++;
1.1 albertel 277: {
1.448 albertel 278: my $dfh;
279: if (open($dfh,">$dfilename")) {
280: print $dfh "$cmd\n";
281: close($dfh);
282: }
1.1 albertel 283: }
284: sleep 2;
285: my $wcmd='';
286: {
1.448 albertel 287: my $dfh;
288: if (open($dfh,"<$dfilename")) {
289: $wcmd=<$dfh>;
290: close($dfh);
291: }
1.1 albertel 292: }
293: chomp($wcmd);
1.7 www 294: if ($wcmd eq $cmd) {
1.672 albertel 295: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 296: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 297: &logperm("D:$server:$cmd");
298: return 'con_delayed';
299: } else {
1.672 albertel 300: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 301: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 302: &logperm("F:$server:$cmd");
303: return 'con_failed';
304: }
305: }
306: }
307: return $answer;
1.405 albertel 308: }
309:
1.755 albertel 310: # ------------------------------------------- check if return value is an error
311:
312: sub error {
313: my ($result) = @_;
1.756 albertel 314: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 315: if ($2 == 2) { return undef; }
316: return $1;
317: }
318: return undef;
319: }
320:
1.783 albertel 321: sub convert_and_load_session_env {
322: my ($lonidsdir,$handle)=@_;
323: my @profile;
324: {
1.917 albertel 325: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
326: if (!$opened) {
1.915 albertel 327: return 0;
328: }
1.783 albertel 329: flock($idf,LOCK_SH);
330: @profile=<$idf>;
331: close($idf);
332: }
333: my %temp_env;
334: foreach my $line (@profile) {
1.786 albertel 335: if ($line !~ m/=/) {
336: return 0;
337: }
1.783 albertel 338: chomp($line);
339: my ($envname,$envvalue)=split(/=/,$line,2);
340: $temp_env{&unescape($envname)} = &unescape($envvalue);
341: }
342: unlink("$lonidsdir/$handle.id");
343: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
344: 0640)) {
345: %disk_env = %temp_env;
346: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
347: untie(%disk_env);
348: }
1.786 albertel 349: return 1;
1.783 albertel 350: }
351:
1.374 www 352: # ------------------------------------------- Transfer profile into environment
1.780 albertel 353: my $env_loaded;
354: sub transfer_profile_to_env {
1.788 albertel 355: my ($lonidsdir,$handle,$force_transfer) = @_;
356: if (!$force_transfer && $env_loaded) { return; }
1.374 www 357:
1.720 albertel 358: if (!defined($lonidsdir)) {
359: $lonidsdir = $perlvar{'lonIDsDir'};
360: }
361: if (!defined($handle)) {
362: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
363: }
364:
1.786 albertel 365: my $convert;
366: {
1.917 albertel 367: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
368: if (!$opened) {
1.915 albertel 369: return;
370: }
1.786 albertel 371: flock($idf,LOCK_SH);
372: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
373: &GDBM_READER(),0640)) {
374: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
375: untie(%disk_env);
376: } else {
377: $convert = 1;
378: }
379: }
380: if ($convert) {
381: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
382: &logthis("Failed to load session, or convert session.");
383: }
1.374 www 384: }
1.783 albertel 385:
1.786 albertel 386: my %remove;
1.783 albertel 387: while ( my $envname = each(%env) ) {
1.433 matthew 388: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
389: if ($time < time-300) {
1.783 albertel 390: $remove{$key}++;
1.433 matthew 391: }
392: }
393: }
1.783 albertel 394:
1.619 albertel 395: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 396: $env_loaded=1;
1.783 albertel 397: foreach my $expired_key (keys(%remove)) {
1.433 matthew 398: &delenv($expired_key);
1.374 www 399: }
1.1 albertel 400: }
401:
1.916 albertel 402: # ---------------------------------------------------- Check for valid session
403: sub check_for_valid_session {
404: my ($r) = @_;
405: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
406: my $lonid=$cookies{'lonID'};
407: return undef if (!$lonid);
408:
409: my $handle=&LONCAPA::clean_handle($lonid->value);
410: my $lonidsdir=$r->dir_config('lonIDsDir');
411: return undef if (!-e "$lonidsdir/$handle.id");
412:
1.917 albertel 413: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
414: return undef if (!$opened);
1.916 albertel 415:
416: flock($idf,LOCK_SH);
417: my %disk_env;
418: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
419: &GDBM_READER(),0640)) {
420: return undef;
421: }
422:
423: if (!defined($disk_env{'user.name'})
424: || !defined($disk_env{'user.domain'})) {
425: return undef;
426: }
427: return $handle;
428: }
429:
1.830 albertel 430: sub timed_flock {
431: my ($file,$lock_type) = @_;
432: my $failed=0;
433: eval {
434: local $SIG{__DIE__}='DEFAULT';
435: local $SIG{ALRM}=sub {
436: $failed=1;
437: die("failed lock");
438: };
439: alarm(13);
440: flock($file,$lock_type);
441: alarm(0);
442: };
443: if ($failed) {
444: return undef;
445: } else {
446: return 1;
447: }
448: }
449:
1.5 www 450: # ---------------------------------------------------------- Append Environment
451:
452: sub appenv {
1.949 raeburn 453: my ($newenv,$roles) = @_;
454: if (ref($newenv) eq 'HASH') {
455: foreach my $key (keys(%{$newenv})) {
456: my $refused = 0;
457: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
458: $refused = 1;
459: if (ref($roles) eq 'ARRAY') {
460: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
461: if (grep(/^\Q$role\E$/,@{$roles})) {
462: $refused = 0;
463: }
464: }
465: }
466: if ($refused) {
467: &logthis("<font color=\"blue\">WARNING: ".
468: "Attempt to modify environment ".$key." to ".$newenv->{$key}
469: .'</font>');
470: delete($newenv->{$key});
471: } else {
472: $env{$key}=$newenv->{$key};
473: }
474: }
475: my $opened = open(my $env_file,'+<',$env{'user.environment'});
476: if ($opened
477: && &timed_flock($env_file,LOCK_EX)
478: &&
479: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
480: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
481: while (my ($key,$value) = each(%{$newenv})) {
482: $disk_env{$key} = $value;
483: }
484: untie(%disk_env);
1.35 www 485: }
1.191 harris41 486: }
1.56 www 487: return 'ok';
488: }
489: # ----------------------------------------------------- Delete from Environment
490:
491: sub delenv {
492: my $delthis=shift;
493: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 494: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 495: "Attempt to delete from environment ".$delthis);
496: return 'error';
497: }
1.917 albertel 498: my $opened = open(my $env_file,'+<',$env{'user.environment'});
499: if ($opened
1.915 albertel 500: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 501: &&
502: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
503: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 504: foreach my $key (keys(%disk_env)) {
505: if ($key=~/^$delthis/) {
1.915 albertel 506: delete($env{$key});
507: delete($disk_env{$key});
508: }
1.448 albertel 509: }
1.783 albertel 510: untie(%disk_env);
1.5 www 511: }
512: return 'ok';
1.369 albertel 513: }
514:
1.790 albertel 515: sub get_env_multiple {
516: my ($name) = @_;
517: my @values;
518: if (defined($env{$name})) {
519: # exists is it an array
520: if (ref($env{$name})) {
521: @values=@{ $env{$name} };
522: } else {
523: $values[0]=$env{$name};
524: }
525: }
526: return(@values);
527: }
528:
1.958 www 529: # ------------------------------------------------------------------- Locking
530:
531: sub set_lock {
532: my ($text)=@_;
533: $locknum++;
534: my $id=$$.'-'.$locknum;
535: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
536: 'session.lock.'.$id => $text});
537: return $id;
538: }
539:
540: sub get_locks {
541: my $num=0;
542: my %texts=();
543: foreach my $lock (split(/\,/,$env{'session.locks'})) {
544: if ($lock=~/\w/) {
545: $num++;
546: $texts{$lock}=$env{'session.lock.'.$lock};
547: }
548: }
549: return ($num,%texts);
550: }
551:
552: sub remove_lock {
553: my ($id)=@_;
554: my $newlocks='';
555: foreach my $lock (split(/\,/,$env{'session.locks'})) {
556: if (($lock=~/\w/) && ($lock ne $id)) {
557: $newlocks.=','.$lock;
558: }
559: }
560: &appenv({'session.locks' => $newlocks});
561: &delenv('session.lock.'.$id);
562: }
563:
564: sub remove_all_locks {
565: my $activelocks=$env{'session.locks'};
566: foreach my $lock (split(/\,/,$env{'session.locks'})) {
567: if ($lock=~/\w/) {
568: &remove_lock($lock);
569: }
570: }
571: }
572:
573:
1.369 albertel 574: # ------------------------------------------ Find out current server userload
575: sub userload {
576: my $numusers=0;
577: {
578: opendir(LONIDS,$perlvar{'lonIDsDir'});
579: my $filename;
580: my $curtime=time;
581: while ($filename=readdir(LONIDS)) {
1.925 albertel 582: next if ($filename eq '.' || $filename eq '..');
583: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 584: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 585: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 586: }
587: closedir(LONIDS);
588: }
589: my $userloadpercent=0;
590: my $maxuserload=$perlvar{'lonUserLoadLim'};
591: if ($maxuserload) {
1.371 albertel 592: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 593: }
1.372 albertel 594: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 595: return $userloadpercent;
1.283 www 596: }
597:
598: # ------------------------------------------ Fight off request when overloaded
599:
600: sub overloaderror {
601: my ($r,$checkserver)=@_;
602: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
603: my $loadavg;
604: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 605: open(my $loadfile,'/proc/loadavg');
1.283 www 606: $loadavg=<$loadfile>;
607: $loadavg =~ s/\s.*//g;
1.285 matthew 608: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 609: close($loadfile);
1.283 www 610: } else {
611: $loadavg=&reply('load',$checkserver);
612: }
1.285 matthew 613: my $overload=$loadavg-100;
1.283 www 614: if ($overload>0) {
1.285 matthew 615: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 616: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 617: return 413;
1.283 www 618: }
619: return '';
1.5 www 620: }
1.1 albertel 621:
622: # ------------------------------ Find server with least workload from spare.tab
1.11 www 623:
1.1 albertel 624: sub spareserver {
1.670 albertel 625: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 626: my $spare_server;
1.370 albertel 627: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 628: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
629: : $userloadpercent;
630:
631: foreach my $try_server (@{ $spareid{'primary'} }) {
632: ($spare_server, $lowest_load) =
633: &compare_server_load($try_server, $spare_server, $lowest_load);
634: }
635:
636: my $found_server = ($spare_server ne '' && $lowest_load < 100);
637:
638: if (!$found_server) {
639: foreach my $try_server (@{ $spareid{'default'} }) {
640: ($spare_server, $lowest_load) =
641: &compare_server_load($try_server, $spare_server, $lowest_load);
642: }
643: }
644:
645: if (!$want_server_name) {
1.838 albertel 646: $spare_server="http://".&hostname($spare_server);
1.784 albertel 647: }
648: return $spare_server;
649: }
650:
651: sub compare_server_load {
652: my ($try_server, $spare_server, $lowest_load) = @_;
653:
654: my $loadans = &reply('load', $try_server);
655: my $userloadans = &reply('userload',$try_server);
656:
657: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
658: next; #didn't get a number from the server
659: }
660:
661: my $load;
662: if ($loadans =~ /\d/) {
663: if ($userloadans =~ /\d/) {
664: #both are numbers, pick the bigger one
665: $load = ($loadans > $userloadans) ? $loadans
666: : $userloadans;
1.411 albertel 667: } else {
1.784 albertel 668: $load = $loadans;
1.411 albertel 669: }
1.784 albertel 670: } else {
671: $load = $userloadans;
672: }
673:
674: if (($load =~ /\d/) && ($load < $lowest_load)) {
675: $spare_server = $try_server;
676: $lowest_load = $load;
1.370 albertel 677: }
1.784 albertel 678: return ($spare_server,$lowest_load);
1.202 matthew 679: }
1.914 albertel 680:
681: # --------------------------- ask offload servers if user already has a session
682: sub find_existing_session {
683: my ($udom,$uname) = @_;
684: foreach my $try_server (@{ $spareid{'primary'} },
685: @{ $spareid{'default'} }) {
686: return $try_server if (&has_user_session($try_server, $udom, $uname));
687: }
688: return;
689: }
690:
691: # -------------------------------- ask if server already has a session for user
692: sub has_user_session {
693: my ($lonid,$udom,$uname) = @_;
694: my $result = &reply(join(':','userhassession',
695: map {&escape($_)} ($udom,$uname)),$lonid);
696: return 1 if ($result eq 'ok');
697:
698: return 0;
699: }
700:
1.202 matthew 701: # --------------------------------------------- Try to change a user's password
702:
703: sub changepass {
1.799 raeburn 704: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 705: $currentpass = &escape($currentpass);
706: $newpass = &escape($newpass);
1.799 raeburn 707: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202 matthew 708: $server);
709: if (! $answer) {
710: &logthis("No reply on password change request to $server ".
711: "by $uname in domain $udom.");
712: } elsif ($answer =~ "^ok") {
713: &logthis("$uname in $udom successfully changed their password ".
714: "on $server.");
715: } elsif ($answer =~ "^pwchange_failure") {
716: &logthis("$uname in $udom was unable to change their password ".
717: "on $server. The action was blocked by either lcpasswd ".
718: "or pwchange");
719: } elsif ($answer =~ "^non_authorized") {
720: &logthis("$uname in $udom did not get their password correct when ".
721: "attempting to change it on $server.");
722: } elsif ($answer =~ "^auth_mode_error") {
723: &logthis("$uname in $udom attempted to change their password despite ".
724: "not being locally or internally authenticated on $server.");
725: } elsif ($answer =~ "^unknown_user") {
726: &logthis("$uname in $udom attempted to change their password ".
727: "on $server but were unable to because $server is not ".
728: "their home server.");
729: } elsif ($answer =~ "^refused") {
730: &logthis("$server refused to change $uname in $udom password because ".
731: "it was sent an unencrypted request to change the password.");
732: }
733: return $answer;
1.1 albertel 734: }
735:
1.169 harris41 736: # ----------------------- Try to determine user's current authentication scheme
737:
738: sub queryauthenticate {
739: my ($uname,$udom)=@_;
1.456 albertel 740: my $uhome=&homeserver($uname,$udom);
741: if (!$uhome) {
742: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
743: return 'no_host';
744: }
745: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
746: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
747: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 748: }
1.456 albertel 749: return $answer;
1.169 harris41 750: }
751:
1.1 albertel 752: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 753:
1.1 albertel 754: sub authenticate {
1.952 raeburn 755: my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807 albertel 756: $upass=&escape($upass);
757: $uname= &LONCAPA::clean_username($uname);
1.836 www 758: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 759: my $newhome;
1.836 www 760: if ((!$uhome) || ($uhome eq 'no_host')) {
761: # Maybe the machine was offline and only re-appeared again recently?
762: &reconlonc();
763: # One more
1.952 raeburn 764: $uhome=&homeserver($uname,$udom,1);
765: if (($uhome eq 'no_host') && $checkdefauth) {
766: if (defined(&domain($udom,'primary'))) {
767: $newhome=&domain($udom,'primary');
768: }
769: if ($newhome ne '') {
770: $uhome = $newhome;
771: }
772: }
1.836 www 773: if ((!$uhome) || ($uhome eq 'no_host')) {
774: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 775: return 'no_host';
776: }
1.1 albertel 777: }
1.952 raeburn 778: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471 albertel 779: if ($answer eq 'authorized') {
1.952 raeburn 780: if ($newhome) {
781: &logthis("User $uname at $udom authorized by $uhome, but needs account");
782: return 'no_account_on_host';
783: } else {
784: &logthis("User $uname at $udom authorized by $uhome");
785: return $uhome;
786: }
1.471 albertel 787: }
788: if ($answer eq 'non_authorized') {
789: &logthis("User $uname at $udom rejected by $uhome");
790: return 'no_host';
1.9 www 791: }
1.471 albertel 792: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 793: return 'no_host';
794: }
795:
796: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 797:
1.599 albertel 798: my %homecache;
1.1 albertel 799: sub homeserver {
1.230 stredwic 800: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 801: my $index="$uname:$udom";
1.426 albertel 802:
1.599 albertel 803: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 804:
805: my %servers = &get_servers($udom,'library');
806: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 807: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 808: exists($badServerCache{$tryserver}));
1.841 albertel 809:
810: my $answer=reply("home:$udom:$uname",$tryserver);
811: if ($answer eq 'found') {
812: delete($badServerCache{$tryserver});
813: return $homecache{$index}=$tryserver;
814: } elsif ($answer eq 'no_host') {
815: $badServerCache{$tryserver}=1;
816: }
1.1 albertel 817: }
818: return 'no_host';
1.70 www 819: }
820:
821: # ------------------------------------- Find the usernames behind a list of IDs
822:
823: sub idget {
824: my ($udom,@ids)=@_;
825: my %returnhash=();
826:
1.841 albertel 827: my %servers = &get_servers($udom,'library');
828: foreach my $tryserver (keys(%servers)) {
829: my $idlist=join('&',@ids);
830: $idlist=~tr/A-Z/a-z/;
831: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
832: my @answer=();
833: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
834: @answer=split(/\&/,$reply);
835: } ;
836: my $i;
837: for ($i=0;$i<=$#ids;$i++) {
838: if ($answer[$i]) {
839: $returnhash{$ids[$i]}=$answer[$i];
840: }
841: }
842: }
1.70 www 843: return %returnhash;
844: }
845:
846: # ------------------------------------- Find the IDs behind a list of usernames
847:
848: sub idrget {
849: my ($udom,@unames)=@_;
850: my %returnhash=();
1.800 albertel 851: foreach my $uname (@unames) {
852: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 853: }
1.70 www 854: return %returnhash;
855: }
856:
857: # ------------------------------- Store away a list of names and associated IDs
858:
859: sub idput {
860: my ($udom,%ids)=@_;
861: my %servers=();
1.800 albertel 862: foreach my $uname (keys(%ids)) {
863: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
864: my $uhom=&homeserver($uname,$udom);
1.70 www 865: if ($uhom ne 'no_host') {
1.800 albertel 866: my $id=&escape($ids{$uname});
1.70 www 867: $id=~tr/A-Z/a-z/;
1.800 albertel 868: my $esc_unam=&escape($uname);
1.70 www 869: if ($servers{$uhom}) {
1.800 albertel 870: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 871: } else {
1.800 albertel 872: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 873: }
874: }
1.191 harris41 875: }
1.800 albertel 876: foreach my $server (keys(%servers)) {
877: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 878: }
1.344 www 879: }
880:
1.806 raeburn 881: # ------------------------------------------- get items from domain db files
882:
883: sub get_dom {
1.860 raeburn 884: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 885: my $items='';
886: foreach my $item (@$storearr) {
887: $items.=&escape($item).'&';
888: }
889: $items=~s/\&$//;
1.860 raeburn 890: if (!$udom) {
891: $udom=$env{'user.domain'};
892: if (defined(&domain($udom,'primary'))) {
893: $uhome=&domain($udom,'primary');
894: } else {
1.874 albertel 895: undef($uhome);
1.860 raeburn 896: }
897: } else {
898: if (!$uhome) {
899: if (defined(&domain($udom,'primary'))) {
900: $uhome=&domain($udom,'primary');
901: }
902: }
903: }
904: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 905: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 906: my %returnhash;
1.875 albertel 907: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 908: return %returnhash;
909: }
1.806 raeburn 910: my @pairs=split(/\&/,$rep);
911: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
912: return @pairs;
913: }
914: my $i=0;
915: foreach my $item (@$storearr) {
916: $returnhash{$item}=&thaw_unescape($pairs[$i]);
917: $i++;
918: }
919: return %returnhash;
920: } else {
1.880 banghart 921: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 922: }
923: }
924:
925: # -------------------------------------------- put items in domain db files
926:
927: sub put_dom {
1.860 raeburn 928: my ($namespace,$storehash,$udom,$uhome)=@_;
929: if (!$udom) {
930: $udom=$env{'user.domain'};
931: if (defined(&domain($udom,'primary'))) {
932: $uhome=&domain($udom,'primary');
933: } else {
1.874 albertel 934: undef($uhome);
1.860 raeburn 935: }
936: } else {
937: if (!$uhome) {
938: if (defined(&domain($udom,'primary'))) {
939: $uhome=&domain($udom,'primary');
940: }
941: }
942: }
943: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 944: my $items='';
945: foreach my $item (keys(%$storehash)) {
946: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
947: }
948: $items=~s/\&$//;
949: return &reply("putdom:$udom:$namespace:$items",$uhome);
950: } else {
1.860 raeburn 951: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 952: }
953: }
954:
1.837 raeburn 955: sub retrieve_inst_usertypes {
956: my ($udom) = @_;
957: my (%returnhash,@order);
1.846 albertel 958: if (defined(&domain($udom,'primary'))) {
959: my $uhome=&domain($udom,'primary');
1.837 raeburn 960: my $rep=&reply("inst_usertypes:$udom",$uhome);
1.960 raeburn 961: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
962: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
963: return (\%returnhash,\@order);
964: }
1.837 raeburn 965: my ($hashitems,$orderitems) = split(/:/,$rep);
966: my @pairs=split(/\&/,$hashitems);
967: foreach my $item (@pairs) {
968: my ($key,$value)=split(/=/,$item,2);
969: $key = &unescape($key);
970: next if ($key =~ /^error: 2 /);
971: $returnhash{$key}=&thaw_unescape($value);
972: }
973: my @esc_order = split(/\&/,$orderitems);
974: foreach my $item (@esc_order) {
975: push(@order,&unescape($item));
976: }
977: } else {
978: &logthis("get_dom failed - no primary domain server for $udom");
979: }
980: return (\%returnhash,\@order);
981: }
982:
1.868 raeburn 983: sub is_domainimage {
984: my ($url) = @_;
985: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
986: if (&domain($1) ne '') {
987: return '1';
988: }
989: }
990: return;
991: }
992:
1.899 raeburn 993: sub inst_directory_query {
994: my ($srch) = @_;
995: my $udom = $srch->{'srchdomain'};
996: my %results;
997: my $homeserver = &domain($udom,'primary');
1.909 raeburn 998: my $outcome;
1.899 raeburn 999: if ($homeserver ne '') {
1.904 albertel 1000: my $queryid=&reply("querysend:instdirsearch:".
1001: &escape($srch->{'srchby'}).':'.
1002: &escape($srch->{'srchterm'}).':'.
1003: &escape($srch->{'srchtype'}),$homeserver);
1004: my $host=&hostname($homeserver);
1005: if ($queryid !~/^\Q$host\E\_/) {
1006: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1007: return;
1008: }
1009: my $response = &get_query_reply($queryid);
1010: my $maxtries = 5;
1011: my $tries = 1;
1012: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1013: $response = &get_query_reply($queryid);
1014: $tries ++;
1015: }
1016:
1017: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1018: if ($response eq 'unavailable') {
1019: $outcome = $response;
1020: } else {
1021: $outcome = 'ok';
1022: my @matches = split(/\n/,$response);
1023: foreach my $match (@matches) {
1024: my ($key,$value) = split(/=/,$match);
1025: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1026: }
1.899 raeburn 1027: }
1028: }
1029: }
1.909 raeburn 1030: return ($outcome,%results);
1.899 raeburn 1031: }
1032:
1033: sub usersearch {
1034: my ($srch) = @_;
1035: my $dom = $srch->{'srchdomain'};
1036: my %results;
1037: my %libserv = &all_library();
1038: my $query = 'usersearch';
1039: foreach my $tryserver (keys(%libserv)) {
1040: if (&host_domain($tryserver) eq $dom) {
1041: my $host=&hostname($tryserver);
1042: my $queryid=
1.911 raeburn 1043: &reply("querysend:".&escape($query).':'.
1044: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1045: &escape($srch->{'srchtype'}).':'.
1046: &escape($srch->{'srchterm'}),$tryserver);
1047: if ($queryid !~/^\Q$host\E\_/) {
1048: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1049: next;
1.899 raeburn 1050: }
1051: my $reply = &get_query_reply($queryid);
1052: my $maxtries = 1;
1053: my $tries = 1;
1054: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1055: $reply = &get_query_reply($queryid);
1056: $tries ++;
1057: }
1058: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1059: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1060: } else {
1.911 raeburn 1061: my @matches;
1062: if ($reply =~ /\n/) {
1063: @matches = split(/\n/,$reply);
1064: } else {
1065: @matches = split(/\&/,$reply);
1066: }
1.899 raeburn 1067: foreach my $match (@matches) {
1068: my ($uname,$udom,%userhash);
1.911 raeburn 1069: foreach my $entry (split(/:/,$match)) {
1070: my ($key,$value) =
1071: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1072: $userhash{$key} = $value;
1073: if ($key eq 'username') {
1074: $uname = $value;
1075: } elsif ($key eq 'domain') {
1076: $udom = $value;
1.911 raeburn 1077: }
1.899 raeburn 1078: }
1079: $results{$uname.':'.$udom} = \%userhash;
1080: }
1081: }
1082: }
1083: }
1084: return %results;
1085: }
1086:
1.912 raeburn 1087: sub get_instuser {
1088: my ($udom,$uname,$id) = @_;
1089: my $homeserver = &domain($udom,'primary');
1090: my ($outcome,%results);
1091: if ($homeserver ne '') {
1092: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1093: &escape($id).':'.&escape($udom),$homeserver);
1094: my $host=&hostname($homeserver);
1095: if ($queryid !~/^\Q$host\E\_/) {
1096: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1097: return;
1098: }
1099: my $response = &get_query_reply($queryid);
1100: my $maxtries = 5;
1101: my $tries = 1;
1102: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1103: $response = &get_query_reply($queryid);
1104: $tries ++;
1105: }
1106: if (!&error($response) && $response ne 'refused') {
1107: if ($response eq 'unavailable') {
1108: $outcome = $response;
1109: } else {
1110: $outcome = 'ok';
1111: my @matches = split(/\n/,$response);
1112: foreach my $match (@matches) {
1113: my ($key,$value) = split(/=/,$match);
1114: $results{&unescape($key)} = &thaw_unescape($value);
1115: }
1116: }
1117: }
1118: }
1119: my %userinfo;
1120: if (ref($results{$uname}) eq 'HASH') {
1121: %userinfo = %{$results{$uname}};
1122: }
1123: return ($outcome,%userinfo);
1124: }
1125:
1126: sub inst_rulecheck {
1.923 raeburn 1127: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1128: my %returnhash;
1129: if ($udom ne '') {
1130: if (ref($rules) eq 'ARRAY') {
1131: @{$rules} = map {&escape($_);} (@{$rules});
1132: my $rulestr = join(':',@{$rules});
1133: my $homeserver=&domain($udom,'primary');
1134: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1135: my $response;
1136: if ($item eq 'username') {
1137: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1138: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1139: $homeserver));
1.923 raeburn 1140: } elsif ($item eq 'id') {
1141: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1142: ':'.&escape($id).':'.$rulestr,
1143: $homeserver));
1.945 raeburn 1144: } elsif ($item eq 'selfcreate') {
1145: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1146: &escape($udom).':'.&escape($uname).
1147: ':'.$rulestr,$homeserver));
1.923 raeburn 1148: }
1.912 raeburn 1149: if ($response ne 'refused') {
1150: my @pairs=split(/\&/,$response);
1151: foreach my $item (@pairs) {
1152: my ($key,$value)=split(/=/,$item,2);
1153: $key = &unescape($key);
1154: next if ($key =~ /^error: 2 /);
1155: $returnhash{$key}=&thaw_unescape($value);
1156: }
1157: }
1158: }
1159: }
1160: }
1161: return %returnhash;
1162: }
1163:
1164: sub inst_userrules {
1.923 raeburn 1165: my ($udom,$check) = @_;
1.912 raeburn 1166: my (%ruleshash,@ruleorder);
1167: if ($udom ne '') {
1168: my $homeserver=&domain($udom,'primary');
1169: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1170: my $response;
1171: if ($check eq 'id') {
1172: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1173: $homeserver);
1.943 raeburn 1174: } elsif ($check eq 'email') {
1175: $response=&reply('instemailrules:'.&escape($udom),
1176: $homeserver);
1.923 raeburn 1177: } else {
1178: $response=&reply('instuserrules:'.&escape($udom),
1179: $homeserver);
1180: }
1.912 raeburn 1181: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1182: ($response ne 'unknown_cmd') &&
1.912 raeburn 1183: ($response ne 'no_such_host')) {
1184: my ($hashitems,$orderitems) = split(/:/,$response);
1185: my @pairs=split(/\&/,$hashitems);
1186: foreach my $item (@pairs) {
1187: my ($key,$value)=split(/=/,$item,2);
1188: $key = &unescape($key);
1189: next if ($key =~ /^error: 2 /);
1190: $ruleshash{$key}=&thaw_unescape($value);
1191: }
1192: my @esc_order = split(/\&/,$orderitems);
1193: foreach my $item (@esc_order) {
1194: push(@ruleorder,&unescape($item));
1195: }
1196: }
1197: }
1198: }
1199: return (\%ruleshash,\@ruleorder);
1200: }
1201:
1.943 raeburn 1202: # ------------------------- Get Authentication and Language Defaults for Domain
1203:
1204: sub get_domain_defaults {
1205: my ($domain) = @_;
1206: my $cachetime = 60*60*24;
1207: my ($defauthtype,$defautharg,$deflang);
1208: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1209: if (defined($cached)) {
1210: if (ref($result) eq 'HASH') {
1211: return %{$result};
1212: }
1213: }
1214: my %domdefaults;
1215: my %domconfig =
1216: &Apache::lonnet::get_dom('configuration',['defaults'],$domain);
1217: if (ref($domconfig{'defaults'}) eq 'HASH') {
1218: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1219: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1220: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1221: } else {
1222: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1223: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1224: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1225: }
1226: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1227: $cachetime);
1228: return %domdefaults;
1229: }
1230:
1.344 www 1231: # --------------------------------------------------- Assign a key to a student
1232:
1233: sub assign_access_key {
1.364 www 1234: #
1235: # a valid key looks like uname:udom#comments
1236: # comments are being appended
1237: #
1.498 www 1238: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1239: $kdom=
1.620 albertel 1240: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1241: $knum=
1.620 albertel 1242: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1243: $cdom=
1.620 albertel 1244: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1245: $cnum=
1.620 albertel 1246: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1247: $udom=$env{'user.name'} unless (defined($udom));
1248: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1249: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1250: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1251: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1252: # assigned to this person
1253: # - this should not happen,
1.345 www 1254: # unless something went wrong
1255: # the first time around
1256: # ready to assign
1.364 www 1257: $logentry=$1.'; '.$logentry;
1.496 www 1258: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1259: $kdom,$knum) eq 'ok') {
1.345 www 1260: # key now belongs to user
1.346 www 1261: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1262: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1263: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1264: return 'ok';
1265: } else {
1266: return
1267: 'error: Count not permanently assign key, will need to be re-entered later.';
1268: }
1269: } else {
1270: return 'error: Could not assign key, try again later.';
1271: }
1.364 www 1272: } elsif (!$existing{$ckey}) {
1.345 www 1273: # the key does not exist
1274: return 'error: The key does not exist';
1275: } else {
1276: # the key is somebody else's
1277: return 'error: The key is already in use';
1278: }
1.344 www 1279: }
1280:
1.364 www 1281: # ------------------------------------------ put an additional comment on a key
1282:
1283: sub comment_access_key {
1284: #
1285: # a valid key looks like uname:udom#comments
1286: # comments are being appended
1287: #
1288: my ($ckey,$cdom,$cnum,$logentry)=@_;
1289: $cdom=
1.620 albertel 1290: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1291: $cnum=
1.620 albertel 1292: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1293: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1294: if ($existing{$ckey}) {
1295: $existing{$ckey}.='; '.$logentry;
1296: # ready to assign
1.367 www 1297: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1298: $cdom,$cnum) eq 'ok') {
1299: return 'ok';
1300: } else {
1301: return 'error: Count not store comment.';
1302: }
1303: } else {
1304: # the key does not exist
1305: return 'error: The key does not exist';
1306: }
1307: }
1308:
1.344 www 1309: # ------------------------------------------------------ Generate a set of keys
1310:
1311: sub generate_access_keys {
1.364 www 1312: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1313: $cdom=
1.620 albertel 1314: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1315: $cnum=
1.620 albertel 1316: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1317: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1318: unless (($cdom) && ($cnum)) { return 0; }
1319: if ($number>10000) { return 0; }
1320: sleep(2); # make sure don't get same seed twice
1321: srand(time()^($$+($$<<15))); # from "Programming Perl"
1322: my $total=0;
1323: for (my $i=1;$i<=$number;$i++) {
1324: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1325: sprintf("%lx",int(100000*rand)).'-'.
1326: sprintf("%lx",int(100000*rand));
1327: $newkey=~s/1/g/g; # folks mix up 1 and l
1328: $newkey=~s/0/h/g; # and also 0 and O
1329: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1330: if ($existing{$newkey}) {
1331: $i--;
1332: } else {
1.364 www 1333: if (&put('accesskeys',
1334: { $newkey => '# generated '.localtime().
1.620 albertel 1335: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1336: '; '.$logentry },
1337: $cdom,$cnum) eq 'ok') {
1.344 www 1338: $total++;
1339: }
1340: }
1341: }
1.620 albertel 1342: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1343: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1344: return $total;
1345: }
1346:
1347: # ------------------------------------------------------- Validate an accesskey
1348:
1349: sub validate_access_key {
1350: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1351: $cdom=
1.620 albertel 1352: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1353: $cnum=
1.620 albertel 1354: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1355: $udom=$env{'user.domain'} unless (defined($udom));
1356: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1357: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1358: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1359: }
1360:
1361: # ------------------------------------- Find the section of student in a course
1.652 albertel 1362: sub devalidate_getsection_cache {
1363: my ($udom,$unam,$courseid)=@_;
1364: my $hashid="$udom:$unam:$courseid";
1365: &devalidate_cache_new('getsection',$hashid);
1366: }
1.298 matthew 1367:
1.815 albertel 1368: sub courseid_to_courseurl {
1369: my ($courseid) = @_;
1370: #already url style courseid
1371: return $courseid if ($courseid =~ m{^/});
1372:
1373: if (exists($env{'course.'.$courseid.'.num'})) {
1374: my $cnum = $env{'course.'.$courseid.'.num'};
1375: my $cdom = $env{'course.'.$courseid.'.domain'};
1376: return "/$cdom/$cnum";
1377: }
1378:
1379: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1380: if (exists($courseinfo{'num'})) {
1381: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1382: }
1383:
1384: return undef;
1385: }
1386:
1.298 matthew 1387: sub getsection {
1388: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1389: my $cachetime=1800;
1.551 albertel 1390:
1391: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1392: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1393: if (defined($cached)) { return $result; }
1394:
1.298 matthew 1395: my %Pending;
1396: my %Expired;
1397: #
1398: # Each role can either have not started yet (pending), be active,
1399: # or have expired.
1400: #
1401: # If there is an active role, we are done.
1402: #
1403: # If there is more than one role which has not started yet,
1404: # choose the one which will start sooner
1405: # If there is one role which has not started yet, return it.
1406: #
1407: # If there is more than one expired role, choose the one which ended last.
1408: # If there is a role which has expired, return it.
1409: #
1.815 albertel 1410: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1411: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1412: foreach my $key (keys(%roleshash)) {
1.479 albertel 1413: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1414: my $section=$1;
1415: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1416: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1417: my $now=time;
1.548 albertel 1418: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1419: $Expired{$end}=$section;
1420: next;
1421: }
1.548 albertel 1422: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1423: $Pending{$start}=$section;
1424: next;
1425: }
1.599 albertel 1426: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1427: }
1428: #
1429: # Presumedly there will be few matching roles from the above
1430: # loop and the sorting time will be negligible.
1431: if (scalar(keys(%Pending))) {
1432: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1433: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1434: }
1435: if (scalar(keys(%Expired))) {
1436: my @sorted = sort {$a <=> $b} keys(%Expired);
1437: my $time = pop(@sorted);
1.599 albertel 1438: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1439: }
1.599 albertel 1440: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1441: }
1.70 www 1442:
1.599 albertel 1443: sub save_cache {
1444: &purge_remembered();
1.722 albertel 1445: #&Apache::loncommon::validate_page();
1.620 albertel 1446: undef(%env);
1.780 albertel 1447: undef($env_loaded);
1.599 albertel 1448: }
1.452 albertel 1449:
1.599 albertel 1450: my $to_remember=-1;
1451: my %remembered;
1452: my %accessed;
1453: my $kicks=0;
1454: my $hits=0;
1.849 albertel 1455: sub make_key {
1456: my ($name,$id) = @_;
1.872 albertel 1457: if (length($id) > 65
1458: && length(&escape($id)) > 200) {
1459: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1460: }
1.849 albertel 1461: return &escape($name.':'.$id);
1462: }
1463:
1.599 albertel 1464: sub devalidate_cache_new {
1465: my ($name,$id,$debug) = @_;
1466: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1467: $id=&make_key($name,$id);
1.599 albertel 1468: $memcache->delete($id);
1469: delete($remembered{$id});
1470: delete($accessed{$id});
1471: }
1472:
1473: sub is_cached_new {
1474: my ($name,$id,$debug) = @_;
1.849 albertel 1475: $id=&make_key($name,$id);
1.599 albertel 1476: if (exists($remembered{$id})) {
1477: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1478: $accessed{$id}=[&gettimeofday()];
1479: $hits++;
1480: return ($remembered{$id},1);
1481: }
1482: my $value = $memcache->get($id);
1483: if (!(defined($value))) {
1484: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1485: return (undef,undef);
1.416 albertel 1486: }
1.599 albertel 1487: if ($value eq '__undef__') {
1488: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1489: $value=undef;
1490: }
1491: &make_room($id,$value,$debug);
1492: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1493: return ($value,1);
1494: }
1495:
1496: sub do_cache_new {
1497: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1498: $id=&make_key($name,$id);
1.599 albertel 1499: my $setvalue=$value;
1500: if (!defined($setvalue)) {
1501: $setvalue='__undef__';
1502: }
1.623 albertel 1503: if (!defined($time) ) {
1504: $time=600;
1505: }
1.599 albertel 1506: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1507: my $result = $memcache->set($id,$setvalue,$time);
1508: if (! $result) {
1.872 albertel 1509: &logthis("caching of id -> $id failed");
1.910 albertel 1510: $memcache->disconnect_all();
1.872 albertel 1511: }
1.600 albertel 1512: # need to make a copy of $value
1.919 albertel 1513: &make_room($id,$value,$debug);
1.599 albertel 1514: return $value;
1515: }
1516:
1517: sub make_room {
1518: my ($id,$value,$debug)=@_;
1.919 albertel 1519:
1520: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1521: : $value;
1.599 albertel 1522: if ($to_remember<0) { return; }
1523: $accessed{$id}=[&gettimeofday()];
1524: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1525: my $to_kick;
1526: my $max_time=0;
1527: foreach my $other (keys(%accessed)) {
1528: if (&tv_interval($accessed{$other}) > $max_time) {
1529: $to_kick=$other;
1530: $max_time=&tv_interval($accessed{$other});
1531: }
1532: }
1533: delete($remembered{$to_kick});
1534: delete($accessed{$to_kick});
1535: $kicks++;
1536: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1537: return;
1538: }
1539:
1.599 albertel 1540: sub purge_remembered {
1.604 albertel 1541: #&logthis("Tossing ".scalar(keys(%remembered)));
1542: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1543: undef(%remembered);
1544: undef(%accessed);
1.428 albertel 1545: }
1.70 www 1546: # ------------------------------------- Read an entry from a user's environment
1547:
1548: sub userenvironment {
1549: my ($udom,$unam,@what)=@_;
1550: my %returnhash=();
1551: my @answer=split(/\&/,
1552: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
1553: &homeserver($unam,$udom)));
1554: my $i;
1555: for ($i=0;$i<=$#what;$i++) {
1556: $returnhash{$what[$i]}=&unescape($answer[$i]);
1557: }
1558: return %returnhash;
1.1 albertel 1559: }
1560:
1.617 albertel 1561: # ---------------------------------------------------------- Get a studentphoto
1562: sub studentphoto {
1563: my ($udom,$unam,$ext) = @_;
1564: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1565: if (defined($env{'request.course.id'})) {
1.708 raeburn 1566: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1567: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1568: return(&retrievestudentphoto($udom,$unam,$ext));
1569: } else {
1570: my ($result,$perm_reqd)=
1.707 albertel 1571: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1572: if ($result eq 'ok') {
1573: if (!($perm_reqd eq 'yes')) {
1574: return(&retrievestudentphoto($udom,$unam,$ext));
1575: }
1576: }
1577: }
1578: }
1579: } else {
1580: my ($result,$perm_reqd) =
1.707 albertel 1581: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1582: if ($result eq 'ok') {
1583: if (!($perm_reqd eq 'yes')) {
1584: return(&retrievestudentphoto($udom,$unam,$ext));
1585: }
1586: }
1587: }
1588: return '/adm/lonKaputt/lonlogo_broken.gif';
1589: }
1590:
1591: sub retrievestudentphoto {
1592: my ($udom,$unam,$ext,$type) = @_;
1593: my $home=&Apache::lonnet::homeserver($unam,$udom);
1594: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1595: if ($ret eq 'ok') {
1596: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1597: if ($type eq 'thumbnail') {
1598: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1599: }
1600: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1601: return $tokenurl;
1602: } else {
1603: if ($type eq 'thumbnail') {
1604: return '/adm/lonKaputt/genericstudent_tn.gif';
1605: } else {
1606: return '/adm/lonKaputt/lonlogo_broken.gif';
1607: }
1.617 albertel 1608: }
1609: }
1610:
1.263 www 1611: # -------------------------------------------------------------------- New chat
1612:
1613: sub chatsend {
1.724 raeburn 1614: my ($newentry,$anon,$group)=@_;
1.620 albertel 1615: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1616: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1617: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1618: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1619: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1620: &escape($newentry)).':'.$group,$chome);
1.292 www 1621: }
1622:
1623: # ------------------------------------------ Find current version of a resource
1624:
1625: sub getversion {
1626: my $fname=&clutter(shift);
1627: unless ($fname=~/^\/res\//) { return -1; }
1628: return ¤tversion(&filelocation('',$fname));
1629: }
1630:
1631: sub currentversion {
1632: my $fname=shift;
1.599 albertel 1633: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1634: if (defined($cached)) { return $result; }
1.292 www 1635: my $author=$fname;
1636: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1637: my ($udom,$uname)=split(/\//,$author);
1638: my $home=homeserver($uname,$udom);
1639: if ($home eq 'no_host') {
1640: return -1;
1641: }
1642: my $answer=reply("currentversion:$fname",$home);
1643: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1644: return -1;
1645: }
1.599 albertel 1646: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1647: }
1648:
1.1 albertel 1649: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1650:
1.1 albertel 1651: sub subscribe {
1652: my $fname=shift;
1.761 raeburn 1653: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1654: $fname=~s/[\n\r]//g;
1.1 albertel 1655: my $author=$fname;
1656: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1657: my ($udom,$uname)=split(/\//,$author);
1658: my $home=homeserver($uname,$udom);
1.335 albertel 1659: if ($home eq 'no_host') {
1660: return 'not_found';
1.1 albertel 1661: }
1662: my $answer=reply("sub:$fname",$home);
1.64 www 1663: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1664: $answer.=' by '.$home;
1665: }
1.1 albertel 1666: return $answer;
1667: }
1668:
1.8 www 1669: # -------------------------------------------------------------- Replicate file
1670:
1671: sub repcopy {
1672: my $filename=shift;
1.23 www 1673: $filename=~s/\/+/\//g;
1.607 raeburn 1674: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1675: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1676: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1677: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1678: return &repcopy_userfile($filename);
1679: }
1.532 albertel 1680: $filename=~s/[\n\r]//g;
1.8 www 1681: my $transname="$filename.in.transfer";
1.828 www 1682: # FIXME: this should flock
1.607 raeburn 1683: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1684: my $remoteurl=subscribe($filename);
1.64 www 1685: if ($remoteurl =~ /^con_lost by/) {
1686: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1687: return 'unavailable';
1.8 www 1688: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1689: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1690: return 'not_found';
1.64 www 1691: } elsif ($remoteurl =~ /^rejected by/) {
1692: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1693: return 'forbidden';
1.20 www 1694: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1695: return 'ok';
1.8 www 1696: } else {
1.290 www 1697: my $author=$filename;
1698: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1699: my ($udom,$uname)=split(/\//,$author);
1700: my $home=homeserver($uname,$udom);
1701: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1702: my @parts=split(/\//,$filename);
1703: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1704: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1705: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1706: return 'bad_request';
1.8 www 1707: }
1708: my $count;
1709: for ($count=5;$count<$#parts;$count++) {
1710: $path.="/$parts[$count]";
1711: if ((-e $path)!=1) {
1712: mkdir($path,0777);
1713: }
1714: }
1715: my $ua=new LWP::UserAgent;
1716: my $request=new HTTP::Request('GET',"$remoteurl");
1717: my $response=$ua->request($request,$transname);
1718: if ($response->is_error()) {
1719: unlink($transname);
1720: my $message=$response->status_line;
1.672 albertel 1721: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1722: ." LWP get: $message: $filename</font>");
1.607 raeburn 1723: return 'unavailable';
1.8 www 1724: } else {
1.16 www 1725: if ($remoteurl!~/\.meta$/) {
1726: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1727: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1728: if ($mresponse->is_error()) {
1729: unlink($filename.'.meta');
1730: &logthis(
1.672 albertel 1731: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1732: }
1733: }
1.8 www 1734: rename($transname,$filename);
1.607 raeburn 1735: return 'ok';
1.8 www 1736: }
1.290 www 1737: }
1.8 www 1738: }
1.330 www 1739: }
1740:
1741: # ------------------------------------------------ Get server side include body
1742: sub ssi_body {
1.381 albertel 1743: my ($filelink,%form)=@_;
1.606 matthew 1744: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1745: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1746: }
1.953 www 1747: my $output='';
1748: my $response;
1749: if ($filelink=~/^http\:/) {
1.954 raeburn 1750: ($output,$response)=&externalssi($filelink);
1.953 www 1751: } else {
1752: ($output,$response)=&ssi($filelink,%form);
1753: }
1.778 albertel 1754: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1755: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 1756: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 1757: if (wantarray) {
1758: return ($output, $response);
1759: } else {
1760: return $output;
1761: }
1.8 www 1762: }
1763:
1.15 www 1764: # --------------------------------------------------------- Server Side Include
1765:
1.782 albertel 1766: sub absolute_url {
1767: my ($host_name) = @_;
1768: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1769: if ($host_name eq '') {
1770: $host_name = $ENV{'SERVER_NAME'};
1771: }
1772: return $protocol.$host_name;
1773: }
1774:
1.942 foxr 1775: #
1776: # Server side include.
1777: # Parameters:
1778: # fn Possibly encrypted resource name/id.
1779: # form Hash that describes how the rendering should be done
1780: # and other things.
1.944 foxr 1781: # Returns:
1.950 raeburn 1782: # Scalar context: The content of the response.
1783: # Array context: 2 element list of the content and the full response object.
1.942 foxr 1784: #
1.15 www 1785: sub ssi {
1786:
1.944 foxr 1787: my ($fn,%form)=@_;
1.15 www 1788: my $ua=new LWP::UserAgent;
1.23 www 1789: my $request;
1.711 albertel 1790:
1791: $form{'no_update_last_known'}=1;
1.895 albertel 1792: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 1793: if (%form) {
1.782 albertel 1794: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201 albertel 1795: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23 www 1796: } else {
1.782 albertel 1797: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1798: }
1799:
1.15 www 1800: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1801: my $response=$ua->request($request);
1802:
1.944 foxr 1803: if (wantarray) {
1804: return ($response->content, $response);
1805: } else {
1806: return $response->content;
1.942 foxr 1807: }
1.324 www 1808: }
1809:
1810: sub externalssi {
1811: my ($url)=@_;
1812: my $ua=new LWP::UserAgent;
1813: my $request=new HTTP::Request('GET',$url);
1814: my $response=$ua->request($request);
1.954 raeburn 1815: if (wantarray) {
1816: return ($response->content, $response);
1817: } else {
1818: return $response->content;
1819: }
1.15 www 1820: }
1.254 www 1821:
1.492 albertel 1822: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1823:
1824: sub allowuploaded {
1825: my ($srcurl,$url)=@_;
1826: $url=&clutter(&declutter($url));
1827: my $dir=$url;
1828: $dir=~s/\/[^\/]+$//;
1829: my %httpref=();
1830: my $httpurl=&hreflocation('',$url);
1831: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 1832: &Apache::lonnet::appenv(\%httpref);
1.254 www 1833: }
1.477 raeburn 1834:
1.478 albertel 1835: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1836: # input: action, courseID, current domain, intended
1.637 raeburn 1837: # path to file, source of file, instruction to parse file for objects,
1838: # ref to hash for embedded objects,
1839: # ref to hash for codebase of java objects.
1840: #
1.485 raeburn 1841: # output: url to file (if action was uploaddoc),
1842: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 1843: #
1.478 albertel 1844: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1845: # course.
1.477 raeburn 1846: #
1.478 albertel 1847: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1848: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1849: # course's home server.
1.477 raeburn 1850: #
1.478 albertel 1851: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1852: # be copied from $source (current location) to
1853: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1854: # and will then be copied to
1855: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1856: # course's home server.
1.485 raeburn 1857: #
1.481 raeburn 1858: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 1859: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 1860: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1861: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1862: # in course's home server.
1.637 raeburn 1863: #
1.477 raeburn 1864:
1865: sub process_coursefile {
1.638 albertel 1866: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 1867: my $fetchresult;
1.638 albertel 1868: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 1869: if ($action eq 'propagate') {
1.638 albertel 1870: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1871: $home);
1.481 raeburn 1872: } else {
1.477 raeburn 1873: my $fpath = '';
1874: my $fname = $file;
1.478 albertel 1875: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 1876: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 1877: my $filepath = &build_filepath($fpath);
1.481 raeburn 1878: if ($action eq 'copy') {
1879: if ($source eq '') {
1880: $fetchresult = 'no source file';
1881: return $fetchresult;
1882: } else {
1883: my $destination = $filepath.'/'.$fname;
1884: rename($source,$destination);
1885: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1886: $home);
1.481 raeburn 1887: }
1888: } elsif ($action eq 'uploaddoc') {
1889: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 1890: print $fh $env{'form.'.$source};
1.481 raeburn 1891: close($fh);
1.637 raeburn 1892: if ($parser eq 'parse') {
1.961 raeburn 1893: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637 raeburn 1894: unless ($parse_result eq 'ok') {
1895: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1896: }
1897: }
1.477 raeburn 1898: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1899: $home);
1.481 raeburn 1900: if ($fetchresult eq 'ok') {
1901: return '/uploaded/'.$fpath.'/'.$fname;
1902: } else {
1903: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1904: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 1905: return '/adm/notfound.html';
1906: }
1.477 raeburn 1907: }
1908: }
1.485 raeburn 1909: unless ( $fetchresult eq 'ok') {
1.477 raeburn 1910: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1911: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 1912: }
1913: return $fetchresult;
1914: }
1915:
1.637 raeburn 1916: sub build_filepath {
1917: my ($fpath) = @_;
1918: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1919: unless ($fpath eq '') {
1920: my @parts=split('/',$fpath);
1921: foreach my $part (@parts) {
1922: $filepath.= '/'.$part;
1923: if ((-e $filepath)!=1) {
1924: mkdir($filepath,0777);
1925: }
1926: }
1927: }
1928: return $filepath;
1929: }
1930:
1931: sub store_edited_file {
1.638 albertel 1932: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 1933: my $file = $primary_url;
1934: $file =~ s#^/uploaded/$docudom/$docuname/##;
1935: my $fpath = '';
1936: my $fname = $file;
1937: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1938: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1939: my $filepath = &build_filepath($fpath);
1940: open(my $fh,'>'.$filepath.'/'.$fname);
1941: print $fh $content;
1942: close($fh);
1.638 albertel 1943: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 1944: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1945: $home);
1.637 raeburn 1946: if ($$fetchresult eq 'ok') {
1947: return '/uploaded/'.$fpath.'/'.$fname;
1948: } else {
1.638 albertel 1949: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1950: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 1951: return '/adm/notfound.html';
1952: }
1953: }
1954:
1.531 albertel 1955: sub clean_filename {
1.831 albertel 1956: my ($fname,$args)=@_;
1.315 www 1957: # Replace Windows backslashes by forward slashes
1.257 www 1958: $fname=~s/\\/\//g;
1.831 albertel 1959: if (!$args->{'keep_path'}) {
1960: # Get rid of everything but the actual filename
1961: $fname=~s/^.*\/([^\/]+)$/$1/;
1962: }
1.315 www 1963: # Replace spaces by underscores
1964: $fname=~s/\s+/\_/g;
1965: # Replace all other weird characters by nothing
1.831 albertel 1966: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 1967: # Replace all .\d. sequences with _\d. so they no longer look like version
1968: # numbers
1969: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 1970: return $fname;
1971: }
1972:
1.608 albertel 1973: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 1974: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 1975: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 1976: # $coursedoc - if true up to the current course
1977: # if false
1978: # $subdir - directory in userfile to store the file into
1.858 raeburn 1979: # $parser - instruction to parse file for objects ($parser = parse)
1980: # $allfiles - reference to hash for embedded objects
1981: # $codebase - reference to hash for codebase of java objects
1982: # $desuname - username for permanent storage of uploaded file
1983: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 1984: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
1985: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858 raeburn 1986: #
1.686 albertel 1987: # output: url of file in userspace, or error: <message>
1988: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 1989:
1990:
1.531 albertel 1991: sub userfileupload {
1.860 raeburn 1992: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1993: $destudom,$thumbwidth,$thumbheight)=@_;
1.531 albertel 1994: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 1995: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 1996: $fname=&clean_filename($fname);
1.315 www 1997: # See if there is anything left
1.257 www 1998: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 1999: chop($env{'form.'.$formname});
1.523 raeburn 2000: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2001: my $now = time;
2002: my $filepath = 'tmp/helprequests/'.$now;
2003: my @parts=split(/\//,$filepath);
2004: my $fullpath = $perlvar{'lonDaemons'};
2005: for (my $i=0;$i<@parts;$i++) {
2006: $fullpath .= '/'.$parts[$i];
2007: if ((-e $fullpath)!=1) {
2008: mkdir($fullpath,0777);
2009: }
2010: }
2011: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2012: print $fh $env{'form.'.$formname};
1.523 raeburn 2013: close($fh);
1.741 raeburn 2014: return $fullpath.'/'.$fname;
2015: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2016: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2017: '_'.$env{'user.domain'}.'/pending';
2018: my @parts=split(/\//,$filepath);
2019: my $fullpath = $perlvar{'lonDaemons'};
2020: for (my $i=0;$i<@parts;$i++) {
2021: $fullpath .= '/'.$parts[$i];
2022: if ((-e $fullpath)!=1) {
2023: mkdir($fullpath,0777);
2024: }
2025: }
2026: open(my $fh,'>'.$fullpath.'/'.$fname);
2027: print $fh $env{'form.'.$formname};
2028: close($fh);
2029: return $fullpath.'/'.$fname;
1.523 raeburn 2030: }
1.719 banghart 2031:
1.258 www 2032: # Create the directory if not present
1.493 albertel 2033: $fname="$subdir/$fname";
1.259 www 2034: if ($coursedoc) {
1.638 albertel 2035: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2036: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2037: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2038: return &finishuserfileupload($docuname,$docudom,
2039: $formname,$fname,$parser,$allfiles,
1.860 raeburn 2040: $codebase,$thumbwidth,$thumbheight);
1.481 raeburn 2041: } else {
1.620 albertel 2042: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2043: return &process_coursefile('uploaddoc',$docuname,$docudom,
2044: $fname,$formname,$parser,
2045: $allfiles,$codebase);
1.481 raeburn 2046: }
1.719 banghart 2047: } elsif (defined($destuname)) {
2048: my $docuname=$destuname;
2049: my $docudom=$destudom;
1.860 raeburn 2050: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2051: $parser,$allfiles,$codebase,
2052: $thumbwidth,$thumbheight);
1.719 banghart 2053:
1.259 www 2054: } else {
1.638 albertel 2055: my $docuname=$env{'user.name'};
2056: my $docudom=$env{'user.domain'};
1.714 raeburn 2057: if (exists($env{'form.group'})) {
2058: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2059: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2060: }
1.860 raeburn 2061: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2062: $parser,$allfiles,$codebase,
2063: $thumbwidth,$thumbheight);
1.259 www 2064: }
1.271 www 2065: }
2066:
2067: sub finishuserfileupload {
1.860 raeburn 2068: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2069: $thumbwidth,$thumbheight) = @_;
1.477 raeburn 2070: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2071: my $filepath=$perlvar{'lonDocRoot'};
1.860 raeburn 2072: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2073: $file=$fname;
2074: if ($fname=~m|/|) {
2075: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2076: $path.=$fnamepath.'/';
2077: }
1.259 www 2078: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2079: my $count;
2080: for ($count=4;$count<=$#parts;$count++) {
2081: $filepath.="/$parts[$count]";
2082: if ((-e $filepath)!=1) {
2083: mkdir($filepath,0777);
2084: }
2085: }
2086: # Save the file
2087: {
1.701 albertel 2088: if (!open(FH,'>'.$filepath.'/'.$file)) {
2089: &logthis('Failed to create '.$filepath.'/'.$file);
2090: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2091: return '/adm/notfound.html';
2092: }
2093: if (!print FH ($env{'form.'.$formname})) {
2094: &logthis('Failed to write to '.$filepath.'/'.$file);
2095: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2096: return '/adm/notfound.html';
2097: }
1.570 albertel 2098: close(FH);
1.258 www 2099: }
1.637 raeburn 2100: if ($parser eq 'parse') {
1.961 raeburn 2101: my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638 albertel 2102: $codebase);
1.637 raeburn 2103: unless ($parse_result eq 'ok') {
1.638 albertel 2104: &logthis('Failed to parse '.$filepath.$file.
2105: ' for embedded media: '.$parse_result);
1.637 raeburn 2106: }
2107: }
1.860 raeburn 2108: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2109: my $input = $filepath.'/'.$file;
2110: my $output = $filepath.'/'.'tn-'.$file;
2111: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2112: system("convert -sample $thumbsize $input $output");
2113: if (-e $filepath.'/'.'tn-'.$file) {
2114: $fetchthumb = 1;
2115: }
2116: }
1.858 raeburn 2117:
1.259 www 2118: # Notify homeserver to grep it
2119: #
1.638 albertel 2120: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2121: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2122: if ($fetchresult eq 'ok') {
1.860 raeburn 2123: if ($fetchthumb) {
2124: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2125: if ($thumbresult ne 'ok') {
2126: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2127: $docuhome.': '.$thumbresult);
2128: }
2129: }
1.259 www 2130: #
1.258 www 2131: # Return the URL to it
1.494 albertel 2132: return '/uploaded/'.$path.$file;
1.263 www 2133: } else {
1.494 albertel 2134: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2135: ': '.$fetchresult);
1.263 www 2136: return '/adm/notfound.html';
1.858 raeburn 2137: }
1.493 albertel 2138: }
2139:
1.637 raeburn 2140: sub extract_embedded_items {
1.961 raeburn 2141: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2142: my @state = ();
2143: my %javafiles = (
2144: codebase => '',
2145: code => '',
2146: archive => ''
2147: );
2148: my %mediafiles = (
2149: src => '',
2150: movie => '',
2151: );
1.648 raeburn 2152: my $p;
2153: if ($content) {
2154: $p = HTML::LCParser->new($content);
2155: } else {
1.961 raeburn 2156: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2157: }
1.641 albertel 2158: while (my $t=$p->get_token()) {
1.640 albertel 2159: if ($t->[0] eq 'S') {
2160: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2161: push(@state, $tagname);
1.648 raeburn 2162: if (lc($tagname) eq 'allow') {
2163: &add_filetype($allfiles,$attr->{'src'},'src');
2164: }
1.640 albertel 2165: if (lc($tagname) eq 'img') {
2166: &add_filetype($allfiles,$attr->{'src'},'src');
2167: }
1.886 albertel 2168: if (lc($tagname) eq 'a') {
2169: &add_filetype($allfiles,$attr->{'href'},'href');
2170: }
1.645 raeburn 2171: if (lc($tagname) eq 'script') {
2172: if ($attr->{'archive'} =~ /\.jar$/i) {
2173: &add_filetype($allfiles,$attr->{'archive'},'archive');
2174: } else {
2175: &add_filetype($allfiles,$attr->{'src'},'src');
2176: }
2177: }
2178: if (lc($tagname) eq 'link') {
2179: if (lc($attr->{'rel'}) eq 'stylesheet') {
2180: &add_filetype($allfiles,$attr->{'href'},'href');
2181: }
2182: }
1.640 albertel 2183: if (lc($tagname) eq 'object' ||
2184: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2185: foreach my $item (keys(%javafiles)) {
2186: $javafiles{$item} = '';
2187: }
2188: }
2189: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2190: my $name = lc($attr->{'name'});
2191: foreach my $item (keys(%javafiles)) {
2192: if ($name eq $item) {
2193: $javafiles{$item} = $attr->{'value'};
2194: last;
2195: }
2196: }
2197: foreach my $item (keys(%mediafiles)) {
2198: if ($name eq $item) {
2199: &add_filetype($allfiles, $attr->{'value'}, 'value');
2200: last;
2201: }
2202: }
2203: }
2204: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2205: foreach my $item (keys(%javafiles)) {
2206: if ($attr->{$item}) {
2207: $javafiles{$item} = $attr->{$item};
2208: last;
2209: }
2210: }
2211: foreach my $item (keys(%mediafiles)) {
2212: if ($attr->{$item}) {
2213: &add_filetype($allfiles,$attr->{$item},$item);
2214: last;
2215: }
2216: }
2217: }
2218: } elsif ($t->[0] eq 'E') {
2219: my ($tagname) = ($t->[1]);
2220: if ($javafiles{'codebase'} ne '') {
2221: $javafiles{'codebase'} .= '/';
2222: }
2223: if (lc($tagname) eq 'applet' ||
2224: lc($tagname) eq 'object' ||
2225: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2226: ) {
2227: foreach my $item (keys(%javafiles)) {
2228: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2229: my $file=$javafiles{'codebase'}.$javafiles{$item};
2230: &add_filetype($allfiles,$file,$item);
2231: }
2232: }
2233: }
2234: pop @state;
2235: }
2236: }
1.637 raeburn 2237: return 'ok';
2238: }
2239:
1.639 albertel 2240: sub add_filetype {
2241: my ($allfiles,$file,$type)=@_;
2242: if (exists($allfiles->{$file})) {
2243: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2244: push(@{$allfiles->{$file}}, &escape($type));
2245: }
2246: } else {
2247: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2248: }
2249: }
2250:
1.493 albertel 2251: sub removeuploadedurl {
2252: my ($url)=@_;
2253: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2254: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2255: }
2256:
2257: sub removeuserfile {
2258: my ($docuname,$docudom,$fname)=@_;
2259: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2260: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
2261: if ($result eq 'ok') {
2262: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2263: my $metafile = $fname.'.meta';
2264: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2265: my $url = "/uploaded/$docudom/$docuname/$fname";
2266: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2267: my $sqlresult =
1.823 albertel 2268: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2269: 'portfolio_metadata',$group,
2270: 'delete');
1.798 raeburn 2271: }
2272: }
2273: return $result;
1.257 www 2274: }
1.15 www 2275:
1.530 albertel 2276: sub mkdiruserfile {
2277: my ($docuname,$docudom,$dir)=@_;
2278: my $home=&homeserver($docuname,$docudom);
2279: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2280: }
2281:
1.531 albertel 2282: sub renameuserfile {
2283: my ($docuname,$docudom,$old,$new)=@_;
2284: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2285: my $result = &reply("renameuserfile:$docudom:$docuname:".
2286: &escape("$old").':'.&escape("$new"),$home);
2287: if ($result eq 'ok') {
2288: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2289: my $oldmeta = $old.'.meta';
2290: my $newmeta = $new.'.meta';
2291: my $metaresult =
2292: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2293: my $url = "/uploaded/$docudom/$docuname/$old";
2294: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2295: my $sqlresult =
1.823 albertel 2296: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2297: 'portfolio_metadata',$group,
2298: 'delete');
1.798 raeburn 2299: }
2300: }
2301: return $result;
1.531 albertel 2302: }
2303:
1.14 www 2304: # ------------------------------------------------------------------------- Log
2305:
2306: sub log {
2307: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2308: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2309: }
2310:
2311: # ------------------------------------------------------------------ Course Log
1.352 www 2312: #
2313: # This routine flushes several buffers of non-mission-critical nature
2314: #
1.157 www 2315:
2316: sub flushcourselogs {
1.352 www 2317: &logthis('Flushing log buffers');
2318: #
2319: # course logs
2320: # This is a log of all transactions in a course, which can be used
2321: # for data mining purposes
2322: #
2323: # It also collects the courseid database, which lists last transaction
2324: # times and course titles for all courseids
2325: #
2326: my %courseidbuffer=();
1.921 raeburn 2327: foreach my $crsid (keys(%courselogs)) {
1.352 www 2328: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2329: &escape($courselogs{$crsid}),
2330: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2331: delete $courselogs{$crsid};
2332: } else {
2333: &logthis('Failed to flush log buffer for '.$crsid);
2334: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2335: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2336: " exceeded maximum size, deleting.</font>");
2337: delete $courselogs{$crsid};
2338: }
1.352 www 2339: }
1.920 raeburn 2340: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2341: 'description' => $coursedescrbuf{$crsid},
2342: 'inst_code' => $courseinstcodebuf{$crsid},
2343: 'type' => $coursetypebuf{$crsid},
2344: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2345: };
1.191 harris41 2346: }
1.352 www 2347: #
2348: # Write course id database (reverse lookup) to homeserver of courses
2349: # Is used in pickcourse
2350: #
1.840 albertel 2351: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2352: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2353: $courseidbuffer{$crs_home},
2354: $crs_home,'timeonly');
1.352 www 2355: }
2356: #
2357: # File accesses
2358: # Writes to the dynamic metadata of resources to get hit counts, etc.
2359: #
1.449 matthew 2360: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2361: if ($entry =~ /___count$/) {
2362: my ($dom,$name);
1.807 albertel 2363: ($dom,$name,undef)=
1.811 albertel 2364: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2365: if (! defined($dom) || $dom eq '' ||
2366: ! defined($name) || $name eq '') {
1.620 albertel 2367: my $cid = $env{'request.course.id'};
2368: $dom = $env{'request.'.$cid.'.domain'};
2369: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2370: }
1.450 matthew 2371: my $value = $accesshash{$entry};
2372: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2373: my %temphash=($url => $value);
1.449 matthew 2374: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2375: if ($result eq 'ok') {
2376: delete $accesshash{$entry};
2377: } elsif ($result eq 'unknown_cmd') {
2378: # Target server has old code running on it.
1.450 matthew 2379: my %temphash=($entry => $value);
1.449 matthew 2380: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2381: delete $accesshash{$entry};
2382: }
2383: }
2384: } else {
1.811 albertel 2385: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2386: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2387: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2388: delete $accesshash{$entry};
2389: }
1.185 www 2390: }
1.191 harris41 2391: }
1.352 www 2392: #
2393: # Roles
2394: # Reverse lookup of user roles for course faculty/staff and co-authorship
2395: #
1.800 albertel 2396: foreach my $entry (keys(%userrolehash)) {
1.351 www 2397: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2398: split(/\:/,$entry);
2399: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2400: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2401: $rudom,$runame) eq 'ok') {
2402: delete $userrolehash{$entry};
2403: }
2404: }
1.662 raeburn 2405: #
2406: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2407: #
2408: my %domrolebuffer = ();
2409: foreach my $entry (keys %domainrolehash) {
1.901 albertel 2410: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2411: if ($domrolebuffer{$rudom}) {
2412: $domrolebuffer{$rudom}.='&'.&escape($entry).
2413: '='.&escape($domainrolehash{$entry});
2414: } else {
2415: $domrolebuffer{$rudom}.=&escape($entry).
2416: '='.&escape($domainrolehash{$entry});
2417: }
2418: delete $domainrolehash{$entry};
2419: }
2420: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2421: my %servers = &get_servers($dom,'library');
2422: foreach my $tryserver (keys(%servers)) {
2423: unless (&reply('domroleput:'.$dom.':'.
2424: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2425: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2426: }
1.662 raeburn 2427: }
2428: }
1.186 www 2429: $dumpcount++;
1.157 www 2430: }
2431:
2432: sub courselog {
2433: my $what=shift;
1.158 www 2434: $what=time.':'.$what;
1.620 albertel 2435: unless ($env{'request.course.id'}) { return ''; }
2436: $coursedombuf{$env{'request.course.id'}}=
2437: $env{'course.'.$env{'request.course.id'}.'.domain'};
2438: $coursenumbuf{$env{'request.course.id'}}=
2439: $env{'course.'.$env{'request.course.id'}.'.num'};
2440: $coursehombuf{$env{'request.course.id'}}=
2441: $env{'course.'.$env{'request.course.id'}.'.home'};
2442: $coursedescrbuf{$env{'request.course.id'}}=
2443: $env{'course.'.$env{'request.course.id'}.'.description'};
2444: $courseinstcodebuf{$env{'request.course.id'}}=
2445: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2446: $courseownerbuf{$env{'request.course.id'}}=
2447: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2448: $coursetypebuf{$env{'request.course.id'}}=
2449: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2450: if (defined $courselogs{$env{'request.course.id'}}) {
2451: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2452: } else {
1.620 albertel 2453: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2454: }
1.620 albertel 2455: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2456: &flushcourselogs();
2457: }
1.158 www 2458: }
2459:
2460: sub courseacclog {
2461: my $fnsymb=shift;
1.620 albertel 2462: unless ($env{'request.course.id'}) { return ''; }
2463: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2464: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2465: $what.=':POST';
1.583 matthew 2466: # FIXME: Probably ought to escape things....
1.800 albertel 2467: foreach my $key (keys(%env)) {
2468: if ($key=~/^form\.(.*)/) {
2469: $what.=':'.$1.'='.$env{$key};
1.158 www 2470: }
1.191 harris41 2471: }
1.583 matthew 2472: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2473: # FIXME: We should not be depending on a form parameter that someone
2474: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2475: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2476: $what.= ':POST';
2477: # FIXME: Probably ought to escape things....
2478: foreach my $element ('courseexp','crsfulltext','crsrelated',
2479: 'crsdiscuss') {
1.620 albertel 2480: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2481: }
2482: }
1.158 www 2483: }
2484: &courselog($what);
1.149 www 2485: }
2486:
1.185 www 2487: sub countacc {
2488: my $url=&declutter(shift);
1.458 matthew 2489: return if (! defined($url) || $url eq '');
1.620 albertel 2490: unless ($env{'request.course.id'}) { return ''; }
2491: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2492: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2493: $accesshash{$key}++;
1.185 www 2494: }
1.349 www 2495:
1.361 www 2496: sub linklog {
2497: my ($from,$to)=@_;
2498: $from=&declutter($from);
2499: $to=&declutter($to);
2500: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2501: $accesshash{$to.'___'.$from.'___goto'}=1;
2502: }
2503:
1.349 www 2504: sub userrolelog {
2505: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2506: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2507: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2508: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2509: ($trole=~/^ta/)) {
1.350 www 2510: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2511: $userrolehash
2512: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2513: =$tend.':'.$tstart;
1.662 raeburn 2514: }
1.898 albertel 2515: if (($env{'request.role'} =~ /dc\./) &&
2516: (($trole=~/^au/) || ($trole=~/^in/) ||
2517: ($trole=~/^cc/) || ($trole=~/^ep/) ||
2518: ($trole=~/^cr/) || ($trole=~/^ta/))) {
2519: $userrolehash
2520: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2521: =$tend.':'.$tstart;
2522: }
1.662 raeburn 2523: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2524: ($trole=~/^li/) || ($trole=~/^li/) ||
2525: ($trole=~/^au/) || ($trole=~/^dg/) ||
2526: ($trole=~/^sc/)) {
2527: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2528: $domainrolehash
2529: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2530: = $tend.':'.$tstart;
2531: }
1.351 www 2532: }
2533:
1.957 raeburn 2534: sub courserolelog {
2535: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2536: if (($trole eq 'cc') || ($trole eq 'in') ||
2537: ($trole eq 'ep') || ($trole eq 'ad') ||
2538: ($trole eq 'ta') || ($trole eq 'st') ||
2539: ($trole=~/^cr/) || ($trole eq 'gr')) {
2540: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2541: my $cdom = $1;
2542: my $cnum = $2;
2543: my $sec = $3;
2544: my $namespace = 'rolelog';
2545: my %storehash = (
2546: role => $trole,
2547: start => $tstart,
2548: end => $tend,
2549: selfenroll => $selfenroll,
2550: context => $context,
2551: );
2552: if ($trole eq 'gr') {
2553: $namespace = 'groupslog';
2554: $storehash{'group'} = $sec;
2555: } else {
2556: $storehash{'section'} = $sec;
2557: }
2558: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
2559: }
2560: }
2561: return;
2562: }
2563:
1.351 www 2564: sub get_course_adv_roles {
1.948 raeburn 2565: my ($cid,$codes) = @_;
1.620 albertel 2566: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2567: my %coursehash=&coursedescription($cid);
1.470 www 2568: my %nothide=();
1.800 albertel 2569: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2570: if ($user !~ /:/) {
2571: $nothide{join(':',split(/[\@]/,$user))}=1;
2572: } else {
2573: $nothide{$user}=1;
2574: }
1.470 www 2575: }
1.351 www 2576: my %returnhash=();
2577: my %dumphash=
2578: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2579: my $now=time;
1.800 albertel 2580: foreach my $entry (keys %dumphash) {
2581: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2582: if (($tstart) && ($tstart<0)) { next; }
2583: if (($tend) && ($tend<$now)) { next; }
2584: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2585: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2586: if ($username eq '' || $domain eq '') { next; }
1.470 www 2587: if ((&privileged($username,$domain)) &&
2588: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2589: if ($role eq 'cr') { next; }
1.948 raeburn 2590: if ($codes) {
2591: if ($section) { $role .= ':'.$section; }
2592: if ($returnhash{$role}) {
2593: $returnhash{$role}.=','.$username.':'.$domain;
2594: } else {
2595: $returnhash{$role}=$username.':'.$domain;
2596: }
1.351 www 2597: } else {
1.948 raeburn 2598: my $key=&plaintext($role);
2599: if ($section) { $key.=' (Section '.$section.')'; }
2600: if ($returnhash{$key}) {
2601: $returnhash{$key}.=','.$username.':'.$domain;
2602: } else {
2603: $returnhash{$key}=$username.':'.$domain;
2604: }
1.351 www 2605: }
1.948 raeburn 2606: }
1.400 www 2607: return %returnhash;
2608: }
2609:
2610: sub get_my_roles {
1.937 raeburn 2611: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 2612: unless (defined($uname)) { $uname=$env{'user.name'}; }
2613: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 2614: my (%dumphash,%nothide);
1.858 raeburn 2615: if ($context eq 'userroles') {
2616: %dumphash = &dump('roles',$udom,$uname);
2617: } else {
2618: %dumphash=
1.400 www 2619: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 2620: if ($hidepriv) {
2621: my %coursehash=&coursedescription($udom.'_'.$uname);
2622: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2623: if ($user !~ /:/) {
2624: $nothide{join(':',split(/[\@]/,$user))} = 1;
2625: } else {
2626: $nothide{$user} = 1;
2627: }
2628: }
2629: }
1.858 raeburn 2630: }
1.400 www 2631: my %returnhash=();
2632: my $now=time;
1.800 albertel 2633: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2634: my ($role,$tend,$tstart);
2635: if ($context eq 'userroles') {
2636: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2637: } else {
2638: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2639: }
1.400 www 2640: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2641: my $status = 'active';
1.939 raeburn 2642: if (($tend) && ($tend<=$now)) {
1.832 raeburn 2643: $status = 'previous';
2644: }
2645: if (($tstart) && ($now<$tstart)) {
2646: $status = 'future';
2647: }
2648: if (ref($types) eq 'ARRAY') {
2649: if (!grep(/^\Q$status\E$/,@{$types})) {
2650: next;
2651: }
2652: } else {
2653: if ($status ne 'active') {
2654: next;
2655: }
2656: }
1.867 raeburn 2657: my ($rolecode,$username,$domain,$section,$area);
2658: if ($context eq 'userroles') {
2659: ($area,$rolecode) = split(/_/,$entry);
2660: (undef,$domain,$username,$section) = split(/\//,$area);
2661: } else {
2662: ($role,$username,$domain,$section) = split(/\:/,$entry);
2663: }
1.832 raeburn 2664: if (ref($roledoms) eq 'ARRAY') {
2665: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2666: next;
2667: }
2668: }
2669: if (ref($roles) eq 'ARRAY') {
2670: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 2671: if ($role =~ /^cr\//) {
2672: if (!grep(/^cr$/,@{$roles})) {
2673: next;
2674: }
2675: } else {
2676: next;
2677: }
1.832 raeburn 2678: }
1.867 raeburn 2679: }
1.937 raeburn 2680: if ($hidepriv) {
2681: if ((&privileged($username,$domain)) &&
2682: (!$nothide{$username.':'.$domain})) {
2683: next;
2684: }
2685: }
1.933 raeburn 2686: if ($withsec) {
2687: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2688: $tstart.':'.$tend;
2689: } else {
2690: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2691: }
1.832 raeburn 2692: }
1.373 www 2693: return %returnhash;
1.399 www 2694: }
2695:
2696: # ----------------------------------------------------- Frontpage Announcements
2697: #
2698: #
2699:
2700: sub postannounce {
2701: my ($server,$text)=@_;
1.844 albertel 2702: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2703: unless ($text=~/\w/) { $text=''; }
2704: return &reply('setannounce:'.&escape($text),$server);
2705: }
2706:
2707: sub getannounce {
1.448 albertel 2708:
2709: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 2710: my $announcement='';
1.800 albertel 2711: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 2712: close($fh);
1.399 www 2713: if ($announcement=~/\w/) {
2714: return
2715: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 2716: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 2717: } else {
2718: return '';
2719: }
2720: } else {
2721: return '';
2722: }
1.351 www 2723: }
1.353 www 2724:
2725: # ---------------------------------------------------------- Course ID routines
2726: # Deal with domain's nohist_courseid.db files
2727: #
2728:
2729: sub courseidput {
1.921 raeburn 2730: my ($domain,$storehash,$coursehome,$caller) = @_;
2731: my $outcome;
2732: if ($caller eq 'timeonly') {
2733: my $cids = '';
2734: foreach my $item (keys(%$storehash)) {
2735: $cids.=&escape($item).'&';
2736: }
2737: $cids=~s/\&$//;
2738: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
2739: $coursehome);
2740: } else {
2741: my $items = '';
2742: foreach my $item (keys(%$storehash)) {
2743: $items.= &escape($item).'='.
2744: &freeze_escape($$storehash{$item}).'&';
2745: }
2746: $items=~s/\&$//;
2747: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
2748: $coursehome);
1.918 raeburn 2749: }
2750: if ($outcome eq 'unknown_cmd') {
2751: my $what;
2752: foreach my $cid (keys(%$storehash)) {
2753: $what .= &escape($cid).'=';
1.921 raeburn 2754: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 2755: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 2756: }
2757: $what =~ s/\:$/&/;
2758: }
2759: $what =~ s/\&$//;
2760: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2761: } else {
2762: return $outcome;
2763: }
1.353 www 2764: }
2765:
2766: sub courseiddump {
1.921 raeburn 2767: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 2768: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962 ! raeburn 2769: $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918 raeburn 2770: my $as_hash = 1;
2771: my %returnhash;
2772: if (!$domfilter) { $domfilter=''; }
1.845 albertel 2773: my %libserv = &all_library();
2774: foreach my $tryserver (keys(%libserv)) {
2775: if ( ( $hostidflag == 1
2776: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
2777: || (!defined($hostidflag)) ) {
2778:
1.918 raeburn 2779: if (($domfilter eq '') ||
2780: (&host_domain($tryserver) eq $domfilter)) {
2781: my $rep =
2782: &reply('courseiddump:'.&host_domain($tryserver).':'.
2783: $sincefilter.':'.&escape($descfilter).':'.
2784: &escape($instcodefilter).':'.&escape($ownerfilter).
2785: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 2786: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 ! raeburn 2787: &escape($selfenrollonly).':'.&escape($catfilter).':'.
! 2788: $showhidden.':'.$caller,$tryserver);
1.918 raeburn 2789: my @pairs=split(/\&/,$rep);
2790: foreach my $item (@pairs) {
2791: my ($key,$value)=split(/\=/,$item,2);
2792: $key = &unescape($key);
2793: next if ($key =~ /^error: 2 /);
2794: my $result = &thaw_unescape($value);
2795: if (ref($result) eq 'HASH') {
2796: $returnhash{$key}=$result;
2797: } else {
1.921 raeburn 2798: my @responses = split(/:/,$value);
2799: my @items = ('description','inst_code','owner','type');
1.918 raeburn 2800: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 2801: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 2802: }
2803: }
1.353 www 2804: }
2805: }
2806: }
2807: }
2808: return %returnhash;
2809: }
2810:
1.658 raeburn 2811: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 2812:
2813: sub dcmailput {
1.685 raeburn 2814: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 2815: my $status = &Apache::lonnet::critical(
1.740 www 2816: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2817: &escape($message),$server);
1.662 raeburn 2818: return $status;
2819: }
2820:
1.658 raeburn 2821: sub dcmaildump {
2822: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 2823: my %returnhash=();
1.846 albertel 2824:
2825: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 2826: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2827: &escape($enddate).':';
2828: my @esc_senders=map { &escape($_)} @$senders;
2829: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 2830: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 2831: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 2832: if (($key) && ($value)) {
2833: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 2834: }
2835: }
2836: }
2837: return %returnhash;
2838: }
1.662 raeburn 2839: # ---------------------------------------------------------- Domain roles
2840:
2841: sub get_domain_roles {
2842: my ($dom,$roles,$startdate,$enddate)=@_;
2843: if (undef($startdate) || $startdate eq '') {
2844: $startdate = '.';
2845: }
2846: if (undef($enddate) || $enddate eq '') {
2847: $enddate = '.';
2848: }
1.922 raeburn 2849: my $rolelist;
2850: if (ref($roles) eq 'ARRAY') {
2851: $rolelist = join(':',@{$roles});
2852: }
1.662 raeburn 2853: my %personnel = ();
1.841 albertel 2854:
2855: my %servers = &get_servers($dom,'library');
2856: foreach my $tryserver (keys(%servers)) {
2857: %{$personnel{$tryserver}}=();
2858: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
2859: &escape($startdate).':'.
2860: &escape($enddate).':'.
2861: &escape($rolelist), $tryserver))) {
2862: my ($key,$value) = split(/\=/,$line,2);
2863: if (($key) && ($value)) {
2864: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2865: }
2866: }
1.662 raeburn 2867: }
2868: return %personnel;
2869: }
1.658 raeburn 2870:
1.149 www 2871: # ----------------------------------------------------------- Check out an item
2872:
1.504 albertel 2873: sub get_first_access {
2874: my ($type,$argsymb)=@_;
1.790 albertel 2875: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2876: if ($argsymb) { $symb=$argsymb; }
2877: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 2878: if ($type eq 'course') {
2879: $res='course';
2880: } elsif ($type eq 'map') {
1.588 albertel 2881: $res=&symbread($map);
2882: } else {
2883: $res=$symb;
2884: }
2885: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2886: return $times{"$courseid\0$res"};
1.504 albertel 2887: }
2888:
2889: sub set_first_access {
2890: my ($type)=@_;
1.790 albertel 2891: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2892: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 2893: if ($type eq 'course') {
2894: $res='course';
2895: } elsif ($type eq 'map') {
1.588 albertel 2896: $res=&symbread($map);
2897: } else {
2898: $res=$symb;
2899: }
2900: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 2901: if (!$firstaccess) {
1.588 albertel 2902: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 2903: }
2904: return 'already_set';
1.504 albertel 2905: }
2906:
1.149 www 2907: sub checkout {
2908: my ($symb,$tuname,$tudom,$tcrsid)=@_;
2909: my $now=time;
2910: my $lonhost=$perlvar{'lonHostID'};
2911: my $infostr=&escape(
1.234 www 2912: 'CHECKOUTTOKEN&'.
1.149 www 2913: $tuname.'&'.
2914: $tudom.'&'.
2915: $tcrsid.'&'.
2916: $symb.'&'.
2917: $now.'&'.$ENV{'REMOTE_ADDR'});
2918: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 2919: if ($token=~/^error\:/) {
1.672 albertel 2920: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2921: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
2922: "</font>");
2923: return '';
2924: }
2925:
1.149 www 2926: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
2927: $token=~tr/a-z/A-Z/;
2928:
1.153 www 2929: my %infohash=('resource.0.outtoken' => $token,
2930: 'resource.0.checkouttime' => $now,
2931: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 2932:
2933: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2934: return '';
1.151 www 2935: } else {
1.672 albertel 2936: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2937: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
2938: "</font>");
1.149 www 2939: }
2940:
2941: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2942: &escape('Checkout '.$infostr.' - '.
2943: $token)) ne 'ok') {
2944: return '';
1.151 www 2945: } else {
1.672 albertel 2946: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2947: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
2948: "</font>");
1.149 www 2949: }
1.151 www 2950: return $token;
1.149 www 2951: }
2952:
2953: # ------------------------------------------------------------ Check in an item
2954:
2955: sub checkin {
2956: my $token=shift;
1.150 www 2957: my $now=time;
2958: my ($ta,$tb,$lonhost)=split(/\*/,$token);
2959: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 2960: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 2961: $dtoken=~s/\W/\_/g;
1.234 www 2962: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 2963: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
2964:
1.154 www 2965: unless (($tuname) && ($tudom)) {
2966: &logthis('Check in '.$token.' ('.$dtoken.') failed');
2967: return '';
2968: }
2969:
2970: unless (&allowed('mgr',$tcrsid)) {
2971: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 2972: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 2973: return '';
2974: }
2975:
1.153 www 2976: my %infohash=('resource.0.intoken' => $token,
2977: 'resource.0.checkintime' => $now,
2978: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 2979:
2980: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2981: return '';
2982: }
2983:
2984: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2985: &escape('Checkin - '.$token)) ne 'ok') {
2986: return '';
2987: }
2988:
2989: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 2990: }
2991:
2992: # --------------------------------------------- Set Expire Date for Spreadsheet
2993:
2994: sub expirespread {
2995: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 2996: my $cid=$env{'request.course.id'};
1.110 www 2997: if ($cid) {
2998: my $now=time;
2999: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3000: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3001: $env{'course.'.$cid.'.num'}.
1.110 www 3002: ':nohist_expirationdates:'.
3003: &escape($key).'='.$now,
1.620 albertel 3004: $env{'course.'.$cid.'.home'})
1.110 www 3005: }
3006: return 'ok';
1.14 www 3007: }
3008:
1.109 www 3009: # ----------------------------------------------------- Devalidate Spreadsheets
3010:
3011: sub devalidate {
1.325 www 3012: my ($symb,$uname,$udom)=@_;
1.620 albertel 3013: my $cid=$env{'request.course.id'};
1.109 www 3014: if ($cid) {
1.391 matthew 3015: # delete the stored spreadsheets for
3016: # - the student level sheet of this user in course's homespace
3017: # - the assessment level sheet for this resource
3018: # for this user in user's homespace
1.553 albertel 3019: # - current conditional state info
1.325 www 3020: my $key=$uname.':'.$udom.':';
1.109 www 3021: my $status=
1.299 matthew 3022: &del('nohist_calculatedsheets',
1.391 matthew 3023: [$key.'studentcalc:'],
1.620 albertel 3024: $env{'course.'.$cid.'.domain'},
3025: $env{'course.'.$cid.'.num'})
1.133 albertel 3026: .' '.
3027: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3028: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3029: unless ($status eq 'ok ok') {
3030: &logthis('Could not devalidate spreadsheet '.
1.325 www 3031: $uname.' at '.$udom.' for '.
1.109 www 3032: $symb.': '.$status);
1.133 albertel 3033: }
1.553 albertel 3034: &delenv('user.state.'.$cid);
1.109 www 3035: }
3036: }
3037:
1.265 albertel 3038: sub get_scalar {
3039: my ($string,$end) = @_;
3040: my $value;
3041: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3042: $value = $1;
3043: } elsif ($$string =~ s/^([^&]*?)&//) {
3044: $value = $1;
3045: }
3046: return &unescape($value);
3047: }
3048:
3049: sub array2str {
3050: my (@array) = @_;
3051: my $result=&arrayref2str(\@array);
3052: $result=~s/^__ARRAY_REF__//;
3053: $result=~s/__END_ARRAY_REF__$//;
3054: return $result;
3055: }
3056:
1.204 albertel 3057: sub arrayref2str {
3058: my ($arrayref) = @_;
1.265 albertel 3059: my $result='__ARRAY_REF__';
1.204 albertel 3060: foreach my $elem (@$arrayref) {
1.265 albertel 3061: if(ref($elem) eq 'ARRAY') {
3062: $result.=&arrayref2str($elem).'&';
3063: } elsif(ref($elem) eq 'HASH') {
3064: $result.=&hashref2str($elem).'&';
3065: } elsif(ref($elem)) {
3066: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3067: } else {
3068: $result.=&escape($elem).'&';
3069: }
3070: }
3071: $result=~s/\&$//;
1.265 albertel 3072: $result .= '__END_ARRAY_REF__';
1.204 albertel 3073: return $result;
3074: }
3075:
1.168 albertel 3076: sub hash2str {
1.204 albertel 3077: my (%hash) = @_;
3078: my $result=&hashref2str(\%hash);
1.265 albertel 3079: $result=~s/^__HASH_REF__//;
3080: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3081: return $result;
3082: }
3083:
3084: sub hashref2str {
3085: my ($hashref)=@_;
1.265 albertel 3086: my $result='__HASH_REF__';
1.800 albertel 3087: foreach my $key (sort(keys(%$hashref))) {
3088: if (ref($key) eq 'ARRAY') {
3089: $result.=&arrayref2str($key).'=';
3090: } elsif (ref($key) eq 'HASH') {
3091: $result.=&hashref2str($key).'=';
3092: } elsif (ref($key)) {
1.265 albertel 3093: $result.='=';
1.800 albertel 3094: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3095: } else {
1.800 albertel 3096: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3097: }
3098:
1.800 albertel 3099: if(ref($hashref->{$key}) eq 'ARRAY') {
3100: $result.=&arrayref2str($hashref->{$key}).'&';
3101: } elsif(ref($hashref->{$key}) eq 'HASH') {
3102: $result.=&hashref2str($hashref->{$key}).'&';
3103: } elsif(ref($hashref->{$key})) {
1.265 albertel 3104: $result.='&';
1.800 albertel 3105: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3106: } else {
1.800 albertel 3107: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3108: }
3109: }
1.168 albertel 3110: $result=~s/\&$//;
1.265 albertel 3111: $result .= '__END_HASH_REF__';
1.168 albertel 3112: return $result;
3113: }
3114:
3115: sub str2hash {
1.265 albertel 3116: my ($string)=@_;
3117: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3118: return %$hash;
3119: }
3120:
3121: sub str2hashref {
1.168 albertel 3122: my ($string) = @_;
1.265 albertel 3123:
3124: my %hash;
3125:
3126: if($string !~ /^__HASH_REF__/) {
3127: if (! ($string eq '' || !defined($string))) {
3128: $hash{'error'}='Not hash reference';
3129: }
3130: return (\%hash, $string);
3131: }
3132:
3133: $string =~ s/^__HASH_REF__//;
3134:
3135: while($string !~ /^__END_HASH_REF__/) {
3136: #key
3137: my $key='';
3138: if($string =~ /^__HASH_REF__/) {
3139: ($key, $string)=&str2hashref($string);
3140: if(defined($key->{'error'})) {
3141: $hash{'error'}='Bad data';
3142: return (\%hash, $string);
3143: }
3144: } elsif($string =~ /^__ARRAY_REF__/) {
3145: ($key, $string)=&str2arrayref($string);
3146: if($key->[0] eq 'Array reference error') {
3147: $hash{'error'}='Bad data';
3148: return (\%hash, $string);
3149: }
3150: } else {
3151: $string =~ s/^(.*?)=//;
1.267 albertel 3152: $key=&unescape($1);
1.265 albertel 3153: }
3154: $string =~ s/^=//;
3155:
3156: #value
3157: my $value='';
3158: if($string =~ /^__HASH_REF__/) {
3159: ($value, $string)=&str2hashref($string);
3160: if(defined($value->{'error'})) {
3161: $hash{'error'}='Bad data';
3162: return (\%hash, $string);
3163: }
3164: } elsif($string =~ /^__ARRAY_REF__/) {
3165: ($value, $string)=&str2arrayref($string);
3166: if($value->[0] eq 'Array reference error') {
3167: $hash{'error'}='Bad data';
3168: return (\%hash, $string);
3169: }
3170: } else {
3171: $value=&get_scalar(\$string,'__END_HASH_REF__');
3172: }
3173: $string =~ s/^&//;
3174:
3175: $hash{$key}=$value;
1.204 albertel 3176: }
1.265 albertel 3177:
3178: $string =~ s/^__END_HASH_REF__//;
3179:
3180: return (\%hash, $string);
1.204 albertel 3181: }
3182:
3183: sub str2array {
1.265 albertel 3184: my ($string)=@_;
3185: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3186: return @$array;
3187: }
3188:
3189: sub str2arrayref {
1.204 albertel 3190: my ($string) = @_;
1.265 albertel 3191: my @array;
3192:
3193: if($string !~ /^__ARRAY_REF__/) {
3194: if (! ($string eq '' || !defined($string))) {
3195: $array[0]='Array reference error';
3196: }
3197: return (\@array, $string);
3198: }
3199:
3200: $string =~ s/^__ARRAY_REF__//;
3201:
3202: while($string !~ /^__END_ARRAY_REF__/) {
3203: my $value='';
3204: if($string =~ /^__HASH_REF__/) {
3205: ($value, $string)=&str2hashref($string);
3206: if(defined($value->{'error'})) {
3207: $array[0] ='Array reference error';
3208: return (\@array, $string);
3209: }
3210: } elsif($string =~ /^__ARRAY_REF__/) {
3211: ($value, $string)=&str2arrayref($string);
3212: if($value->[0] eq 'Array reference error') {
3213: $array[0] ='Array reference error';
3214: return (\@array, $string);
3215: }
3216: } else {
3217: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3218: }
3219: $string =~ s/^&//;
3220:
3221: push(@array, $value);
1.191 harris41 3222: }
1.265 albertel 3223:
3224: $string =~ s/^__END_ARRAY_REF__//;
3225:
3226: return (\@array, $string);
1.168 albertel 3227: }
3228:
1.167 albertel 3229: # -------------------------------------------------------------------Temp Store
3230:
1.168 albertel 3231: sub tmpreset {
3232: my ($symb,$namespace,$domain,$stuname) = @_;
3233: if (!$symb) {
3234: $symb=&symbread();
1.620 albertel 3235: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3236: }
3237: $symb=escape($symb);
3238:
1.620 albertel 3239: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3240: $namespace=~s/\//\_/g;
3241: $namespace=~s/\W//g;
3242:
1.620 albertel 3243: if (!$domain) { $domain=$env{'user.domain'}; }
3244: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3245: if ($domain eq 'public' && $stuname eq 'public') {
3246: $stuname=$ENV{'REMOTE_ADDR'};
3247: }
1.168 albertel 3248: my $path=$perlvar{'lonDaemons'}.'/tmp';
3249: my %hash;
3250: if (tie(%hash,'GDBM_File',
3251: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3252: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3253: foreach my $key (keys %hash) {
1.180 albertel 3254: if ($key=~ /:$symb/) {
1.168 albertel 3255: delete($hash{$key});
3256: }
3257: }
3258: }
3259: }
3260:
1.167 albertel 3261: sub tmpstore {
1.168 albertel 3262: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3263:
3264: if (!$symb) {
3265: $symb=&symbread();
1.620 albertel 3266: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3267: }
3268: $symb=escape($symb);
3269:
3270: if (!$namespace) {
3271: # I don't think we would ever want to store this for a course.
3272: # it seems this will only be used if we don't have a course.
1.620 albertel 3273: #$namespace=$env{'request.course.id'};
1.168 albertel 3274: #if (!$namespace) {
1.620 albertel 3275: $namespace=$env{'request.state'};
1.168 albertel 3276: #}
3277: }
3278: $namespace=~s/\//\_/g;
3279: $namespace=~s/\W//g;
1.620 albertel 3280: if (!$domain) { $domain=$env{'user.domain'}; }
3281: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3282: if ($domain eq 'public' && $stuname eq 'public') {
3283: $stuname=$ENV{'REMOTE_ADDR'};
3284: }
1.168 albertel 3285: my $now=time;
3286: my %hash;
3287: my $path=$perlvar{'lonDaemons'}.'/tmp';
3288: if (tie(%hash,'GDBM_File',
3289: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3290: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3291: $hash{"version:$symb"}++;
3292: my $version=$hash{"version:$symb"};
3293: my $allkeys='';
3294: foreach my $key (keys(%$storehash)) {
3295: $allkeys.=$key.':';
1.591 albertel 3296: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3297: }
3298: $hash{"$version:$symb:timestamp"}=$now;
3299: $allkeys.='timestamp';
3300: $hash{"$version:keys:$symb"}=$allkeys;
3301: if (untie(%hash)) {
3302: return 'ok';
3303: } else {
3304: return "error:$!";
3305: }
3306: } else {
3307: return "error:$!";
3308: }
3309: }
1.167 albertel 3310:
1.168 albertel 3311: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3312:
1.168 albertel 3313: sub tmprestore {
3314: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3315:
1.168 albertel 3316: if (!$symb) {
3317: $symb=&symbread();
1.620 albertel 3318: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3319: }
3320: $symb=escape($symb);
3321:
1.620 albertel 3322: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3323:
1.620 albertel 3324: if (!$domain) { $domain=$env{'user.domain'}; }
3325: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3326: if ($domain eq 'public' && $stuname eq 'public') {
3327: $stuname=$ENV{'REMOTE_ADDR'};
3328: }
1.168 albertel 3329: my %returnhash;
3330: $namespace=~s/\//\_/g;
3331: $namespace=~s/\W//g;
3332: my %hash;
3333: my $path=$perlvar{'lonDaemons'}.'/tmp';
3334: if (tie(%hash,'GDBM_File',
3335: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3336: &GDBM_READER(),0640)) {
1.168 albertel 3337: my $version=$hash{"version:$symb"};
3338: $returnhash{'version'}=$version;
3339: my $scope;
3340: for ($scope=1;$scope<=$version;$scope++) {
3341: my $vkeys=$hash{"$scope:keys:$symb"};
3342: my @keys=split(/:/,$vkeys);
3343: my $key;
3344: $returnhash{"$scope:keys"}=$vkeys;
3345: foreach $key (@keys) {
1.591 albertel 3346: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3347: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3348: }
3349: }
1.168 albertel 3350: if (!(untie(%hash))) {
3351: return "error:$!";
3352: }
3353: } else {
3354: return "error:$!";
3355: }
3356: return %returnhash;
1.167 albertel 3357: }
3358:
1.9 www 3359: # ----------------------------------------------------------------------- Store
3360:
3361: sub store {
1.124 www 3362: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3363: my $home='';
3364:
1.168 albertel 3365: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3366:
1.213 www 3367: $symb=&symbclean($symb);
1.122 albertel 3368: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3369:
1.620 albertel 3370: if (!$domain) { $domain=$env{'user.domain'}; }
3371: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3372:
3373: &devalidate($symb,$stuname,$domain);
1.109 www 3374:
3375: $symb=escape($symb);
1.187 www 3376: if (!$namespace) {
1.620 albertel 3377: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3378: return '';
3379: }
3380: }
1.620 albertel 3381: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3382:
3383: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3384: $$storehash{'host'}=$perlvar{'lonHostID'};
3385:
1.12 www 3386: my $namevalue='';
1.800 albertel 3387: foreach my $key (keys(%$storehash)) {
3388: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3389: }
1.12 www 3390: $namevalue=~s/\&$//;
1.187 www 3391: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3392: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3393: }
3394:
1.47 www 3395: # -------------------------------------------------------------- Critical Store
3396:
3397: sub cstore {
1.124 www 3398: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3399: my $home='';
3400:
1.168 albertel 3401: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3402:
1.213 www 3403: $symb=&symbclean($symb);
1.122 albertel 3404: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3405:
1.620 albertel 3406: if (!$domain) { $domain=$env{'user.domain'}; }
3407: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3408:
3409: &devalidate($symb,$stuname,$domain);
1.109 www 3410:
3411: $symb=escape($symb);
1.187 www 3412: if (!$namespace) {
1.620 albertel 3413: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3414: return '';
3415: }
3416: }
1.620 albertel 3417: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3418:
3419: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3420: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3421:
1.47 www 3422: my $namevalue='';
1.800 albertel 3423: foreach my $key (keys(%$storehash)) {
3424: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3425: }
1.47 www 3426: $namevalue=~s/\&$//;
1.187 www 3427: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3428: return critical
3429: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3430: }
3431:
1.9 www 3432: # --------------------------------------------------------------------- Restore
3433:
3434: sub restore {
1.124 www 3435: my ($symb,$namespace,$domain,$stuname) = @_;
3436: my $home='';
3437:
1.168 albertel 3438: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3439:
1.122 albertel 3440: if (!$symb) {
3441: unless ($symb=escape(&symbread())) { return ''; }
3442: } else {
1.213 www 3443: $symb=&escape(&symbclean($symb));
1.122 albertel 3444: }
1.188 www 3445: if (!$namespace) {
1.620 albertel 3446: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3447: return '';
3448: }
3449: }
1.620 albertel 3450: if (!$domain) { $domain=$env{'user.domain'}; }
3451: if (!$stuname) { $stuname=$env{'user.name'}; }
3452: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3453: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3454:
1.12 www 3455: my %returnhash=();
1.800 albertel 3456: foreach my $line (split(/\&/,$answer)) {
3457: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3458: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3459: }
1.75 www 3460: my $version;
3461: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3462: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3463: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3464: }
1.75 www 3465: }
1.13 www 3466: return %returnhash;
1.34 www 3467: }
3468:
3469: # ---------------------------------------------------------- Course Description
3470:
3471: sub coursedescription {
1.731 albertel 3472: my ($courseid,$args)=@_;
1.34 www 3473: $courseid=~s/^\///;
1.49 www 3474: $courseid=~s/\_/\//g;
1.34 www 3475: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3476: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3477: my $normalid=$cdomain.'_'.$cnum;
3478: # need to always cache even if we get errors otherwise we keep
3479: # trying and trying and trying to get the course description.
3480: my %envhash=();
3481: my %returnhash=();
1.731 albertel 3482:
3483: my $expiretime=600;
3484: if ($env{'request.course.id'} eq $normalid) {
3485: $expiretime=120;
3486: }
3487:
3488: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3489: if (!$args->{'freshen_cache'}
3490: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3491: foreach my $key (keys(%env)) {
3492: next if ($key !~ /^\Q$prefix\E(.*)/);
3493: my ($setting) = $1;
3494: $returnhash{$setting} = $env{$key};
3495: }
3496: return %returnhash;
3497: }
3498:
3499: # get the data agin
3500: if (!$args->{'one_time'}) {
3501: $envhash{'course.'.$normalid.'.last_cache'}=time;
3502: }
1.811 albertel 3503:
1.34 www 3504: if ($chome ne 'no_host') {
1.302 albertel 3505: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3506: if (!exists($returnhash{'con_lost'})) {
3507: $returnhash{'home'}= $chome;
3508: $returnhash{'domain'} = $cdomain;
3509: $returnhash{'num'} = $cnum;
1.741 raeburn 3510: if (!defined($returnhash{'type'})) {
3511: $returnhash{'type'} = 'Course';
3512: }
1.130 albertel 3513: while (my ($name,$value) = each %returnhash) {
1.53 www 3514: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3515: }
1.270 www 3516: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3517: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3518: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3519: $envhash{'course.'.$normalid.'.home'}=$chome;
3520: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3521: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3522: }
3523: }
1.731 albertel 3524: if (!$args->{'one_time'}) {
1.949 raeburn 3525: &appenv(\%envhash);
1.731 albertel 3526: }
1.302 albertel 3527: return %returnhash;
1.461 www 3528: }
3529:
3530: # -------------------------------------------------See if a user is privileged
3531:
3532: sub privileged {
3533: my ($username,$domain)=@_;
3534: my $rolesdump=&reply("dump:$domain:$username:roles",
3535: &homeserver($username,$domain));
3536: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
3537: my $now=time;
3538: if ($rolesdump ne '') {
1.800 albertel 3539: foreach my $entry (split(/&/,$rolesdump)) {
3540: if ($entry!~/^rolesdef_/) {
3541: my ($area,$role)=split(/=/,$entry);
1.461 www 3542: $area=~s/\_\w\w$//;
3543: my ($trole,$tend,$tstart)=split(/_/,$role);
3544: if (($trole eq 'dc') || ($trole eq 'su')) {
3545: my $active=1;
3546: if ($tend) {
3547: if ($tend<$now) { $active=0; }
3548: }
3549: if ($tstart) {
3550: if ($tstart>$now) { $active=0; }
3551: }
3552: if ($active) { return 1; }
3553: }
3554: }
3555: }
3556: }
3557: return 0;
1.9 www 3558: }
1.1 albertel 3559:
1.103 harris41 3560: # -------------------------------------------------------- Get user privileges
1.11 www 3561:
3562: sub rolesinit {
3563: my ($domain,$username,$authhost)=@_;
3564: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12 www 3565: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11 www 3566: my %allroles=();
1.678 raeburn 3567: my %allgroups=();
1.11 www 3568: my $now=time;
1.743 albertel 3569: my %userroles = ('user.login.time' => $now);
1.678 raeburn 3570: my $group_privs;
1.11 www 3571:
3572: if ($rolesdump ne '') {
1.800 albertel 3573: foreach my $entry (split(/&/,$rolesdump)) {
3574: if ($entry!~/^rolesdef_/) {
3575: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3576: $area=~s/\_\w\w$//;
1.678 raeburn 3577: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3578: if ($role=~/^cr/) {
1.807 albertel 3579: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3580: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3581: ($tend,$tstart)=split('_',$trest);
3582: } else {
3583: $trole=$role;
3584: }
1.678 raeburn 3585: } elsif ($role =~ m|^gr/|) {
3586: ($trole,$tend,$tstart) = split(/_/,$role);
3587: ($trole,$group_privs) = split(/\//,$trole);
3588: $group_privs = &unescape($group_privs);
1.587 albertel 3589: } else {
3590: ($trole,$tend,$tstart)=split(/_/,$role);
3591: }
1.743 albertel 3592: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3593: $username);
3594: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3595: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3596: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3597: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3598: my $spec=$trole.'.'.$area;
3599: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3600: if ($trole =~ /^cr\//) {
1.567 raeburn 3601: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3602: } elsif ($trole eq 'gr') {
3603: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3604: } else {
1.567 raeburn 3605: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3606: }
1.12 www 3607: }
1.662 raeburn 3608: }
1.191 harris41 3609: }
1.743 albertel 3610: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3611: $userroles{'user.adv'} = $adv;
3612: $userroles{'user.author'} = $author;
1.620 albertel 3613: $env{'user.adv'}=$adv;
1.11 www 3614: }
1.743 albertel 3615: return \%userroles;
1.11 www 3616: }
3617:
1.567 raeburn 3618: sub set_arearole {
3619: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3620: # log the associated role with the area
3621: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3622: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3623: }
3624:
3625: sub custom_roleprivs {
3626: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3627: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3628: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3629: if (&hostname($homsvr) ne '') {
1.567 raeburn 3630: my ($rdummy,$roledef)=
3631: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3632: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3633: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3634: if (defined($syspriv)) {
3635: $$allroles{'cm./'}.=':'.$syspriv;
3636: $$allroles{$spec.'./'}.=':'.$syspriv;
3637: }
3638: if ($tdomain ne '') {
3639: if (defined($dompriv)) {
3640: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3641: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3642: }
3643: if (($trest ne '') && (defined($coursepriv))) {
3644: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3645: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3646: }
3647: }
3648: }
3649: }
3650: }
3651:
1.678 raeburn 3652: sub group_roleprivs {
3653: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3654: my $access = 1;
3655: my $now = time;
3656: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3657: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3658: if ($access) {
1.811 albertel 3659: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3660: $$allgroups{$course}{$group} .=':'.$group_privs;
3661: }
3662: }
1.567 raeburn 3663:
3664: sub standard_roleprivs {
3665: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3666: if (defined($pr{$trole.':s'})) {
3667: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3668: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3669: }
3670: if ($tdomain ne '') {
3671: if (defined($pr{$trole.':d'})) {
3672: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3673: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3674: }
3675: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3676: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3677: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3678: }
3679: }
3680: }
3681:
3682: sub set_userprivs {
1.678 raeburn 3683: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 3684: my $author=0;
3685: my $adv=0;
1.678 raeburn 3686: my %grouproles = ();
3687: if (keys(%{$allgroups}) > 0) {
3688: foreach my $role (keys %{$allroles}) {
1.681 raeburn 3689: my ($trole,$area,$sec,$extendedarea);
1.881 raeburn 3690: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678 raeburn 3691: $trole = $1;
3692: $area = $2;
1.681 raeburn 3693: $sec = $3;
3694: $extendedarea = $area.$sec;
3695: if (exists($$allgroups{$area})) {
3696: foreach my $group (keys(%{$$allgroups{$area}})) {
3697: my $spec = $trole.'.'.$extendedarea;
3698: $grouproles{$spec.'.'.$area.'/'.$group} =
3699: $$allgroups{$area}{$group};
1.678 raeburn 3700: }
3701: }
3702: }
3703: }
3704: }
1.800 albertel 3705: foreach my $group (keys(%grouproles)) {
3706: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3707: }
1.800 albertel 3708: foreach my $role (keys(%{$allroles})) {
3709: my %thesepriv;
1.941 raeburn 3710: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 3711: foreach my $item (split(/:/,$$allroles{$role})) {
3712: if ($item ne '') {
3713: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3714: if ($restrictions eq '') {
3715: $thesepriv{$privilege}='F';
3716: } elsif ($thesepriv{$privilege} ne 'F') {
3717: $thesepriv{$privilege}.=$restrictions;
3718: }
3719: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3720: }
3721: }
3722: my $thesestr='';
1.800 albertel 3723: foreach my $priv (keys(%thesepriv)) {
3724: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3725: }
3726: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3727: }
3728: return ($author,$adv);
3729: }
3730:
1.12 www 3731: # --------------------------------------------------------------- get interface
3732:
3733: sub get {
1.131 albertel 3734: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3735: my $items='';
1.800 albertel 3736: foreach my $item (@$storearr) {
3737: $items.=&escape($item).'&';
1.191 harris41 3738: }
1.12 www 3739: $items=~s/\&$//;
1.620 albertel 3740: if (!$udomain) { $udomain=$env{'user.domain'}; }
3741: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 3742: my $uhome=&homeserver($uname,$udomain);
3743:
1.133 albertel 3744: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3745: my @pairs=split(/\&/,$rep);
1.273 albertel 3746: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
3747: return @pairs;
3748: }
1.15 www 3749: my %returnhash=();
1.42 www 3750: my $i=0;
1.800 albertel 3751: foreach my $item (@$storearr) {
3752: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3753: $i++;
1.191 harris41 3754: }
1.15 www 3755: return %returnhash;
1.27 www 3756: }
3757:
3758: # --------------------------------------------------------------- del interface
3759:
3760: sub del {
1.133 albertel 3761: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 3762: my $items='';
1.800 albertel 3763: foreach my $item (@$storearr) {
3764: $items.=&escape($item).'&';
1.191 harris41 3765: }
1.27 www 3766: $items=~s/\&$//;
1.620 albertel 3767: if (!$udomain) { $udomain=$env{'user.domain'}; }
3768: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3769: my $uhome=&homeserver($uname,$udomain);
3770:
3771: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3772: }
3773:
3774: # -------------------------------------------------------------- dump interface
3775:
3776: sub dump {
1.755 albertel 3777: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3778: if (!$udomain) { $udomain=$env{'user.domain'}; }
3779: if (!$uname) { $uname=$env{'user.name'}; }
3780: my $uhome=&homeserver($uname,$udomain);
3781: if ($regexp) {
3782: $regexp=&escape($regexp);
3783: } else {
3784: $regexp='.';
3785: }
3786: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3787: my @pairs=split(/\&/,$rep);
3788: my %returnhash=();
3789: foreach my $item (@pairs) {
3790: my ($key,$value)=split(/=/,$item,2);
3791: $key = &unescape($key);
3792: next if ($key =~ /^error: 2 /);
3793: $returnhash{$key}=&thaw_unescape($value);
3794: }
3795: return %returnhash;
1.407 www 3796: }
3797:
1.717 albertel 3798: # --------------------------------------------------------- dumpstore interface
3799:
3800: sub dumpstore {
3801: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 3802: if (!$udomain) { $udomain=$env{'user.domain'}; }
3803: if (!$uname) { $uname=$env{'user.name'}; }
3804: my $uhome=&homeserver($uname,$udomain);
3805: if ($regexp) {
3806: $regexp=&escape($regexp);
3807: } else {
3808: $regexp='.';
3809: }
3810: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3811: my @pairs=split(/\&/,$rep);
3812: my %returnhash=();
3813: foreach my $item (@pairs) {
3814: my ($key,$value)=split(/=/,$item,2);
3815: next if ($key =~ /^error: 2 /);
3816: $returnhash{$key}=&thaw_unescape($value);
3817: }
3818: return %returnhash;
1.717 albertel 3819: }
3820:
1.407 www 3821: # -------------------------------------------------------------- keys interface
3822:
3823: sub getkeys {
3824: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 3825: if (!$udomain) { $udomain=$env{'user.domain'}; }
3826: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 3827: my $uhome=&homeserver($uname,$udomain);
3828: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3829: my @keyarray=();
1.800 albertel 3830: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 3831: next if ($key =~ /^error: 2 /);
1.800 albertel 3832: push(@keyarray,&unescape($key));
1.407 www 3833: }
3834: return @keyarray;
1.318 matthew 3835: }
3836:
1.319 matthew 3837: # --------------------------------------------------------------- currentdump
3838: sub currentdump {
1.328 matthew 3839: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 3840: $courseid = $env{'request.course.id'} if (! defined($courseid));
3841: $sdom = $env{'user.domain'} if (! defined($sdom));
3842: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 3843: my $uhome = &homeserver($sname,$sdom);
3844: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 3845: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 3846: #
1.318 matthew 3847: my %returnhash=();
1.319 matthew 3848: #
3849: if ($rep eq "unknown_cmd") {
3850: # an old lond will not know currentdump
3851: # Do a dump and make it look like a currentdump
1.822 albertel 3852: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 3853: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3854: my %hash = @tmp;
3855: @tmp=();
1.424 matthew 3856: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 3857: } else {
3858: my @pairs=split(/\&/,$rep);
1.800 albertel 3859: foreach my $pair (@pairs) {
3860: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 3861: my ($symb,$param) = split(/:/,$key);
3862: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 3863: &thaw_unescape($value);
1.319 matthew 3864: }
1.191 harris41 3865: }
1.12 www 3866: return %returnhash;
1.424 matthew 3867: }
3868:
3869: sub convert_dump_to_currentdump{
3870: my %hash = %{shift()};
3871: my %returnhash;
3872: # Code ripped from lond, essentially. The only difference
3873: # here is the unescaping done by lonnet::dump(). Conceivably
3874: # we might run in to problems with parameter names =~ /^v\./
3875: while (my ($key,$value) = each(%hash)) {
3876: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 3877: $symb = &unescape($symb);
3878: $param = &unescape($param);
1.424 matthew 3879: next if ($v eq 'version' || $symb eq 'keys');
3880: next if (exists($returnhash{$symb}) &&
3881: exists($returnhash{$symb}->{$param}) &&
3882: $returnhash{$symb}->{'v.'.$param} > $v);
3883: $returnhash{$symb}->{$param}=$value;
3884: $returnhash{$symb}->{'v.'.$param}=$v;
3885: }
3886: #
3887: # Remove all of the keys in the hashes which keep track of
3888: # the version of the parameter.
3889: while (my ($symb,$param_hash) = each(%returnhash)) {
3890: # use a foreach because we are going to delete from the hash.
3891: foreach my $key (keys(%$param_hash)) {
3892: delete($param_hash->{$key}) if ($key =~ /^v\./);
3893: }
3894: }
3895: return \%returnhash;
1.12 www 3896: }
3897:
1.627 albertel 3898: # ------------------------------------------------------ critical inc interface
3899:
3900: sub cinc {
3901: return &inc(@_,'critical');
3902: }
3903:
1.449 matthew 3904: # --------------------------------------------------------------- inc interface
3905:
3906: sub inc {
1.627 albertel 3907: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 3908: if (!$udomain) { $udomain=$env{'user.domain'}; }
3909: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 3910: my $uhome=&homeserver($uname,$udomain);
3911: my $items='';
3912: if (! ref($store)) {
3913: # got a single value, so use that instead
3914: $items = &escape($store).'=&';
3915: } elsif (ref($store) eq 'SCALAR') {
3916: $items = &escape($$store).'=&';
3917: } elsif (ref($store) eq 'ARRAY') {
3918: $items = join('=&',map {&escape($_);} @{$store});
3919: } elsif (ref($store) eq 'HASH') {
3920: while (my($key,$value) = each(%{$store})) {
3921: $items.= &escape($key).'='.&escape($value).'&';
3922: }
3923: }
3924: $items=~s/\&$//;
1.627 albertel 3925: if ($critical) {
3926: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
3927: } else {
3928: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
3929: }
1.449 matthew 3930: }
3931:
1.12 www 3932: # --------------------------------------------------------------- put interface
3933:
3934: sub put {
1.134 albertel 3935: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3936: if (!$udomain) { $udomain=$env{'user.domain'}; }
3937: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3938: my $uhome=&homeserver($uname,$udomain);
1.12 www 3939: my $items='';
1.800 albertel 3940: foreach my $item (keys(%$storehash)) {
3941: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3942: }
1.12 www 3943: $items=~s/\&$//;
1.134 albertel 3944: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 3945: }
3946:
1.631 albertel 3947: # ------------------------------------------------------------ newput interface
3948:
3949: sub newput {
3950: my ($namespace,$storehash,$udomain,$uname)=@_;
3951: if (!$udomain) { $udomain=$env{'user.domain'}; }
3952: if (!$uname) { $uname=$env{'user.name'}; }
3953: my $uhome=&homeserver($uname,$udomain);
3954: my $items='';
3955: foreach my $key (keys(%$storehash)) {
3956: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3957: }
3958: $items=~s/\&$//;
3959: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
3960: }
3961:
3962: # --------------------------------------------------------- putstore interface
3963:
1.524 raeburn 3964: sub putstore {
1.715 albertel 3965: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 3966: if (!$udomain) { $udomain=$env{'user.domain'}; }
3967: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 3968: my $uhome=&homeserver($uname,$udomain);
3969: my $items='';
1.715 albertel 3970: foreach my $key (keys(%$storehash)) {
3971: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 3972: }
1.715 albertel 3973: $items=~s/\&$//;
1.716 albertel 3974: my $esc_symb=&escape($symb);
3975: my $esc_v=&escape($version);
1.715 albertel 3976: my $reply =
1.716 albertel 3977: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 3978: $uhome);
3979: if ($reply eq 'unknown_cmd') {
1.716 albertel 3980: # gfall back to way things use to be done
1.715 albertel 3981: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
3982: $uname);
1.524 raeburn 3983: }
1.715 albertel 3984: return $reply;
3985: }
3986:
3987: sub old_putstore {
1.716 albertel 3988: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3989: if (!$udomain) { $udomain=$env{'user.domain'}; }
3990: if (!$uname) { $uname=$env{'user.name'}; }
3991: my $uhome=&homeserver($uname,$udomain);
3992: my %newstorehash;
1.800 albertel 3993: foreach my $item (keys(%$storehash)) {
3994: my $key = $version.':'.&escape($symb).':'.$item;
3995: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 3996: }
3997: my $items='';
3998: my %allitems = ();
1.800 albertel 3999: foreach my $item (keys(%newstorehash)) {
4000: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4001: my $key = $1.':keys:'.$2;
4002: $allitems{$key} .= $3.':';
4003: }
1.800 albertel 4004: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4005: }
1.800 albertel 4006: foreach my $item (keys(%allitems)) {
4007: $allitems{$item} =~ s/\:$//;
4008: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4009: }
4010: $items=~s/\&$//;
4011: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4012: }
4013:
1.47 www 4014: # ------------------------------------------------------ critical put interface
4015:
4016: sub cput {
1.134 albertel 4017: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4018: if (!$udomain) { $udomain=$env{'user.domain'}; }
4019: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4020: my $uhome=&homeserver($uname,$udomain);
1.47 www 4021: my $items='';
1.800 albertel 4022: foreach my $item (keys(%$storehash)) {
4023: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4024: }
1.47 www 4025: $items=~s/\&$//;
1.134 albertel 4026: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4027: }
4028:
4029: # -------------------------------------------------------------- eget interface
4030:
4031: sub eget {
1.133 albertel 4032: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4033: my $items='';
1.800 albertel 4034: foreach my $item (@$storearr) {
4035: $items.=&escape($item).'&';
1.191 harris41 4036: }
1.12 www 4037: $items=~s/\&$//;
1.620 albertel 4038: if (!$udomain) { $udomain=$env{'user.domain'}; }
4039: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4040: my $uhome=&homeserver($uname,$udomain);
4041: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4042: my @pairs=split(/\&/,$rep);
4043: my %returnhash=();
1.42 www 4044: my $i=0;
1.800 albertel 4045: foreach my $item (@$storearr) {
4046: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4047: $i++;
1.191 harris41 4048: }
1.12 www 4049: return %returnhash;
4050: }
4051:
1.667 albertel 4052: # ------------------------------------------------------------ tmpput interface
4053: sub tmpput {
1.802 raeburn 4054: my ($storehash,$server,$context)=@_;
1.667 albertel 4055: my $items='';
1.800 albertel 4056: foreach my $item (keys(%$storehash)) {
4057: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4058: }
4059: $items=~s/\&$//;
1.802 raeburn 4060: if (defined($context)) {
4061: $items .= ':'.&escape($context);
4062: }
1.667 albertel 4063: return &reply("tmpput:$items",$server);
4064: }
4065:
4066: # ------------------------------------------------------------ tmpget interface
4067: sub tmpget {
1.688 albertel 4068: my ($token,$server)=@_;
4069: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4070: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4071: my %returnhash;
4072: foreach my $item (split(/\&/,$rep)) {
4073: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4074: next if ($key =~ /^error: 2 /);
1.667 albertel 4075: $returnhash{&unescape($key)}=&thaw_unescape($value);
4076: }
4077: return %returnhash;
4078: }
4079:
1.688 albertel 4080: # ------------------------------------------------------------ tmpget interface
4081: sub tmpdel {
4082: my ($token,$server)=@_;
4083: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4084: return &reply("tmpdel:$token",$server);
4085: }
4086:
1.765 albertel 4087: # -------------------------------------------------- portfolio access checking
4088:
4089: sub portfolio_access {
1.766 albertel 4090: my ($requrl) = @_;
1.765 albertel 4091: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4092: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4093: if ($result) {
4094: my %setters;
4095: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4096: my ($startblock,$endblock) =
4097: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4098: if ($startblock && $endblock) {
4099: return 'B';
4100: }
4101: } else {
4102: my ($startblock,$endblock) =
4103: &Apache::loncommon::blockcheck(\%setters,'port');
4104: if ($startblock && $endblock) {
4105: return 'B';
4106: }
4107: }
4108: }
1.765 albertel 4109: if ($result eq 'ok') {
1.766 albertel 4110: return 'F';
1.765 albertel 4111: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4112: return 'A';
1.765 albertel 4113: }
1.766 albertel 4114: return '';
1.765 albertel 4115: }
4116:
4117: sub get_portfolio_access {
1.767 albertel 4118: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4119:
4120: if (!ref($access_hash)) {
4121: my $current_perms = &get_portfile_permissions($udom,$unum);
4122: my %access_controls = &get_access_controls($current_perms,$group,
4123: $file_name);
4124: $access_hash = $access_controls{$file_name};
4125: }
4126:
1.765 albertel 4127: my ($public,$guest,@domains,@users,@courses,@groups);
4128: my $now = time;
4129: if (ref($access_hash) eq 'HASH') {
4130: foreach my $key (keys(%{$access_hash})) {
4131: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4132: if ($start > $now) {
4133: next;
4134: }
4135: if ($end && $end<$now) {
4136: next;
4137: }
4138: if ($scope eq 'public') {
4139: $public = $key;
4140: last;
4141: } elsif ($scope eq 'guest') {
4142: $guest = $key;
4143: } elsif ($scope eq 'domains') {
4144: push(@domains,$key);
4145: } elsif ($scope eq 'users') {
4146: push(@users,$key);
4147: } elsif ($scope eq 'course') {
4148: push(@courses,$key);
4149: } elsif ($scope eq 'group') {
4150: push(@groups,$key);
4151: }
4152: }
4153: if ($public) {
4154: return 'ok';
4155: }
4156: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4157: if ($guest) {
4158: return $guest;
4159: }
4160: } else {
4161: if (@domains > 0) {
4162: foreach my $domkey (@domains) {
4163: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4164: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4165: return 'ok';
4166: }
4167: }
4168: }
4169: }
4170: if (@users > 0) {
4171: foreach my $userkey (@users) {
1.865 raeburn 4172: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4173: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4174: if (ref($item) eq 'HASH') {
4175: if (($item->{'uname'} eq $env{'user.name'}) &&
4176: ($item->{'udom'} eq $env{'user.domain'})) {
4177: return 'ok';
4178: }
4179: }
4180: }
4181: }
1.765 albertel 4182: }
4183: }
4184: my %roleshash;
4185: my @courses_and_groups = @courses;
4186: push(@courses_and_groups,@groups);
4187: if (@courses_and_groups > 0) {
4188: my (%allgroups,%allroles);
4189: my ($start,$end,$role,$sec,$group);
4190: foreach my $envkey (%env) {
1.811 albertel 4191: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4192: my $cid = $2.'_'.$3;
4193: if ($1 eq 'gr') {
4194: $group = $4;
4195: $allgroups{$cid}{$group} = $env{$envkey};
4196: } else {
4197: if ($4 eq '') {
4198: $sec = 'none';
4199: } else {
4200: $sec = $4;
4201: }
4202: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4203: }
1.811 albertel 4204: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4205: my $cid = $2.'_'.$3;
4206: if ($4 eq '') {
4207: $sec = 'none';
4208: } else {
4209: $sec = $4;
4210: }
4211: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4212: }
4213: }
4214: if (keys(%allroles) == 0) {
4215: return;
4216: }
4217: foreach my $key (@courses_and_groups) {
4218: my %content = %{$$access_hash{$key}};
4219: my $cnum = $content{'number'};
4220: my $cdom = $content{'domain'};
4221: my $cid = $cdom.'_'.$cnum;
4222: if (!exists($allroles{$cid})) {
4223: next;
4224: }
4225: foreach my $role_id (keys(%{$content{'roles'}})) {
4226: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4227: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4228: my @status = @{$content{'roles'}{$role_id}{'access'}};
4229: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4230: foreach my $role (keys(%{$allroles{$cid}})) {
4231: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4232: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4233: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4234: if (grep/^all$/,@sections) {
4235: return 'ok';
4236: } else {
4237: if (grep/^$sec$/,@sections) {
4238: return 'ok';
4239: }
4240: }
4241: }
4242: }
4243: if (keys(%{$allgroups{$cid}}) == 0) {
4244: if (grep/^none$/,@groups) {
4245: return 'ok';
4246: }
4247: } else {
4248: if (grep/^all$/,@groups) {
4249: return 'ok';
4250: }
4251: foreach my $group (keys(%{$allgroups{$cid}})) {
4252: if (grep/^$group$/,@groups) {
4253: return 'ok';
4254: }
4255: }
4256: }
4257: }
4258: }
4259: }
4260: }
4261: }
4262: if ($guest) {
4263: return $guest;
4264: }
4265: }
4266: }
4267: return;
4268: }
4269:
4270: sub course_group_datechecker {
4271: my ($dates,$now,$status) = @_;
4272: my ($start,$end) = split(/\./,$dates);
4273: if (!$start && !$end) {
4274: return 'ok';
4275: }
4276: if (grep/^active$/,@{$status}) {
4277: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4278: return 'ok';
4279: }
4280: }
4281: if (grep/^previous$/,@{$status}) {
4282: if ($end > $now ) {
4283: return 'ok';
4284: }
4285: }
4286: if (grep/^future$/,@{$status}) {
4287: if ($start > $now) {
4288: return 'ok';
4289: }
4290: }
4291: return;
4292: }
4293:
4294: sub parse_portfolio_url {
4295: my ($url) = @_;
4296:
4297: my ($type,$udom,$unum,$group,$file_name);
4298:
1.823 albertel 4299: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4300: $type = 1;
4301: $udom = $1;
4302: $unum = $2;
4303: $file_name = $3;
1.823 albertel 4304: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4305: $type = 2;
4306: $udom = $1;
4307: $unum = $2;
4308: $group = $3;
4309: $file_name = $3.'/'.$4;
4310: }
4311: if (wantarray) {
4312: return ($type,$udom,$unum,$file_name,$group);
4313: }
4314: return $type;
4315: }
4316:
4317: sub is_portfolio_url {
4318: my ($url) = @_;
4319: return scalar(&parse_portfolio_url($url));
4320: }
4321:
1.798 raeburn 4322: sub is_portfolio_file {
4323: my ($file) = @_;
1.820 raeburn 4324: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4325: return 1;
4326: }
4327: return;
4328: }
4329:
4330:
1.341 www 4331: # ---------------------------------------------- Custom access rule evaluation
4332:
4333: sub customaccess {
4334: my ($priv,$uri)=@_;
1.807 albertel 4335: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 4336: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 4337: $udom = &LONCAPA::clean_domain($udom);
4338: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 4339: my $access=0;
1.800 albertel 4340: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 4341: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4342: if ($type eq 'user') {
4343: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 4344: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 4345: if ($tdom) {
4346: if ($tdom ne $env{'user.domain'}) { next; }
4347: }
1.896 albertel 4348: if ($tuname) {
4349: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 4350: }
4351: $access=($effect eq 'allow');
4352: last;
4353: }
4354: } else {
4355: if ($role) {
4356: if ($role ne $urole) { next; }
4357: }
4358: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4359: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4360: if ($tdom) {
4361: if ($tdom ne $udom) { next; }
4362: }
4363: if ($tcrs) {
4364: if ($tcrs ne $ucrs) { next; }
4365: }
4366: if ($tsec) {
4367: if ($tsec ne $usec) { next; }
4368: }
4369: $access=($effect eq 'allow');
4370: last;
4371: }
4372: if ($realm eq '' && $role eq '') {
4373: $access=($effect eq 'allow');
4374: }
1.402 bowersj2 4375: }
1.341 www 4376: }
4377: return $access;
4378: }
4379:
1.103 harris41 4380: # ------------------------------------------------- Check for a user privilege
1.12 www 4381:
4382: sub allowed {
1.810 raeburn 4383: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 4384: my $ver_orguri=$uri;
1.439 www 4385: $uri=&deversion($uri);
1.152 www 4386: my $orguri=$uri;
1.52 www 4387: $uri=&declutter($uri);
1.809 raeburn 4388:
1.810 raeburn 4389: if ($priv eq 'evb') {
4390: # Evade communication block restrictions for specified role in a course
4391: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4392: return $1;
4393: } else {
4394: return;
4395: }
4396: }
4397:
1.620 albertel 4398: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 4399: # Free bre access to adm and meta resources
1.775 albertel 4400: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 4401: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4402: && ($priv eq 'bre')) {
1.14 www 4403: return 'F';
1.159 www 4404: }
4405:
1.545 banghart 4406: # Free bre access to user's own portfolio contents
1.714 raeburn 4407: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 4408: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 4409: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 4410: my %setters;
4411: my ($startblock,$endblock) =
4412: &Apache::loncommon::blockcheck(\%setters,'port');
4413: if ($startblock && $endblock) {
4414: return 'B';
4415: } else {
4416: return 'F';
4417: }
1.545 banghart 4418: }
4419:
1.762 raeburn 4420: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 4421: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
4422: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
4423: if (exists($env{'request.course.id'})) {
4424: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4425: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4426: if (($domain eq $cdom) && ($name eq $cnum)) {
4427: my $courseprivid=$env{'request.course.id'};
4428: $courseprivid=~s/\_/\//;
4429: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
4430: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
4431: return $1;
1.762 raeburn 4432: } else {
4433: if ($env{'request.course.sec'}) {
4434: $courseprivid.='/'.$env{'request.course.sec'};
4435: }
4436: if ($env{'user.priv.'.$env{'request.role'}.'./'.
4437: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
4438: return $2;
4439: }
1.714 raeburn 4440: }
4441: }
4442: }
4443: }
4444:
1.159 www 4445: # Free bre to public access
4446:
4447: if ($priv eq 'bre') {
1.238 www 4448: my $copyright=&metadata($uri,'copyright');
1.620 albertel 4449: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 4450: return 'F';
4451: }
1.238 www 4452: if ($copyright eq 'priv') {
4453: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4454: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 4455: return '';
4456: }
4457: }
4458: if ($copyright eq 'domain') {
4459: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4460: unless (($env{'user.domain'} eq $1) ||
4461: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 4462: return '';
4463: }
1.262 matthew 4464: }
1.620 albertel 4465: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 4466: # Library role, so allow browsing of resources in this domain.
4467: return 'F';
1.238 www 4468: }
1.341 www 4469: if ($copyright eq 'custom') {
4470: unless (&customaccess($priv,$uri)) { return ''; }
4471: }
1.14 www 4472: }
1.264 matthew 4473: # Domain coordinator is trying to create a course
1.620 albertel 4474: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 4475: # uri is the requested domain in this case.
4476: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 4477: # a role of dc for the domain in question.
1.620 albertel 4478: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 4479: }
1.29 www 4480:
1.52 www 4481: my $thisallowed='';
4482: my $statecond=0;
4483: my $courseprivid='';
4484:
4485: # Course
4486:
1.620 albertel 4487: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4488: $thisallowed.=$1;
4489: }
1.29 www 4490:
1.52 www 4491: # Domain
4492:
1.620 albertel 4493: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 4494: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4495: $thisallowed.=$1;
4496: }
1.52 www 4497:
4498: # Course: uri itself is a course
1.66 www 4499: my $courseuri=$uri;
4500: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 4501: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 4502:
1.620 albertel 4503: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 4504: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4505: $thisallowed.=$1;
4506: }
1.29 www 4507:
1.665 albertel 4508: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 4509: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 4510: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 4511: $thisallowed='';
1.671 raeburn 4512: my ($match)=&is_on_map($uri);
4513: if ($match) {
4514: if ($env{'user.priv.'.$env{'request.role'}.'./'}
4515: =~/\Q$priv\E\&([^\:]*)/) {
4516: $thisallowed.=$1;
4517: }
4518: } else {
1.705 albertel 4519: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 4520: if ($refuri) {
4521: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 4522: $thisallowed='F';
1.671 raeburn 4523: } else {
4524: $refuri=&declutter($refuri);
4525: my ($match) = &is_on_map($refuri);
4526: if ($match) {
4527: $thisallowed='F';
4528: }
1.669 raeburn 4529: }
1.671 raeburn 4530: }
4531: }
1.314 www 4532: }
1.492 albertel 4533:
1.766 albertel 4534: if ($priv eq 'bre'
4535: && $thisallowed ne 'F'
4536: && $thisallowed ne '2'
4537: && &is_portfolio_url($uri)) {
4538: $thisallowed = &portfolio_access($uri);
4539: }
4540:
1.52 www 4541: # Full access at system, domain or course-wide level? Exit.
1.29 www 4542: if ($thisallowed=~/F/) {
4543: return 'F';
4544: }
4545:
1.52 www 4546: # If this is generating or modifying users, exit with special codes
1.29 www 4547:
1.643 www 4548: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
4549: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 4550: my ($audom,$auname)=split('/',$uri);
1.643 www 4551: # no author name given, so this just checks on the general right to make a co-author in this domain
4552: unless ($auname) { return $thisallowed; }
4553: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 4554: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
4555: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
4556: ($audom ne $env{'request.role.domain'}))) { return ''; }
4557: }
1.52 www 4558: return $thisallowed;
4559: }
4560: #
1.103 harris41 4561: # Gathered so far: system, domain and course wide privileges
1.52 www 4562: #
4563: # Course: See if uri or referer is an individual resource that is part of
4564: # the course
4565:
1.620 albertel 4566: if ($env{'request.course.id'}) {
1.232 www 4567:
1.620 albertel 4568: $courseprivid=$env{'request.course.id'};
4569: if ($env{'request.course.sec'}) {
4570: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 4571: }
4572: $courseprivid=~s/\_/\//;
4573: my $checkreferer=1;
1.232 www 4574: my ($match,$cond)=&is_on_map($uri);
4575: if ($match) {
4576: $statecond=$cond;
1.620 albertel 4577: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4578: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4579: $thisallowed.=$1;
4580: $checkreferer=0;
4581: }
1.29 www 4582: }
1.83 www 4583:
1.148 www 4584: if ($checkreferer) {
1.620 albertel 4585: my $refuri=$env{'httpref.'.$orguri};
1.148 www 4586: unless ($refuri) {
1.800 albertel 4587: foreach my $key (keys(%env)) {
4588: if ($key=~/^httpref\..*\*/) {
4589: my $pattern=$key;
1.156 www 4590: $pattern=~s/^httpref\.\/res\///;
1.148 www 4591: $pattern=~s/\*/\[\^\/\]\+/g;
4592: $pattern=~s/\//\\\//g;
1.152 www 4593: if ($orguri=~/$pattern/) {
1.800 albertel 4594: $refuri=$env{$key};
1.148 www 4595: }
4596: }
1.191 harris41 4597: }
1.148 www 4598: }
1.232 www 4599:
1.148 www 4600: if ($refuri) {
1.152 www 4601: $refuri=&declutter($refuri);
1.232 www 4602: my ($match,$cond)=&is_on_map($refuri);
4603: if ($match) {
4604: my $refstatecond=$cond;
1.620 albertel 4605: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4606: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4607: $thisallowed.=$1;
1.53 www 4608: $uri=$refuri;
4609: $statecond=$refstatecond;
1.52 www 4610: }
4611: }
1.148 www 4612: }
1.29 www 4613: }
1.52 www 4614: }
1.29 www 4615:
1.52 www 4616: #
1.103 harris41 4617: # Gathered now: all privileges that could apply, and condition number
1.52 www 4618: #
4619: #
4620: # Full or no access?
4621: #
1.29 www 4622:
1.52 www 4623: if ($thisallowed=~/F/) {
4624: return 'F';
4625: }
1.29 www 4626:
1.52 www 4627: unless ($thisallowed) {
4628: return '';
4629: }
1.29 www 4630:
1.52 www 4631: # Restrictions exist, deal with them
4632: #
4633: # C:according to course preferences
4634: # R:according to resource settings
4635: # L:unless locked
4636: # X:according to user session state
4637: #
4638:
4639: # Possibly locked functionality, check all courses
1.54 www 4640: # Locks might take effect only after 10 minutes cache expiration for other
4641: # courses, and 2 minutes for current course
1.52 www 4642:
4643: my $envkey;
4644: if ($thisallowed=~/L/) {
1.620 albertel 4645: foreach $envkey (keys %env) {
1.54 www 4646: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
4647: my $courseid=$2;
4648: my $roleid=$1.'.'.$2;
1.92 www 4649: $courseid=~s/^\///;
1.54 www 4650: my $expiretime=600;
1.620 albertel 4651: if ($env{'request.role'} eq $roleid) {
1.54 www 4652: $expiretime=120;
4653: }
4654: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
4655: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 4656: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 4657: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 4658: }
1.620 albertel 4659: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
4660: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
4661: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
4662: &log($env{'user.domain'},$env{'user.name'},
4663: $env{'user.home'},
1.57 www 4664: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 4665: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4666: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4667: return '';
4668: }
4669: }
1.620 albertel 4670: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
4671: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
4672: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
4673: &log($env{'user.domain'},$env{'user.name'},
4674: $env{'user.home'},
1.57 www 4675: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 4676: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4677: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4678: return '';
4679: }
4680: }
4681: }
1.29 www 4682: }
1.52 www 4683: }
4684:
4685: #
4686: # Rest of the restrictions depend on selected course
4687: #
4688:
1.620 albertel 4689: unless ($env{'request.course.id'}) {
1.766 albertel 4690: if ($thisallowed eq 'A') {
4691: return 'A';
1.814 raeburn 4692: } elsif ($thisallowed eq 'B') {
4693: return 'B';
1.766 albertel 4694: } else {
4695: return '1';
4696: }
1.52 www 4697: }
1.29 www 4698:
1.52 www 4699: #
4700: # Now user is definitely in a course
4701: #
1.53 www 4702:
4703:
4704: # Course preferences
4705:
4706: if ($thisallowed=~/C/) {
1.620 albertel 4707: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4708: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
4709: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 4710: =~/\Q$rolecode\E/) {
1.689 albertel 4711: if ($priv ne 'pch') {
4712: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4713: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
4714: $env{'request.course.id'});
4715: }
1.237 www 4716: return '';
4717: }
4718:
1.620 albertel 4719: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 4720: =~/\Q$unamedom\E/) {
1.689 albertel 4721: if ($priv ne 'pch') {
4722: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
4723: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
4724: $env{'request.course.id'});
4725: }
1.54 www 4726: return '';
4727: }
1.53 www 4728: }
4729:
4730: # Resource preferences
4731:
4732: if ($thisallowed=~/R/) {
1.620 albertel 4733: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 4734: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 4735: if ($priv ne 'pch') {
4736: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4737: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
4738: }
4739: return '';
1.54 www 4740: }
1.53 www 4741: }
1.30 www 4742:
1.246 www 4743: # Restricted by state or randomout?
1.30 www 4744:
1.52 www 4745: if ($thisallowed=~/X/) {
1.620 albertel 4746: if ($env{'acc.randomout'}) {
1.579 albertel 4747: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 4748: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 4749: return '';
4750: }
1.247 www 4751: }
4752: if (&condval($statecond)) {
1.52 www 4753: return '2';
4754: } else {
4755: return '';
4756: }
4757: }
1.30 www 4758:
1.766 albertel 4759: if ($thisallowed eq 'A') {
4760: return 'A';
1.814 raeburn 4761: } elsif ($thisallowed eq 'B') {
4762: return 'B';
1.766 albertel 4763: }
1.52 www 4764: return 'F';
1.232 www 4765: }
4766:
1.710 albertel 4767: sub split_uri_for_cond {
4768: my $uri=&deversion(&declutter(shift));
4769: my @uriparts=split(/\//,$uri);
4770: my $filename=pop(@uriparts);
4771: my $pathname=join('/',@uriparts);
4772: return ($pathname,$filename);
4773: }
1.232 www 4774: # --------------------------------------------------- Is a resource on the map?
4775:
4776: sub is_on_map {
1.710 albertel 4777: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 4778: #Trying to find the conditional for the file
1.620 albertel 4779: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 4780: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 4781: if ($match) {
1.289 bowersj2 4782: return (1,$1);
4783: } else {
1.434 www 4784: return (0,0);
1.289 bowersj2 4785: }
1.12 www 4786: }
4787:
1.427 www 4788: # --------------------------------------------------------- Get symb from alias
4789:
4790: sub get_symb_from_alias {
4791: my $symb=shift;
4792: my ($map,$resid,$url)=&decode_symb($symb);
4793: # Already is a symb
4794: if ($url) { return $symb; }
4795: # Must be an alias
4796: my $aliassymb='';
4797: my %bighash;
1.620 albertel 4798: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 4799: &GDBM_READER(),0640)) {
4800: my $rid=$bighash{'mapalias_'.$symb};
4801: if ($rid) {
4802: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 4803: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
4804: $resid,$bighash{'src_'.$rid});
1.427 www 4805: }
4806: untie %bighash;
4807: }
4808: return $aliassymb;
4809: }
4810:
1.12 www 4811: # ----------------------------------------------------------------- Define Role
4812:
4813: sub definerole {
4814: if (allowed('mcr','/')) {
4815: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 4816: foreach my $role (split(':',$sysrole)) {
4817: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4818: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
4819: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
4820: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4821: return "refused:s:$crole&$cqual";
4822: }
4823: }
1.191 harris41 4824: }
1.800 albertel 4825: foreach my $role (split(':',$domrole)) {
4826: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4827: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
4828: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
4829: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 4830: return "refused:d:$crole&$cqual";
4831: }
4832: }
1.191 harris41 4833: }
1.800 albertel 4834: foreach my $role (split(':',$courole)) {
4835: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4836: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
4837: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
4838: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4839: return "refused:c:$crole&$cqual";
4840: }
4841: }
1.191 harris41 4842: }
1.620 albertel 4843: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4844: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 4845: "rolesdef_$rolename=".
4846: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 4847: return reply($command,$env{'user.home'});
1.12 www 4848: } else {
4849: return 'refused';
4850: }
1.105 harris41 4851: }
4852:
4853: # ---------------- Make a metadata query against the network of library servers
4854:
4855: sub metadata_query {
1.244 matthew 4856: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 4857: my %rhash;
1.845 albertel 4858: my %libserv = &all_library();
1.244 matthew 4859: my @server_list = (defined($server_array) ? @$server_array
4860: : keys(%libserv) );
4861: for my $server (@server_list) {
1.118 harris41 4862: unless ($custom or $customshow) {
4863: my $reply=&reply("querysend:".&escape($query),$server);
4864: $rhash{$server}=$reply;
4865: }
4866: else {
4867: my $reply=&reply("querysend:".&escape($query).':'.
4868: &escape($custom).':'.&escape($customshow),
4869: $server);
4870: $rhash{$server}=$reply;
4871: }
1.112 harris41 4872: }
1.118 harris41 4873: return \%rhash;
1.240 www 4874: }
4875:
4876: # ----------------------------------------- Send log queries and wait for reply
4877:
4878: sub log_query {
4879: my ($uname,$udom,$query,%filters)=@_;
4880: my $uhome=&homeserver($uname,$udom);
4881: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 4882: my $uhost=&hostname($uhome);
1.800 albertel 4883: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 4884: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
4885: $uhome);
1.479 albertel 4886: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 4887: return get_query_reply($queryid);
4888: }
4889:
1.818 raeburn 4890: # -------------------------- Update MySQL table for portfolio file
4891:
4892: sub update_portfolio_table {
1.821 raeburn 4893: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818 raeburn 4894: my $homeserver = &homeserver($uname,$udom);
4895: my $queryid=
1.821 raeburn 4896: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
4897: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 4898: my $reply = &get_query_reply($queryid);
4899: return $reply;
4900: }
4901:
1.899 raeburn 4902: # -------------------------- Update MySQL allusers table
4903:
4904: sub update_allusers_table {
4905: my ($uname,$udom,$names) = @_;
4906: my $homeserver = &homeserver($uname,$udom);
4907: my $queryid=
4908: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
4909: 'lastname='.&escape($names->{'lastname'}).'%%'.
4910: 'firstname='.&escape($names->{'firstname'}).'%%'.
4911: 'middlename='.&escape($names->{'middlename'}).'%%'.
4912: 'generation='.&escape($names->{'generation'}).'%%'.
4913: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
4914: 'id='.&escape($names->{'id'}),$homeserver);
4915: my $reply = &get_query_reply($queryid);
4916: return $reply;
4917: }
4918:
1.508 raeburn 4919: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 4920:
4921: sub fetch_enrollment_query {
1.511 raeburn 4922: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 4923: my $homeserver;
1.547 raeburn 4924: my $maxtries = 1;
1.508 raeburn 4925: if ($context eq 'automated') {
4926: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 4927: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 4928: } else {
4929: $homeserver = &homeserver($cnum,$dom);
4930: }
1.838 albertel 4931: my $host=&hostname($homeserver);
1.506 raeburn 4932: my $cmd = '';
1.800 albertel 4933: foreach my $affiliate (keys %{$affiliatesref}) {
4934: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 4935: }
4936: $cmd =~ s/%%$//;
4937: $cmd = &escape($cmd);
4938: my $query = 'fetchenrollment';
1.620 albertel 4939: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 4940: unless ($queryid=~/^\Q$host\E\_/) {
4941: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
4942: return 'error: '.$queryid;
4943: }
1.506 raeburn 4944: my $reply = &get_query_reply($queryid);
1.547 raeburn 4945: my $tries = 1;
4946: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4947: $reply = &get_query_reply($queryid);
4948: $tries ++;
4949: }
1.526 raeburn 4950: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 4951: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 4952: } else {
1.901 albertel 4953: my @responses = split(/:/,$reply);
1.515 raeburn 4954: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 4955: foreach my $line (@responses) {
4956: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 4957: $$replyref{$key} = $value;
4958: }
4959: } else {
1.506 raeburn 4960: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 4961: foreach my $line (@responses) {
4962: my ($key,$value) = split(/=/,$line);
1.506 raeburn 4963: $$replyref{$key} = $value;
4964: if ($value > 0) {
1.800 albertel 4965: foreach my $item (@{$$affiliatesref{$key}}) {
4966: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 4967: my $destname = $pathname.'/'.$filename;
4968: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 4969: if ($xml_classlist =~ /^error/) {
4970: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
4971: } else {
1.506 raeburn 4972: if ( open(FILE,">$destname") ) {
4973: print FILE &unescape($xml_classlist);
4974: close(FILE);
1.526 raeburn 4975: } else {
4976: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 4977: }
4978: }
4979: }
4980: }
4981: }
4982: }
4983: return 'ok';
4984: }
4985: return 'error';
4986: }
4987:
1.242 www 4988: sub get_query_reply {
4989: my $queryid=shift;
1.240 www 4990: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
4991: my $reply='';
4992: for (1..100) {
4993: sleep 2;
4994: if (-e $replyfile.'.end') {
1.448 albertel 4995: if (open(my $fh,$replyfile)) {
1.904 albertel 4996: $reply = join('',<$fh>);
4997: close($fh);
1.240 www 4998: } else { return 'error: reply_file_error'; }
1.242 www 4999: return &unescape($reply);
5000: }
1.240 www 5001: }
1.242 www 5002: return 'timeout:'.$queryid;
1.240 www 5003: }
5004:
5005: sub courselog_query {
1.241 www 5006: #
5007: # possible filters:
5008: # url: url or symb
5009: # username
5010: # domain
5011: # action: view, submit, grade
5012: # start: timestamp
5013: # end: timestamp
5014: #
1.240 www 5015: my (%filters)=@_;
1.620 albertel 5016: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5017: if ($filters{'url'}) {
5018: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5019: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5020: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5021: }
1.620 albertel 5022: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5023: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5024: return &log_query($cname,$cdom,'courselog',%filters);
5025: }
5026:
5027: sub userlog_query {
1.858 raeburn 5028: #
5029: # possible filters:
5030: # action: log check role
5031: # start: timestamp
5032: # end: timestamp
5033: #
1.240 www 5034: my ($uname,$udom,%filters)=@_;
5035: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5036: }
5037:
1.506 raeburn 5038: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5039:
5040: sub auto_run {
1.508 raeburn 5041: my ($cnum,$cdom) = @_;
1.876 raeburn 5042: my $response = 0;
5043: my $settings;
5044: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5045: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5046: $settings = $domconfig{'autoenroll'};
5047: if ($settings->{'run'} eq '1') {
5048: $response = 1;
5049: }
5050: } else {
1.934 raeburn 5051: my $homeserver;
5052: if (&is_course($cdom,$cnum)) {
5053: $homeserver = &homeserver($cnum,$cdom);
5054: } else {
5055: $homeserver = &domain($cdom,'primary');
5056: }
5057: if ($homeserver ne 'no_host') {
5058: $response = &reply('autorun:'.$cdom,$homeserver);
5059: }
1.876 raeburn 5060: }
1.506 raeburn 5061: return $response;
5062: }
1.776 albertel 5063:
1.506 raeburn 5064: sub auto_get_sections {
1.508 raeburn 5065: my ($cnum,$cdom,$inst_coursecode) = @_;
5066: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 5067: my @secs = ();
1.511 raeburn 5068: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 5069: unless ($response eq 'refused') {
1.901 albertel 5070: @secs = split(/:/,$response);
1.506 raeburn 5071: }
5072: return @secs;
5073: }
1.776 albertel 5074:
1.506 raeburn 5075: sub auto_new_course {
1.508 raeburn 5076: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5077: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5078: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5079: return $response;
5080: }
1.776 albertel 5081:
1.506 raeburn 5082: sub auto_validate_courseID {
1.508 raeburn 5083: my ($cnum,$cdom,$inst_course_id) = @_;
5084: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5085: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5086: return $response;
5087: }
1.776 albertel 5088:
1.506 raeburn 5089: sub auto_create_password {
1.873 raeburn 5090: my ($cnum,$cdom,$authparam,$udom) = @_;
5091: my ($homeserver,$response);
1.506 raeburn 5092: my $create_passwd = 0;
5093: my $authchk = '';
1.873 raeburn 5094: if ($udom =~ /^$match_domain$/) {
5095: $homeserver = &domain($udom,'primary');
5096: }
5097: if ($homeserver eq '') {
5098: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5099: $homeserver = &homeserver($cnum,$cdom);
5100: }
5101: }
5102: if ($homeserver eq '') {
5103: $authchk = 'nodomain';
1.506 raeburn 5104: } else {
1.873 raeburn 5105: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5106: if ($response eq 'refused') {
5107: $authchk = 'refused';
5108: } else {
1.901 albertel 5109: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 5110: }
1.506 raeburn 5111: }
5112: return ($authparam,$create_passwd,$authchk);
5113: }
5114:
1.706 raeburn 5115: sub auto_photo_permission {
5116: my ($cnum,$cdom,$students) = @_;
5117: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 5118: my ($outcome,$perm_reqd,$conditions) =
5119: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 5120: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5121: return (undef,undef);
5122: }
1.706 raeburn 5123: return ($outcome,$perm_reqd,$conditions);
5124: }
5125:
5126: sub auto_checkphotos {
5127: my ($uname,$udom,$pid) = @_;
5128: my $homeserver = &homeserver($uname,$udom);
5129: my ($result,$resulttype);
5130: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 5131: &escape($uname).':'.&escape($pid),
5132: $homeserver));
1.709 albertel 5133: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5134: return (undef,undef);
5135: }
1.706 raeburn 5136: if ($outcome) {
5137: ($result,$resulttype) = split(/:/,$outcome);
5138: }
5139: return ($result,$resulttype);
5140: }
5141:
5142: sub auto_photochoice {
5143: my ($cnum,$cdom) = @_;
5144: my $homeserver = &homeserver($cnum,$cdom);
5145: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 5146: &escape($cdom),
5147: $homeserver)));
1.709 albertel 5148: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5149: return (undef,undef);
5150: }
1.706 raeburn 5151: return ($update,$comment);
5152: }
5153:
5154: sub auto_photoupdate {
5155: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5156: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 5157: my $host=&hostname($homeserver);
1.706 raeburn 5158: my $cmd = '';
5159: my $maxtries = 1;
1.800 albertel 5160: foreach my $affiliate (keys(%{$affiliatesref})) {
5161: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 5162: }
5163: $cmd =~ s/%%$//;
5164: $cmd = &escape($cmd);
5165: my $query = 'institutionalphotos';
5166: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5167: unless ($queryid=~/^\Q$host\E\_/) {
5168: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5169: return 'error: '.$queryid;
5170: }
5171: my $reply = &get_query_reply($queryid);
5172: my $tries = 1;
5173: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5174: $reply = &get_query_reply($queryid);
5175: $tries ++;
5176: }
5177: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5178: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5179: } else {
5180: my @responses = split(/:/,$reply);
5181: my $outcome = shift(@responses);
5182: foreach my $item (@responses) {
5183: my ($key,$value) = split(/=/,$item);
5184: $$photo{$key} = $value;
5185: }
5186: return $outcome;
5187: }
5188: return 'error';
5189: }
5190:
1.521 raeburn 5191: sub auto_instcode_format {
1.793 albertel 5192: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5193: $cat_order) = @_;
1.521 raeburn 5194: my $courses = '';
1.772 raeburn 5195: my @homeservers;
1.521 raeburn 5196: if ($caller eq 'global') {
1.841 albertel 5197: my %servers = &get_servers($codedom,'library');
5198: foreach my $tryserver (keys(%servers)) {
5199: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5200: push(@homeservers,$tryserver);
5201: }
1.584 raeburn 5202: }
1.521 raeburn 5203: } else {
1.772 raeburn 5204: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 5205: }
1.793 albertel 5206: foreach my $code (keys(%{$instcodes})) {
5207: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 5208: }
5209: chop($courses);
1.772 raeburn 5210: my $ok_response = 0;
5211: my $response;
5212: while (@homeservers > 0 && $ok_response == 0) {
5213: my $server = shift(@homeservers);
5214: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5215: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5216: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 5217: split(/:/,$response);
1.772 raeburn 5218: %{$codes} = (%{$codes},&str2hash($codes_str));
5219: push(@{$codetitles},&str2array($codetitles_str));
5220: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5221: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5222: $ok_response = 1;
5223: }
5224: }
5225: if ($ok_response) {
1.521 raeburn 5226: return 'ok';
1.772 raeburn 5227: } else {
5228: return $response;
1.521 raeburn 5229: }
5230: }
5231:
1.792 raeburn 5232: sub auto_instcode_defaults {
5233: my ($domain,$returnhash,$code_order) = @_;
5234: my @homeservers;
1.841 albertel 5235:
5236: my %servers = &get_servers($domain,'library');
5237: foreach my $tryserver (keys(%servers)) {
5238: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5239: push(@homeservers,$tryserver);
5240: }
1.792 raeburn 5241: }
1.841 albertel 5242:
1.792 raeburn 5243: my $response;
1.841 albertel 5244: foreach my $server (@homeservers) {
1.792 raeburn 5245: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 5246: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5247:
5248: foreach my $pair (split(/\&/,$response)) {
5249: my ($name,$value)=split(/\=/,$pair);
5250: if ($name eq 'code_order') {
5251: @{$code_order} = split(/\&/,&unescape($value));
5252: } else {
5253: $returnhash->{&unescape($name)}=&unescape($value);
5254: }
5255: }
5256: return 'ok';
1.792 raeburn 5257: }
1.841 albertel 5258:
5259: return $response;
1.792 raeburn 5260: }
5261:
1.777 albertel 5262: sub auto_validate_class_sec {
1.918 raeburn 5263: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 5264: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 5265: my $ownerlist;
5266: if (ref($owners) eq 'ARRAY') {
5267: $ownerlist = join(',',@{$owners});
5268: } else {
5269: $ownerlist = $owners;
5270: }
1.773 raeburn 5271: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 5272: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 5273: return $response;
5274: }
5275:
1.679 raeburn 5276: # ------------------------------------------------------- Course Group routines
5277:
5278: sub get_coursegroups {
1.809 raeburn 5279: my ($cdom,$cnum,$group,$namespace) = @_;
5280: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 5281: }
5282:
1.679 raeburn 5283: sub modify_coursegroup {
5284: my ($cdom,$cnum,$groupsettings) = @_;
5285: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
5286: }
5287:
1.809 raeburn 5288: sub toggle_coursegroup_status {
5289: my ($cdom,$cnum,$group,$action) = @_;
5290: my ($from_namespace,$to_namespace);
5291: if ($action eq 'delete') {
5292: $from_namespace = 'coursegroups';
5293: $to_namespace = 'deleted_groups';
5294: } else {
5295: $from_namespace = 'deleted_groups';
5296: $to_namespace = 'coursegroups';
5297: }
5298: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 5299: if (my $tmp = &error(%curr_group)) {
5300: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
5301: return ('read error',$tmp);
5302: } else {
5303: my %savedsettings = %curr_group;
1.809 raeburn 5304: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 5305: my $deloutcome;
5306: if ($result eq 'ok') {
1.809 raeburn 5307: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 5308: } else {
5309: return ('write error',$result);
5310: }
5311: if ($deloutcome eq 'ok') {
5312: return 'ok';
5313: } else {
5314: return ('delete error',$deloutcome);
5315: }
5316: }
5317: }
5318:
1.679 raeburn 5319: sub modify_group_roles {
1.957 raeburn 5320: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 5321: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
5322: my $role = 'gr/'.&escape($userprivs);
5323: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 5324: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 5325: if ($result eq 'ok') {
5326: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
5327: }
1.679 raeburn 5328: return $result;
5329: }
5330:
5331: sub modify_coursegroup_membership {
5332: my ($cdom,$cnum,$membership) = @_;
5333: my $result = &put('groupmembership',$membership,$cdom,$cnum);
5334: return $result;
5335: }
5336:
1.682 raeburn 5337: sub get_active_groups {
5338: my ($udom,$uname,$cdom,$cnum) = @_;
5339: my $now = time;
5340: my %groups = ();
5341: foreach my $key (keys(%env)) {
1.811 albertel 5342: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 5343: my ($start,$end) = split(/\./,$env{$key});
5344: if (($end!=0) && ($end<$now)) { next; }
5345: if (($start!=0) && ($start>$now)) { next; }
5346: if ($1 eq $cdom && $2 eq $cnum) {
5347: $groups{$3} = $env{$key} ;
5348: }
5349: }
5350: }
5351: return %groups;
5352: }
5353:
1.683 raeburn 5354: sub get_group_membership {
5355: my ($cdom,$cnum,$group) = @_;
5356: return(&dump('groupmembership',$cdom,$cnum,$group));
5357: }
5358:
5359: sub get_users_groups {
5360: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 5361: my @usersgroups;
1.683 raeburn 5362: my $cachetime=1800;
5363:
5364: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 5365: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
5366: if (defined($cached)) {
1.734 albertel 5367: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 5368: } else {
5369: $grouplist = '';
1.816 raeburn 5370: my $courseurl = &courseid_to_courseurl($courseid);
5371: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 5372: my $access_end = $env{'course.'.$courseid.
5373: '.default_enrollment_end_date'};
5374: my $now = time;
5375: foreach my $key (keys(%roleshash)) {
5376: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
5377: my $group = $1;
5378: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
5379: my $start = $2;
5380: my $end = $1;
5381: if ($start == -1) { next; } # deleted from group
5382: if (($start!=0) && ($start>$now)) { next; }
5383: if (($end!=0) && ($end<$now)) {
5384: if ($access_end && $access_end < $now) {
5385: if ($access_end - $end < 86400) {
5386: push(@usersgroups,$group);
1.733 raeburn 5387: }
5388: }
1.817 raeburn 5389: next;
1.733 raeburn 5390: }
1.817 raeburn 5391: push(@usersgroups,$group);
1.683 raeburn 5392: }
5393: }
5394: }
1.817 raeburn 5395: @usersgroups = &sort_course_groups($courseid,@usersgroups);
5396: $grouplist = join(':',@usersgroups);
5397: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 5398: }
1.733 raeburn 5399: return @usersgroups;
1.683 raeburn 5400: }
5401:
5402: sub devalidate_getgroups_cache {
5403: my ($udom,$uname,$cdom,$cnum)=@_;
5404: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 5405:
1.683 raeburn 5406: my $hashid="$udom:$uname:$courseid";
5407: &devalidate_cache_new('getgroups',$hashid);
5408: }
5409:
1.12 www 5410: # ------------------------------------------------------------------ Plain Text
5411:
5412: sub plaintext {
1.742 raeburn 5413: my ($short,$type,$cid) = @_;
1.758 albertel 5414: if ($short =~ /^cr/) {
5415: return (split('/',$short))[-1];
5416: }
1.742 raeburn 5417: if (!defined($cid)) {
5418: $cid = $env{'request.course.id'};
5419: }
5420: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
5421: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
5422: '.plaintext'});
5423: }
5424: my %rolenames = (
5425: Course => 'std',
5426: Group => 'alt1',
5427: );
5428: if (defined($type) &&
5429: defined($rolenames{$type}) &&
5430: defined($prp{$short}{$rolenames{$type}})) {
5431: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
5432: } else {
5433: return &Apache::lonlocal::mt($prp{$short}{'std'});
5434: }
1.12 www 5435: }
5436:
5437: # ----------------------------------------------------------------- Assign Role
5438:
5439: sub assignrole {
1.957 raeburn 5440: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
5441: $context)=@_;
1.21 www 5442: my $mrole;
5443: if ($role =~ /^cr\//) {
1.393 www 5444: my $cwosec=$url;
1.811 albertel 5445: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 5446: unless (&allowed('ccr',$cwosec)) {
1.104 www 5447: &logthis('Refused custom assignrole: '.
5448: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 5449: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 5450: return 'refused';
5451: }
1.21 www 5452: $mrole='cr';
1.678 raeburn 5453: } elsif ($role =~ /^gr\//) {
5454: my $cwogrp=$url;
1.811 albertel 5455: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 5456: unless (&allowed('mdg',$cwogrp)) {
5457: &logthis('Refused group assignrole: '.
5458: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
5459: $env{'user.name'}.' at '.$env{'user.domain'});
5460: return 'refused';
5461: }
5462: $mrole='gr';
1.21 www 5463: } else {
1.82 www 5464: my $cwosec=$url;
1.811 albertel 5465: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 5466: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
5467: my $refused;
5468: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
5469: if (!(&allowed('c'.$role,$url))) {
5470: $refused = 1;
5471: }
5472: } else {
5473: $refused = 1;
5474: }
1.947 raeburn 5475: if ($refused) {
5476: if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5477: $refused = '';
5478: } else {
5479: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
5480: ' '.$role.' '.$end.' '.$start.' by '.
5481: $env{'user.name'}.' at '.$env{'user.domain'});
5482: return 'refused';
5483: }
1.932 raeburn 5484: }
1.104 www 5485: }
1.21 www 5486: $mrole=$role;
5487: }
1.620 albertel 5488: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5489: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 5490: if ($end) { $command.='_'.$end; }
1.21 www 5491: if ($start) {
5492: if ($end) {
1.81 www 5493: $command.='_'.$start;
1.21 www 5494: } else {
1.81 www 5495: $command.='_0_'.$start;
1.21 www 5496: }
5497: }
1.739 raeburn 5498: my $origstart = $start;
5499: my $origend = $end;
1.957 raeburn 5500: my $delflag;
1.357 www 5501: # actually delete
5502: if ($deleteflag) {
1.373 www 5503: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 5504: # modify command to delete the role
1.620 albertel 5505: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 5506: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 5507: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 5508: # set start and finish to negative values for userrolelog
5509: $start=-1;
5510: $end=-1;
1.957 raeburn 5511: $delflag = 1;
1.357 www 5512: }
5513: }
5514: # send command
1.349 www 5515: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 5516: # log new user role if status is ok
1.349 www 5517: if ($answer eq 'ok') {
1.663 raeburn 5518: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 5519: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 5520: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 5521: unless ($role =~ /^gr/) {
5522: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 5523: $origstart,$selfenroll,$context);
1.739 raeburn 5524: }
1.349 www 5525: }
5526: return $answer;
1.169 harris41 5527: }
5528:
5529: # -------------------------------------------------- Modify user authentication
1.197 www 5530: # Overrides without validation
5531:
1.169 harris41 5532: sub modifyuserauth {
5533: my ($udom,$uname,$umode,$upass)=@_;
5534: my $uhome=&homeserver($uname,$udom);
1.197 www 5535: unless (&allowed('mau',$udom)) { return 'refused'; }
5536: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 5537: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5538: ' in domain '.$env{'request.role.domain'});
1.169 harris41 5539: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
5540: &escape($upass),$uhome);
1.620 albertel 5541: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 5542: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
5543: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
5544: &log($udom,,$uname,$uhome,
1.620 albertel 5545: 'Authentication changed by '.$env{'user.domain'}.', '.
5546: $env{'user.name'}.', '.$umode.
1.197 www 5547: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 5548: unless ($reply eq 'ok') {
1.197 www 5549: &logthis('Authentication mode error: '.$reply);
1.169 harris41 5550: return 'error: '.$reply;
5551: }
1.170 harris41 5552: return 'ok';
1.80 www 5553: }
5554:
1.81 www 5555: # --------------------------------------------------------------- Modify a user
1.80 www 5556:
1.81 www 5557: sub modifyuser {
1.206 matthew 5558: my ($udom, $uname, $uid,
5559: $umode, $upass, $first,
5560: $middle, $last, $gene,
1.387 www 5561: $forceid, $desiredhome, $email)=@_;
1.807 albertel 5562: $udom= &LONCAPA::clean_domain($udom);
5563: $uname=&LONCAPA::clean_username($uname);
1.81 www 5564: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 5565: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 5566: $last.', '.$gene.'(forceid: '.$forceid.')'.
5567: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
5568: ' desiredhome not specified').
1.620 albertel 5569: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5570: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 5571: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 5572: # ----------------------------------------------------------------- Create User
1.406 albertel 5573: if (($uhome eq 'no_host') &&
5574: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 5575: my $unhome='';
1.844 albertel 5576: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 5577: $unhome = $desiredhome;
1.620 albertel 5578: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
5579: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 5580: } else { # load balancing routine for determining $unhome
1.81 www 5581: my $loadm=10000000;
1.841 albertel 5582: my %servers = &get_servers($udom,'library');
5583: foreach my $tryserver (keys(%servers)) {
5584: my $answer=reply('load',$tryserver);
5585: if (($answer=~/\d+/) && ($answer<$loadm)) {
5586: $loadm=$answer;
5587: $unhome=$tryserver;
5588: }
1.80 www 5589: }
5590: }
5591: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 5592: return 'error: unable to find a home server for '.$uname.
5593: ' in domain '.$udom;
1.80 www 5594: }
5595: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
5596: &escape($upass),$unhome);
5597: unless ($reply eq 'ok') {
5598: return 'error: '.$reply;
5599: }
1.230 stredwic 5600: $uhome=&homeserver($uname,$udom,'true');
1.80 www 5601: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 5602: return 'error: unable verify users home machine.';
1.80 www 5603: }
1.209 matthew 5604: } # End of creation of new user
1.80 www 5605: # ---------------------------------------------------------------------- Add ID
5606: if ($uid) {
5607: $uid=~tr/A-Z/a-z/;
5608: my %uidhash=&idrget($udom,$uname);
1.196 www 5609: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
5610: && (!$forceid)) {
1.80 www 5611: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 5612: return 'error: user id "'.$uid.'" does not match '.
5613: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 5614: }
5615: } else {
5616: &idput($udom,($uname => $uid));
5617: }
5618: }
5619: # -------------------------------------------------------------- Add names, etc
1.313 matthew 5620: my @tmp=&get('environment',
1.899 raeburn 5621: ['firstname','middlename','lastname','generation','id',
5622: 'permanentemail'],
1.134 albertel 5623: $udom,$uname);
1.313 matthew 5624: my %names;
5625: if ($tmp[0] =~ m/^error:.*/) {
5626: %names=();
5627: } else {
5628: %names = @tmp;
5629: }
1.388 www 5630: #
5631: # Make sure to not trash student environment if instructor does not bother
5632: # to supply name and email information
5633: #
5634: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 5635: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 5636: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 5637: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 5638: if ($email) {
5639: $email=~s/[^\w\@\.\-\,]//gs;
5640: if ($email=~/\@/) { $names{'notification'} = $email;
5641: $names{'critnotification'} = $email;
5642: $names{'permanentemail'} = $email; }
5643: }
1.899 raeburn 5644: if ($uid) { $names{'id'} = $uid; }
1.134 albertel 5645: my $reply = &put('environment', \%names, $udom,$uname);
5646: if ($reply ne 'ok') { return 'error: '.$reply; }
1.899 raeburn 5647: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680 www 5648: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81 www 5649: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 5650: $umode.', '.$first.', '.$middle.', '.
5651: $last.', '.$gene.' by '.
1.620 albertel 5652: $env{'user.name'}.' at '.$env{'user.domain'});
1.134 albertel 5653: return 'ok';
1.80 www 5654: }
5655:
1.81 www 5656: # -------------------------------------------------------------- Modify student
1.80 www 5657:
1.81 www 5658: sub modifystudent {
5659: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 5660: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
5661: $selfenroll,$context)=@_;
1.455 albertel 5662: if (!$cid) {
1.620 albertel 5663: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5664: return 'not_in_class';
5665: }
1.80 www 5666: }
5667: # --------------------------------------------------------------- Make the user
1.81 www 5668: my $reply=&modifyuser
1.209 matthew 5669: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 5670: $desiredhome,$email);
1.80 www 5671: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 5672: # This will cause &modify_student_enrollment to get the uid from the
5673: # students environment
5674: $uid = undef if (!$forceid);
1.455 albertel 5675: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 5676: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 5677: return $reply;
5678: }
5679:
5680: sub modify_student_enrollment {
1.957 raeburn 5681: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 5682: my ($cdom,$cnum,$chome);
5683: if (!$cid) {
1.620 albertel 5684: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5685: return 'not_in_class';
5686: }
1.620 albertel 5687: $cdom=$env{'course.'.$cid.'.domain'};
5688: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 5689: } else {
5690: ($cdom,$cnum)=split(/_/,$cid);
5691: }
1.620 albertel 5692: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 5693: if (!$chome) {
1.457 raeburn 5694: $chome=&homeserver($cnum,$cdom);
1.297 matthew 5695: }
1.455 albertel 5696: if (!$chome) { return 'unknown_course'; }
1.297 matthew 5697: # Make sure the user exists
1.81 www 5698: my $uhome=&homeserver($uname,$udom);
5699: if (($uhome eq '') || ($uhome eq 'no_host')) {
5700: return 'error: no such user';
5701: }
1.297 matthew 5702: # Get student data if we were not given enough information
5703: if (!defined($first) || $first eq '' ||
5704: !defined($last) || $last eq '' ||
5705: !defined($uid) || $uid eq '' ||
5706: !defined($middle) || $middle eq '' ||
5707: !defined($gene) || $gene eq '') {
1.294 matthew 5708: # They did not supply us with enough data to enroll the student, so
5709: # we need to pick up more information.
1.297 matthew 5710: my %tmp = &get('environment',
1.294 matthew 5711: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 5712: ,$udom,$uname);
5713:
1.800 albertel 5714: #foreach my $key (keys(%tmp)) {
5715: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 5716: #}
1.294 matthew 5717: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
5718: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
5719: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 5720: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 5721: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
5722: }
1.556 albertel 5723: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 5724: my $reply=cput('classlist',
5725: {"$uname:$udom" =>
1.515 raeburn 5726: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 5727: $cdom,$cnum);
1.81 www 5728: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
5729: return 'error: '.$reply;
1.652 albertel 5730: } else {
5731: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 5732: }
1.297 matthew 5733: # Add student role to user
1.83 www 5734: my $uurl='/'.$cid;
1.81 www 5735: $uurl=~s/\_/\//g;
5736: if ($usec) {
5737: $uurl.='/'.$usec;
5738: }
1.957 raeburn 5739: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 5740: }
5741:
1.556 albertel 5742: sub format_name {
5743: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
5744: my $name;
5745: if ($first ne 'lastname') {
5746: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
5747: } else {
5748: if ($lastname=~/\S/) {
5749: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
5750: $name=~s/\s+,/,/;
5751: } else {
5752: $name.= $firstname.' '.$middlename.' '.$generation;
5753: }
5754: }
5755: $name=~s/^\s+//;
5756: $name=~s/\s+$//;
5757: $name=~s/\s+/ /g;
5758: return $name;
5759: }
5760:
1.84 www 5761: # ------------------------------------------------- Write to course preferences
5762:
5763: sub writecoursepref {
5764: my ($courseid,%prefs)=@_;
5765: $courseid=~s/^\///;
5766: $courseid=~s/\_/\//g;
5767: my ($cdomain,$cnum)=split(/\//,$courseid);
5768: my $chome=homeserver($cnum,$cdomain);
5769: if (($chome eq '') || ($chome eq 'no_host')) {
5770: return 'error: no such course';
5771: }
5772: my $cstring='';
1.800 albertel 5773: foreach my $pref (keys(%prefs)) {
5774: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 5775: }
1.84 www 5776: $cstring=~s/\&$//;
5777: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
5778: }
5779:
5780: # ---------------------------------------------------------- Make/modify course
5781:
5782: sub createcourse {
1.741 raeburn 5783: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
5784: $course_owner,$crstype)=@_;
1.84 www 5785: $url=&declutter($url);
5786: my $cid='';
1.264 matthew 5787: unless (&allowed('ccc',$udom)) {
1.84 www 5788: return 'refused';
5789: }
5790: # ------------------------------------------------------------------- Create ID
1.674 www 5791: my $uname=int(1+rand(9)).
5792: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
5793: substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84 www 5794: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
5795: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 5796: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 5797: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5798: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
5799: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 5800: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5801: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5802: return 'error: unable to generate unique course-ID';
5803: }
5804: }
1.264 matthew 5805: # ------------------------------------------------ Check supplied server name
1.620 albertel 5806: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845 albertel 5807: if (! &is_library($course_server)) {
1.264 matthew 5808: return 'error:bad server name '.$course_server;
5809: }
1.84 www 5810: # ------------------------------------------------------------- Make the course
5811: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 5812: $course_server);
1.84 www 5813: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 5814: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5815: if (($uhome eq '') || ($uhome eq 'no_host')) {
5816: return 'error: no such course';
5817: }
1.271 www 5818: # ----------------------------------------------------------------- Course made
1.516 raeburn 5819: # log existence
1.918 raeburn 5820: my $newcourse = {
5821: $udom.'_'.$uname => {
1.921 raeburn 5822: description => $description,
5823: inst_code => $inst_code,
5824: owner => $course_owner,
5825: type => $crstype,
1.918 raeburn 5826: },
5827: };
1.921 raeburn 5828: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 5829: # set toplevel url
1.271 www 5830: my $topurl=$url;
5831: unless ($nonstandard) {
5832: # ------------------------------------------ For standard courses, make top url
5833: my $mapurl=&clutter($url);
1.278 www 5834: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 5835: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 5836: <map>
5837: <resource id="1" type="start"></resource>
5838: <resource id="2" src="$mapurl"></resource>
5839: <resource id="3" type="finish"></resource>
5840: <link index="1" from="1" to="2"></link>
5841: <link index="2" from="2" to="3"></link>
5842: </map>
5843: ENDINITMAP
5844: $topurl=&declutter(
1.638 albertel 5845: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 5846: );
5847: }
5848: # ----------------------------------------------------------- Write preferences
1.84 www 5849: &writecoursepref($udom.'_'.$uname,
5850: ('description' => $description,
1.271 www 5851: 'url' => $topurl));
1.84 www 5852: return '/'.$udom.'/'.$uname;
5853: }
5854:
1.813 albertel 5855: sub is_course {
5856: my ($cdom,$cnum) = @_;
5857: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 5858: undef,'.');
1.813 albertel 5859: if (exists($courses{$cdom.'_'.$cnum})) {
5860: return 1;
5861: }
5862: return 0;
5863: }
5864:
1.21 www 5865: # ---------------------------------------------------------- Assign Custom Role
5866:
5867: sub assigncustomrole {
1.957 raeburn 5868: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 5869: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 5870: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 5871: }
5872:
5873: # ----------------------------------------------------------------- Revoke Role
5874:
5875: sub revokerole {
1.957 raeburn 5876: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 5877: my $now=time;
1.957 raeburn 5878: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag,$selfenroll,$context);
1.21 www 5879: }
5880:
5881: # ---------------------------------------------------------- Revoke Custom Role
5882:
5883: sub revokecustomrole {
1.957 raeburn 5884: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 5885: my $now=time;
1.357 www 5886: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 5887: $deleteflag,$selfenroll,$context);
1.17 www 5888: }
5889:
1.533 banghart 5890: # ------------------------------------------------------------ Disk usage
1.535 albertel 5891: sub diskusage {
1.955 raeburn 5892: my ($udom,$uname,$directorypath,$getpropath)=@_;
5893: $directorypath =~ s/\/$//;
5894: my $listing=&reply('du2:'.&escape($directorypath).':'
5895: .&escape($getpropath).':'.&escape($uname).':'
5896: .&escape($udom),homeserver($uname,$udom));
5897: if ($listing eq 'unknown_cmd') {
5898: if ($getpropath) {
5899: $directorypath = &propath($udom,$uname).'/'.$directorypath;
5900: }
5901: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
5902: }
1.514 albertel 5903: return $listing;
1.512 banghart 5904: }
5905:
1.566 banghart 5906: sub is_locked {
5907: my ($file_name, $domain, $user) = @_;
5908: my @check;
5909: my $is_locked;
5910: push @check, $file_name;
1.613 albertel 5911: my %locked = &get('file_permissions',\@check,
1.620 albertel 5912: $env{'user.domain'},$env{'user.name'});
1.615 albertel 5913: my ($tmp)=keys(%locked);
5914: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 5915:
1.566 banghart 5916: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 5917: $is_locked = 'false';
5918: foreach my $entry (@{$locked{$file_name}}) {
5919: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 5920: $is_locked = 'true';
5921: last;
1.745 raeburn 5922: }
5923: }
1.566 banghart 5924: } else {
5925: $is_locked = 'false';
5926: }
5927: }
5928:
1.759 albertel 5929: sub declutter_portfile {
5930: my ($file) = @_;
1.833 albertel 5931: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 5932: return $file;
5933: }
5934:
1.559 banghart 5935: # ------------------------------------------------------------- Mark as Read Only
5936:
5937: sub mark_as_readonly {
5938: my ($domain,$user,$files,$what) = @_;
1.613 albertel 5939: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5940: my ($tmp)=keys(%current_permissions);
5941: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 5942: foreach my $file (@{$files}) {
1.759 albertel 5943: $file = &declutter_portfile($file);
1.561 banghart 5944: push(@{$current_permissions{$file}},$what);
1.559 banghart 5945: }
1.613 albertel 5946: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 5947: return;
5948: }
5949:
1.572 banghart 5950: # ------------------------------------------------------------Save Selected Files
5951:
5952: sub save_selected_files {
5953: my ($user, $path, @files) = @_;
5954: my $filename = $user."savedfiles";
1.573 banghart 5955: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 5956: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 5957: foreach my $file (@files) {
1.620 albertel 5958: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 5959: }
5960: foreach my $file (@other_files) {
1.574 banghart 5961: print (OUT $file."\n");
1.572 banghart 5962: }
1.574 banghart 5963: close (OUT);
1.572 banghart 5964: return 'ok';
5965: }
5966:
1.574 banghart 5967: sub clear_selected_files {
5968: my ($user) = @_;
5969: my $filename = $user."savedfiles";
5970: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5971: print (OUT undef);
5972: close (OUT);
5973: return ("ok");
5974: }
5975:
1.572 banghart 5976: sub files_in_path {
5977: my ($user, $path) = @_;
5978: my $filename = $user."savedfiles";
5979: my %return_files;
1.574 banghart 5980: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 5981: while (my $line_in = <IN>) {
1.574 banghart 5982: chomp ($line_in);
5983: my @paths_and_file = split (m!/!, $line_in);
5984: my $file_part = pop (@paths_and_file);
5985: my $path_part = join ('/', @paths_and_file);
1.573 banghart 5986: $path_part.='/';
5987: my $path_and_file = $path_part.$file_part;
5988: if ($path_part eq $path) {
5989: $return_files{$file_part}= 'selected';
5990: }
5991: }
1.574 banghart 5992: close (IN);
5993: return (\%return_files);
1.572 banghart 5994: }
5995:
5996: # called in portfolio select mode, to show files selected NOT in current directory
5997: sub files_not_in_path {
5998: my ($user, $path) = @_;
5999: my $filename = $user."savedfiles";
6000: my @return_files;
6001: my $path_part;
1.800 albertel 6002: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6003: while (my $line = <IN>) {
1.572 banghart 6004: #ok, I know it's clunky, but I want it to work
1.800 albertel 6005: my @paths_and_file = split(m|/|, $line);
6006: my $file_part = pop(@paths_and_file);
6007: chomp($file_part);
6008: my $path_part = join('/', @paths_and_file);
1.572 banghart 6009: $path_part .= '/';
6010: my $path_and_file = $path_part.$file_part;
6011: if ($path_part ne $path) {
1.800 albertel 6012: push(@return_files, ($path_and_file));
1.572 banghart 6013: }
6014: }
1.800 albertel 6015: close(OUT);
1.574 banghart 6016: return (@return_files);
1.572 banghart 6017: }
6018:
1.745 raeburn 6019: #----------------------------------------------Get portfolio file permissions
1.629 banghart 6020:
1.745 raeburn 6021: sub get_portfile_permissions {
6022: my ($domain,$user) = @_;
1.613 albertel 6023: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 6024: my ($tmp)=keys(%current_permissions);
6025: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6026: return \%current_permissions;
6027: }
6028:
6029: #---------------------------------------------Get portfolio file access controls
6030:
1.749 raeburn 6031: sub get_access_controls {
1.745 raeburn 6032: my ($current_permissions,$group,$file) = @_;
1.769 albertel 6033: my %access;
6034: my $real_file = $file;
6035: $file =~ s/\.meta$//;
1.745 raeburn 6036: if (defined($file)) {
1.749 raeburn 6037: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
6038: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 6039: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 6040: }
6041: }
1.745 raeburn 6042: } else {
1.749 raeburn 6043: foreach my $key (keys(%{$current_permissions})) {
6044: if ($key =~ /\0accesscontrol$/) {
6045: if (defined($group)) {
6046: if ($key !~ m-^\Q$group\E/-) {
6047: next;
6048: }
6049: }
6050: my ($fullpath) = split(/\0/,$key);
6051: if (ref($$current_permissions{$key}) eq 'HASH') {
6052: foreach my $control (keys(%{$$current_permissions{$key}})) {
6053: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
6054: }
6055: }
6056: }
6057: }
6058: }
6059: return %access;
6060: }
6061:
6062: sub modify_access_controls {
6063: my ($file_name,$changes,$domain,$user)=@_;
6064: my ($outcome,$deloutcome);
6065: my %store_permissions;
6066: my %new_values;
6067: my %new_control;
6068: my %translation;
6069: my @deletions = ();
6070: my $now = time;
6071: if (exists($$changes{'activate'})) {
6072: if (ref($$changes{'activate'}) eq 'HASH') {
6073: my @newitems = sort(keys(%{$$changes{'activate'}}));
6074: my $numnew = scalar(@newitems);
6075: for (my $i=0; $i<$numnew; $i++) {
6076: my $newkey = $newitems[$i];
6077: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 6078: if ($newkey =~ /^\d+:/) {
6079: $newkey =~ s/^(\d+)/$newid/;
6080: $translation{$1} = $newid;
6081: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
6082: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
6083: $translation{$1} = $newid;
6084: }
1.749 raeburn 6085: $new_values{$file_name."\0".$newkey} =
6086: $$changes{'activate'}{$newitems[$i]};
6087: $new_control{$newkey} = $now;
6088: }
6089: }
6090: }
6091: my %todelete;
6092: my %changed_items;
6093: foreach my $action ('delete','update') {
6094: if (exists($$changes{$action})) {
6095: if (ref($$changes{$action}) eq 'HASH') {
6096: foreach my $key (keys(%{$$changes{$action}})) {
6097: my ($itemnum) = ($key =~ /^([^:]+):/);
6098: if ($action eq 'delete') {
6099: $todelete{$itemnum} = 1;
6100: } else {
6101: $changed_items{$itemnum} = $key;
6102: }
6103: }
1.745 raeburn 6104: }
6105: }
1.749 raeburn 6106: }
6107: # get lock on access controls for file.
6108: my $lockhash = {
6109: $file_name."\0".'locked_access_records' => $env{'user.name'}.
6110: ':'.$env{'user.domain'},
6111: };
6112: my $tries = 0;
6113: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6114:
6115: while (($gotlock ne 'ok') && $tries <3) {
6116: $tries ++;
6117: sleep 1;
6118: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6119: }
6120: if ($gotlock eq 'ok') {
6121: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
6122: my ($tmp)=keys(%curr_permissions);
6123: if ($tmp=~/^error:/) { undef(%curr_permissions); }
6124: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
6125: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
6126: if (ref($curr_controls) eq 'HASH') {
6127: foreach my $control_item (keys(%{$curr_controls})) {
6128: my ($itemnum) = ($control_item =~ /^([^:]+):/);
6129: if (defined($todelete{$itemnum})) {
6130: push(@deletions,$file_name."\0".$control_item);
6131: } else {
6132: if (defined($changed_items{$itemnum})) {
6133: $new_control{$changed_items{$itemnum}} = $now;
6134: push(@deletions,$file_name."\0".$control_item);
6135: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
6136: } else {
6137: $new_control{$control_item} = $$curr_controls{$control_item};
6138: }
6139: }
1.745 raeburn 6140: }
6141: }
6142: }
1.749 raeburn 6143: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
6144: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
6145: $outcome = &put('file_permissions',\%new_values,$domain,$user);
6146: # remove lock
6147: my @del_lock = ($file_name."\0".'locked_access_records');
6148: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 6149: my ($file,$group);
6150: if (&is_course($domain,$user)) {
6151: ($group,$file) = split(/\//,$file_name,2);
6152: } else {
6153: $file = $file_name;
6154: }
6155: my $sqlresult =
6156: &update_portfolio_table($user,$domain,$file,'portfolio_access',
6157: $group);
1.749 raeburn 6158: } else {
6159: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 6160: }
1.749 raeburn 6161: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 6162: }
6163:
1.827 raeburn 6164: sub make_public_indefinitely {
6165: my ($requrl) = @_;
6166: my $now = time;
6167: my $action = 'activate';
6168: my $aclnum = 0;
6169: if (&is_portfolio_url($requrl)) {
6170: my (undef,$udom,$unum,$file_name,$group) =
6171: &parse_portfolio_url($requrl);
6172: my $current_perms = &get_portfile_permissions($udom,$unum);
6173: my %access_controls = &get_access_controls($current_perms,
6174: $group,$file_name);
6175: foreach my $key (keys(%{$access_controls{$file_name}})) {
6176: my ($num,$scope,$end,$start) =
6177: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6178: if ($scope eq 'public') {
6179: if ($start <= $now && $end == 0) {
6180: $action = 'none';
6181: } else {
6182: $action = 'update';
6183: $aclnum = $num;
6184: }
6185: last;
6186: }
6187: }
6188: if ($action eq 'none') {
6189: return 'ok';
6190: } else {
6191: my %changes;
6192: my $newend = 0;
6193: my $newstart = $now;
6194: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
6195: $changes{$action}{$newkey} = {
6196: type => 'public',
6197: time => {
6198: start => $newstart,
6199: end => $newend,
6200: },
6201: };
6202: my ($outcome,$deloutcome,$new_values,$translation) =
6203: &modify_access_controls($file_name,\%changes,$udom,$unum);
6204: return $outcome;
6205: }
6206: } else {
6207: return 'invalid';
6208: }
6209: }
6210:
1.745 raeburn 6211: #------------------------------------------------------Get Marked as Read Only
6212:
6213: sub get_marked_as_readonly {
6214: my ($domain,$user,$what,$group) = @_;
6215: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 6216: my @readonly_files;
1.629 banghart 6217: my $cmp1=$what;
6218: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 6219: while (my ($file_name,$value) = each(%{$current_permissions})) {
6220: if (defined($group)) {
6221: if ($file_name !~ m-^\Q$group\E/-) {
6222: next;
6223: }
6224: }
1.561 banghart 6225: if (ref($value) eq "ARRAY"){
6226: foreach my $stored_what (@{$value}) {
1.629 banghart 6227: my $cmp2=$stored_what;
1.759 albertel 6228: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 6229: $cmp2=join('',@{$stored_what});
1.745 raeburn 6230: }
1.629 banghart 6231: if ($cmp1 eq $cmp2) {
1.561 banghart 6232: push(@readonly_files, $file_name);
1.745 raeburn 6233: last;
1.563 banghart 6234: } elsif (!defined($what)) {
6235: push(@readonly_files, $file_name);
1.745 raeburn 6236: last;
1.561 banghart 6237: }
6238: }
1.745 raeburn 6239: }
1.561 banghart 6240: }
6241: return @readonly_files;
6242: }
1.577 banghart 6243: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 6244:
1.577 banghart 6245: sub get_marked_as_readonly_hash {
1.745 raeburn 6246: my ($current_permissions,$group,$what) = @_;
1.577 banghart 6247: my %readonly_files;
1.745 raeburn 6248: while (my ($file_name,$value) = each(%{$current_permissions})) {
6249: if (defined($group)) {
6250: if ($file_name !~ m-^\Q$group\E/-) {
6251: next;
6252: }
6253: }
1.577 banghart 6254: if (ref($value) eq "ARRAY"){
6255: foreach my $stored_what (@{$value}) {
1.745 raeburn 6256: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 6257: foreach my $lock_descriptor(@{$stored_what}) {
6258: if ($lock_descriptor eq 'graded') {
6259: $readonly_files{$file_name} = 'graded';
6260: } elsif ($lock_descriptor eq 'handback') {
6261: $readonly_files{$file_name} = 'handback';
6262: } else {
6263: if (!exists($readonly_files{$file_name})) {
6264: $readonly_files{$file_name} = 'locked';
6265: }
6266: }
1.745 raeburn 6267: }
1.750 banghart 6268: }
1.577 banghart 6269: }
6270: }
6271: }
6272: return %readonly_files;
6273: }
1.559 banghart 6274: # ------------------------------------------------------------ Unmark as Read Only
6275:
6276: sub unmark_as_readonly {
1.629 banghart 6277: # unmarks $file_name (if $file_name is defined), or all files locked by $what
6278: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 6279: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 6280: $file_name = &declutter_portfile($file_name);
1.634 albertel 6281: my $symb_crs = $what;
6282: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 6283: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 6284: my ($tmp)=keys(%current_permissions);
6285: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6286: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 6287: foreach my $file (@readonly_files) {
1.759 albertel 6288: my $clean_file = &declutter_portfile($file);
6289: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 6290: my $current_locks = $current_permissions{$file};
1.563 banghart 6291: my @new_locks;
6292: my @del_keys;
6293: if (ref($current_locks) eq "ARRAY"){
6294: foreach my $locker (@{$current_locks}) {
1.632 albertel 6295: my $compare=$locker;
1.749 raeburn 6296: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 6297: $compare=join('',@{$locker});
1.746 raeburn 6298: if ($compare ne $symb_crs) {
6299: push(@new_locks, $locker);
6300: }
1.563 banghart 6301: }
6302: }
1.650 albertel 6303: if (scalar(@new_locks) > 0) {
1.563 banghart 6304: $current_permissions{$file} = \@new_locks;
6305: } else {
6306: push(@del_keys, $file);
1.613 albertel 6307: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 6308: delete($current_permissions{$file});
1.563 banghart 6309: }
6310: }
1.561 banghart 6311: }
1.613 albertel 6312: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6313: return;
6314: }
1.512 banghart 6315:
1.17 www 6316: # ------------------------------------------------------------ Directory lister
6317:
6318: sub dirlist {
1.955 raeburn 6319: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 6320: $uri=~s/^\///;
6321: $uri=~s/\/$//;
1.253 stredwic 6322: my ($udom, $uname);
1.955 raeburn 6323: if ($getuserdir) {
1.253 stredwic 6324: $udom = $userdomain;
6325: $uname = $username;
1.955 raeburn 6326: } else {
6327: (undef,$udom,$uname)=split(/\//,$uri);
6328: if(defined($userdomain)) {
6329: $udom = $userdomain;
6330: }
6331: if(defined($username)) {
6332: $uname = $username;
6333: }
1.253 stredwic 6334: }
1.955 raeburn 6335: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 6336:
1.955 raeburn 6337: $dirRoot = $perlvar{'lonDocRoot'};
6338: if (defined($getpropath)) {
6339: $dirRoot = &propath($udom,$uname);
1.253 stredwic 6340: $dirRoot =~ s/\/$//;
1.955 raeburn 6341: } elsif (defined($getuserdir)) {
6342: my $subdir=$uname.'__';
6343: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
6344: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
6345: ."/$udom/$subdir/$uname";
6346: } elsif (defined($alternateRoot)) {
6347: $dirRoot = $alternateRoot;
1.751 banghart 6348: }
1.253 stredwic 6349:
6350: if($udom) {
6351: if($uname) {
1.955 raeburn 6352: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 6353: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 6354: .':'.&escape($uname).':'.&escape($udom),
6355: &homeserver($uname,$udom));
6356: if ($listing eq 'unknown_cmd') {
6357: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
6358: &homeserver($uname,$udom));
6359: } else {
6360: @listing_results = map { &unescape($_); } split(/:/,$listing);
6361: }
1.605 matthew 6362: if ($listing eq 'unknown_cmd') {
1.800 albertel 6363: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
6364: &homeserver($uname,$udom));
1.605 matthew 6365: @listing_results = split(/:/,$listing);
6366: } else {
6367: @listing_results = map { &unescape($_); } split(/:/,$listing);
6368: }
6369: return @listing_results;
1.955 raeburn 6370: } elsif(!$alternateRoot) {
1.800 albertel 6371: my %allusers;
1.841 albertel 6372: my %servers = &get_servers($udom,'library');
1.955 raeburn 6373: foreach my $tryserver (keys(%servers)) {
6374: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
6375: &escape($udom),$tryserver);
6376: if ($listing eq 'unknown_cmd') {
6377: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
6378: $udom, $tryserver);
6379: } else {
6380: @listing_results = map { &unescape($_); } split(/:/,$listing);
6381: }
1.841 albertel 6382: if ($listing eq 'unknown_cmd') {
6383: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
6384: $udom, $tryserver);
6385: @listing_results = split(/:/,$listing);
6386: } else {
6387: @listing_results =
6388: map { &unescape($_); } split(/:/,$listing);
6389: }
6390: if ($listing_results[0] ne 'no_such_dir' &&
6391: $listing_results[0] ne 'empty' &&
6392: $listing_results[0] ne 'con_lost') {
6393: foreach my $line (@listing_results) {
6394: my ($entry) = split(/&/,$line,2);
6395: $allusers{$entry} = 1;
6396: }
6397: }
1.253 stredwic 6398: }
6399: my $alluserstr='';
1.800 albertel 6400: foreach my $user (sort(keys(%allusers))) {
6401: $alluserstr.=$user.'&user:';
1.253 stredwic 6402: }
6403: $alluserstr=~s/:$//;
6404: return split(/:/,$alluserstr);
6405: } else {
1.800 albertel 6406: return ('missing user name');
1.253 stredwic 6407: }
1.955 raeburn 6408: } elsif(!defined($getpropath)) {
1.841 albertel 6409: my @all_domains = sort(&all_domains());
1.955 raeburn 6410: foreach my $domain (@all_domains) {
6411: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
6412: }
6413: return @all_domains;
6414: } else {
1.800 albertel 6415: return ('missing domain');
1.275 stredwic 6416: }
6417: }
6418:
6419: # --------------------------------------------- GetFileTimestamp
6420: # This function utilizes dirlist and returns the date stamp for
6421: # when it was last modified. It will also return an error of -1
6422: # if an error occurs
6423:
6424: sub GetFileTimestamp {
1.955 raeburn 6425: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 6426: $studentDomain = &LONCAPA::clean_domain($studentDomain);
6427: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 6428: my ($fileStat) =
6429: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
6430: undef,$getuserdir);
1.275 stredwic 6431: my @stats = split('&', $fileStat);
6432: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 6433: # @stats contains first the filename, then the stat output
6434: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 6435: } else {
6436: return -1;
1.253 stredwic 6437: }
1.26 www 6438: }
6439:
1.712 albertel 6440: sub stat_file {
6441: my ($uri) = @_;
1.787 albertel 6442: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 6443:
1.955 raeburn 6444: my ($udom,$uname,$file);
1.712 albertel 6445: if ($uri =~ m-^/(uploaded|editupload)/-) {
6446: ($udom,$uname,$file) =
1.811 albertel 6447: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 6448: $file = 'userfiles/'.$file;
6449: }
6450: if ($uri =~ m-^/res/-) {
6451: ($udom,$uname) =
1.807 albertel 6452: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 6453: $file = $uri;
6454: }
6455:
6456: if (!$udom || !$uname || !$file) {
6457: # unable to handle the uri
6458: return ();
6459: }
1.956 raeburn 6460: my $getpropath;
6461: if ($file =~ /^userfiles\//) {
6462: $getpropath = 1;
6463: }
1.955 raeburn 6464: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 6465: my @stats = split('&', $result);
1.721 banghart 6466:
1.712 albertel 6467: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
6468: shift(@stats); #filename is first
6469: return @stats;
6470: }
6471: return ();
6472: }
6473:
1.26 www 6474: # -------------------------------------------------------- Value of a Condition
6475:
1.713 albertel 6476: # gets the value of a specific preevaluated condition
6477: # stored in the string $env{user.state.<cid>}
6478: # or looks up a condition reference in the bighash and if if hasn't
6479: # already been evaluated recurses into docondval to get the value of
6480: # the condition, then memoizing it to
6481: # $env{user.state.<cid>.<condition>}
1.40 www 6482: sub directcondval {
6483: my $number=shift;
1.620 albertel 6484: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 6485: &Apache::lonuserstate::evalstate();
6486: }
1.713 albertel 6487: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
6488: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
6489: } elsif ($number =~ /^_/) {
6490: my $sub_condition;
6491: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6492: &GDBM_READER(),0640)) {
6493: $sub_condition=$bighash{'conditions'.$number};
6494: untie(%bighash);
6495: }
6496: my $value = &docondval($sub_condition);
1.949 raeburn 6497: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 6498: return $value;
6499: }
1.620 albertel 6500: if ($env{'user.state.'.$env{'request.course.id'}}) {
6501: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 6502: } else {
6503: return 2;
6504: }
6505: }
6506:
1.713 albertel 6507: # get the collection of conditions for this resource
1.26 www 6508: sub condval {
6509: my $condidx=shift;
1.54 www 6510: my $allpathcond='';
1.713 albertel 6511: foreach my $cond (split(/\|/,$condidx)) {
6512: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
6513: $allpathcond.=
6514: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
6515: }
1.191 harris41 6516: }
1.54 www 6517: $allpathcond=~s/\|$//;
1.713 albertel 6518: return &docondval($allpathcond);
6519: }
6520:
6521: #evaluates an expression of conditions
6522: sub docondval {
6523: my ($allpathcond) = @_;
6524: my $result=0;
6525: if ($env{'request.course.id'}
6526: && defined($allpathcond)) {
6527: my $operand='|';
6528: my @stack;
6529: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
6530: if ($chunk eq '(') {
6531: push @stack,($operand,$result);
6532: } elsif ($chunk eq ')') {
6533: my $before=pop @stack;
6534: if (pop @stack eq '&') {
6535: $result=$result>$before?$before:$result;
6536: } else {
6537: $result=$result>$before?$result:$before;
6538: }
6539: } elsif (($chunk eq '&') || ($chunk eq '|')) {
6540: $operand=$chunk;
6541: } else {
6542: my $new=directcondval($chunk);
6543: if ($operand eq '&') {
6544: $result=$result>$new?$new:$result;
6545: } else {
6546: $result=$result>$new?$result:$new;
6547: }
6548: }
6549: }
1.26 www 6550: }
6551: return $result;
1.421 albertel 6552: }
6553:
6554: # ---------------------------------------------------- Devalidate courseresdata
6555:
6556: sub devalidatecourseresdata {
6557: my ($coursenum,$coursedomain)=@_;
6558: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6559: &devalidate_cache_new('courseres',$hashid);
1.28 www 6560: }
6561:
1.763 www 6562:
1.200 www 6563: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 6564: #
6565: # Parameters:
6566: # $coursenum - Number of the course.
6567: # $coursedomain - Domain at which the course was created.
6568: # Returns:
6569: # A hash of the course parameters along (I think) with timestamps
6570: # and version info.
1.877 foxr 6571:
1.624 albertel 6572: sub get_courseresdata {
6573: my ($coursenum,$coursedomain)=@_;
1.200 www 6574: my $coursehom=&homeserver($coursenum,$coursedomain);
6575: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6576: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 6577: my %dumpreply;
1.417 albertel 6578: unless (defined($cached)) {
1.624 albertel 6579: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 6580: $result=\%dumpreply;
1.251 albertel 6581: my ($tmp) = keys(%dumpreply);
6582: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 6583: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 6584: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
6585: return $tmp;
1.416 albertel 6586: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 6587: $result=undef;
1.599 albertel 6588: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 6589: }
6590: }
1.624 albertel 6591: return $result;
6592: }
6593:
1.633 albertel 6594: sub devalidateuserresdata {
6595: my ($uname,$udom)=@_;
6596: my $hashid="$udom:$uname";
6597: &devalidate_cache_new('userres',$hashid);
6598: }
6599:
1.624 albertel 6600: sub get_userresdata {
6601: my ($uname,$udom)=@_;
6602: #most student don\'t have any data set, check if there is some data
6603: if (&EXT_cache_status($udom,$uname)) { return undef; }
6604:
6605: my $hashid="$udom:$uname";
6606: my ($result,$cached)=&is_cached_new('userres',$hashid);
6607: if (!defined($cached)) {
6608: my %resourcedata=&dump('resourcedata',$udom,$uname);
6609: $result=\%resourcedata;
6610: &do_cache_new('userres',$hashid,$result,600);
6611: }
6612: my ($tmp)=keys(%$result);
6613: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
6614: return $result;
6615: }
6616: #error 2 occurs when the .db doesn't exist
6617: if ($tmp!~/error: 2 /) {
1.672 albertel 6618: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 6619: " Trying to get resource data for ".
6620: $uname." at ".$udom.": ".
6621: $tmp."</font>");
6622: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 6623: #&EXT_cache_set($udom,$uname);
6624: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 6625: undef($tmp); # not really an error so don't send it back
1.624 albertel 6626: }
6627: return $tmp;
6628: }
1.879 foxr 6629: #----------------------------------------------- resdata - return resource data
6630: # Purpose:
6631: # Return resource data for either users or for a course.
6632: # Parameters:
6633: # $name - Course/user name.
6634: # $domain - Name of the domain the user/course is registered on.
6635: # $type - Type of thing $name is (must be 'course' or 'user'
6636: # @which - Array of names of resources desired.
6637: # Returns:
6638: # The value of the first reasource in @which that is found in the
6639: # resource hash.
6640: # Exceptional Conditions:
6641: # If the $type passed in is not valid (not the string 'course' or
6642: # 'user', an undefined reference is returned.
6643: # If none of the resources are found, an undef is returned
1.624 albertel 6644: sub resdata {
6645: my ($name,$domain,$type,@which)=@_;
6646: my $result;
6647: if ($type eq 'course') {
6648: $result=&get_courseresdata($name,$domain);
6649: } elsif ($type eq 'user') {
6650: $result=&get_userresdata($name,$domain);
6651: }
6652: if (!ref($result)) { return $result; }
1.251 albertel 6653: foreach my $item (@which) {
1.927 albertel 6654: if (defined($result->{$item->[0]})) {
6655: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 6656: }
1.250 albertel 6657: }
1.291 albertel 6658: return undef;
1.200 www 6659: }
6660:
1.379 matthew 6661: #
6662: # EXT resource caching routines
6663: #
6664:
6665: sub clear_EXT_cache_status {
1.383 albertel 6666: &delenv('cache.EXT.');
1.379 matthew 6667: }
6668:
6669: sub EXT_cache_status {
6670: my ($target_domain,$target_user) = @_;
1.383 albertel 6671: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 6672: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 6673: # We know already the user has no data
6674: return 1;
6675: } else {
6676: return 0;
6677: }
6678: }
6679:
6680: sub EXT_cache_set {
6681: my ($target_domain,$target_user) = @_;
1.383 albertel 6682: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 6683: #&appenv({$cachename => time});
1.379 matthew 6684: }
6685:
1.28 www 6686: # --------------------------------------------------------- Value of a Variable
1.58 www 6687: sub EXT {
1.715 albertel 6688:
1.395 albertel 6689: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 6690: unless ($varname) { return ''; }
1.218 albertel 6691: #get real user name/domain, courseid and symb
6692: my $courseid;
1.359 albertel 6693: my $publicuser;
1.427 www 6694: if ($symbparm) {
6695: $symbparm=&get_symb_from_alias($symbparm);
6696: }
1.218 albertel 6697: if (!($uname && $udom)) {
1.790 albertel 6698: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 6699: if (!$symbparm) { $symbparm=$cursymb; }
6700: } else {
1.620 albertel 6701: $courseid=$env{'request.course.id'};
1.218 albertel 6702: }
1.48 www 6703: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
6704: my $rest;
1.320 albertel 6705: if (defined($therest[0])) {
1.48 www 6706: $rest=join('.',@therest);
6707: } else {
6708: $rest='';
6709: }
1.320 albertel 6710:
1.57 www 6711: my $qualifierrest=$qualifier;
6712: if ($rest) { $qualifierrest.='.'.$rest; }
6713: my $spacequalifierrest=$space;
6714: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 6715: if ($realm eq 'user') {
1.48 www 6716: # --------------------------------------------------------------- user.resource
6717: if ($space eq 'resource') {
1.651 albertel 6718: if ( (defined($Apache::lonhomework::parsing_a_problem)
6719: || defined($Apache::lonhomework::parsing_a_task))
6720: &&
1.744 albertel 6721: ($symbparm eq &symbread()) ) {
6722: # if we are in the middle of processing the resource the
6723: # get the value we are planning on committing
6724: if (defined($Apache::lonhomework::results{$qualifierrest})) {
6725: return $Apache::lonhomework::results{$qualifierrest};
6726: } else {
6727: return $Apache::lonhomework::history{$qualifierrest};
6728: }
1.335 albertel 6729: } else {
1.359 albertel 6730: my %restored;
1.620 albertel 6731: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 6732: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
6733: } else {
6734: %restored=&restore($symbparm,$courseid,$udom,$uname);
6735: }
1.335 albertel 6736: return $restored{$qualifierrest};
6737: }
1.48 www 6738: # ----------------------------------------------------------------- user.access
6739: } elsif ($space eq 'access') {
1.218 albertel 6740: # FIXME - not supporting calls for a specific user
1.48 www 6741: return &allowed($qualifier,$rest);
6742: # ------------------------------------------ user.preferences, user.environment
6743: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 6744: if (($uname eq $env{'user.name'}) &&
6745: ($udom eq $env{'user.domain'})) {
6746: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 6747: } else {
1.359 albertel 6748: my %returnhash;
6749: if (!$publicuser) {
6750: %returnhash=&userenvironment($udom,$uname,
6751: $qualifierrest);
6752: }
1.218 albertel 6753: return $returnhash{$qualifierrest};
6754: }
1.48 www 6755: # ----------------------------------------------------------------- user.course
6756: } elsif ($space eq 'course') {
1.218 albertel 6757: # FIXME - not supporting calls for a specific user
1.620 albertel 6758: return $env{join('.',('request.course',$qualifier))};
1.48 www 6759: # ------------------------------------------------------------------- user.role
6760: } elsif ($space eq 'role') {
1.218 albertel 6761: # FIXME - not supporting calls for a specific user
1.620 albertel 6762: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 6763: if ($qualifier eq 'value') {
6764: return $role;
6765: } elsif ($qualifier eq 'extent') {
6766: return $where;
6767: }
6768: # ----------------------------------------------------------------- user.domain
6769: } elsif ($space eq 'domain') {
1.218 albertel 6770: return $udom;
1.48 www 6771: # ------------------------------------------------------------------- user.name
6772: } elsif ($space eq 'name') {
1.218 albertel 6773: return $uname;
1.48 www 6774: # ---------------------------------------------------- Any other user namespace
1.29 www 6775: } else {
1.359 albertel 6776: my %reply;
6777: if (!$publicuser) {
6778: %reply=&get($space,[$qualifierrest],$udom,$uname);
6779: }
6780: return $reply{$qualifierrest};
1.48 www 6781: }
1.236 www 6782: } elsif ($realm eq 'query') {
6783: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 6784: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
6785: [$spacequalifierrest]);
1.620 albertel 6786: return $env{'form.'.$spacequalifierrest};
1.236 www 6787: } elsif ($realm eq 'request') {
1.48 www 6788: # ------------------------------------------------------------- request.browser
6789: if ($space eq 'browser') {
1.430 www 6790: if ($qualifier eq 'textremote') {
1.676 albertel 6791: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 6792: return 1;
6793: } else {
6794: return 0;
6795: }
6796: } else {
1.620 albertel 6797: return $env{'browser.'.$qualifier};
1.430 www 6798: }
1.57 www 6799: # ------------------------------------------------------------ request.filename
6800: } else {
1.620 albertel 6801: return $env{'request.'.$spacequalifierrest};
1.29 www 6802: }
1.28 www 6803: } elsif ($realm eq 'course') {
1.48 www 6804: # ---------------------------------------------------------- course.description
1.620 albertel 6805: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 6806: } elsif ($realm eq 'resource') {
1.165 www 6807:
1.620 albertel 6808: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 6809: if (!$symbparm) { $symbparm=&symbread(); }
6810: }
1.693 albertel 6811:
6812: if ($space eq 'title') {
6813: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
6814: return &gettitle($symbparm);
6815: }
6816:
6817: if ($space eq 'map') {
6818: my ($map) = &decode_symb($symbparm);
6819: return &symbread($map);
6820: }
1.905 albertel 6821: if ($space eq 'filename') {
6822: if ($symbparm) {
6823: return &clutter((&decode_symb($symbparm))[2]);
6824: }
6825: return &hreflocation('',$env{'request.filename'});
6826: }
1.693 albertel 6827:
6828: my ($section, $group, @groups);
1.593 albertel 6829: my ($courselevelm,$courselevel);
1.539 albertel 6830: if ($symbparm && defined($courseid) &&
1.620 albertel 6831: $courseid eq $env{'request.course.id'}) {
1.165 www 6832:
1.218 albertel 6833: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 6834:
1.60 www 6835: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 6836: my $symbp=$symbparm;
1.735 albertel 6837: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 6838:
6839: my $symbparm=$symbp.'.'.$spacequalifierrest;
6840: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
6841:
1.620 albertel 6842: if (($env{'user.name'} eq $uname) &&
6843: ($env{'user.domain'} eq $udom)) {
6844: $section=$env{'request.course.sec'};
1.733 raeburn 6845: @groups = split(/:/,$env{'request.course.groups'});
6846: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 6847: } else {
1.539 albertel 6848: if (! defined($usection)) {
1.551 albertel 6849: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 6850: } else {
6851: $section = $usection;
6852: }
1.733 raeburn 6853: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 6854: }
6855:
6856: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
6857: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
6858: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
6859:
1.593 albertel 6860: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 6861: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 6862: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 6863:
1.60 www 6864: # ----------------------------------------------------------- first, check user
1.624 albertel 6865:
6866: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 6867: ([$courselevelr,'resource'],
6868: [$courselevelm,'map' ],
6869: [$courselevel, 'course' ]));
1.931 albertel 6870: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 6871:
1.594 albertel 6872: # ------------------------------------------------ second, check some of course
1.684 raeburn 6873: my $coursereply;
1.691 raeburn 6874: if (@groups > 0) {
6875: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
6876: $mapparm,$spacequalifierrest);
1.927 albertel 6877: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 6878: }
1.96 www 6879:
1.684 raeburn 6880: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 6881: $env{'course.'.$courseid.'.domain'},
6882: 'course',
6883: ([$seclevelr, 'resource'],
6884: [$seclevelm, 'map' ],
6885: [$seclevel, 'course' ],
6886: [$courselevelr,'resource']));
6887: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 6888:
1.60 www 6889: # ------------------------------------------------------ third, check map parms
1.218 albertel 6890: my %parmhash=();
6891: my $thisparm='';
6892: if (tie(%parmhash,'GDBM_File',
1.620 albertel 6893: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 6894: &GDBM_READER(),0640)) {
1.218 albertel 6895: $thisparm=$parmhash{$symbparm};
6896: untie(%parmhash);
6897: }
1.927 albertel 6898: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 6899: }
1.594 albertel 6900: # ------------------------------------------ fourth, look in resource metadata
1.71 www 6901:
1.218 albertel 6902: $spacequalifierrest=~s/\./\_/;
1.282 albertel 6903: my $filename;
6904: if (!$symbparm) { $symbparm=&symbread(); }
6905: if ($symbparm) {
1.409 www 6906: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 6907: } else {
1.620 albertel 6908: $filename=$env{'request.filename'};
1.282 albertel 6909: }
6910: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 6911: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 6912: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 6913: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 6914:
1.927 albertel 6915: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 6916: if ($symbparm && defined($courseid) &&
1.620 albertel 6917: $courseid eq $env{'request.course.id'}) {
1.624 albertel 6918: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
6919: $env{'course.'.$courseid.'.domain'},
6920: 'course',
1.927 albertel 6921: ([$courselevelm,'map' ],
6922: [$courselevel, 'course']));
6923: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 6924: }
1.145 www 6925: # ------------------------------------------------------------------ Cascade up
1.218 albertel 6926: unless ($space eq '0') {
1.336 albertel 6927: my @parts=split(/_/,$space);
6928: my $id=pop(@parts);
6929: my $part=join('_',@parts);
6930: if ($part eq '') { $part='0'; }
1.927 albertel 6931: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 6932: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 6933: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 6934: }
1.395 albertel 6935: if ($recurse) { return undef; }
6936: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 6937: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 6938: # ---------------------------------------------------- Any other user namespace
6939: } elsif ($realm eq 'environment') {
6940: # ----------------------------------------------------------------- environment
1.620 albertel 6941: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
6942: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 6943: } else {
1.770 albertel 6944: if ($uname eq 'anonymous' && $udom eq '') {
6945: return '';
6946: }
1.219 albertel 6947: my %returnhash=&userenvironment($udom,$uname,
6948: $spacequalifierrest);
6949: return $returnhash{$spacequalifierrest};
6950: }
1.28 www 6951: } elsif ($realm eq 'system') {
1.48 www 6952: # ----------------------------------------------------------------- system.time
6953: if ($space eq 'time') {
6954: return time;
6955: }
1.696 albertel 6956: } elsif ($realm eq 'server') {
6957: # ----------------------------------------------------------------- system.time
6958: if ($space eq 'name') {
6959: return $ENV{'SERVER_NAME'};
6960: }
1.28 www 6961: }
1.48 www 6962: return '';
1.61 www 6963: }
6964:
1.927 albertel 6965: sub get_reply {
6966: my ($reply_value) = @_;
1.940 raeburn 6967: if (ref($reply_value) eq 'ARRAY') {
6968: if (wantarray) {
6969: return @$reply_value;
6970: }
6971: return $reply_value->[0];
6972: } else {
6973: return $reply_value;
1.927 albertel 6974: }
6975: }
6976:
1.691 raeburn 6977: sub check_group_parms {
6978: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
6979: my @groupitems = ();
6980: my $resultitem;
1.927 albertel 6981: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 6982: foreach my $group (@{$groups}) {
6983: foreach my $level (@levels) {
1.927 albertel 6984: my $item = $courseid.'.['.$group.'].'.$level->[0];
6985: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 6986: }
6987: }
6988: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
6989: $env{'course.'.$courseid.'.domain'},
6990: 'course',@groupitems);
6991: return $coursereply;
6992: }
6993:
6994: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 6995: my ($courseid,@groups) = @_;
6996: @groups = sort(@groups);
1.691 raeburn 6997: return @groups;
6998: }
6999:
1.395 albertel 7000: sub packages_tab_default {
7001: my ($uri,$varname)=@_;
7002: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 7003:
7004: my (@extension,@specifics,$do_default);
7005: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 7006: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 7007: if ($pack_type eq 'default') {
7008: $do_default=1;
7009: } elsif ($pack_type eq 'extension') {
7010: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 7011: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 7012: # only look at packages defaults for packages that this id is
1.738 albertel 7013: push(@specifics,[$package,$pack_type,$pack_part]);
7014: }
7015: }
7016: # first look for a package that matches the requested part id
7017: foreach my $package (@specifics) {
7018: my (undef,$pack_type,$pack_part)=@{$package};
7019: next if ($pack_part ne $part);
7020: if (defined($packagetab{"$pack_type&$name&default"})) {
7021: return $packagetab{"$pack_type&$name&default"};
7022: }
7023: }
7024: # look for any possible matching non extension_ package
7025: foreach my $package (@specifics) {
7026: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 7027: if (defined($packagetab{"$pack_type&$name&default"})) {
7028: return $packagetab{"$pack_type&$name&default"};
7029: }
1.585 albertel 7030: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 7031: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
7032: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 7033: }
7034: }
1.738 albertel 7035: # look for any posible extension_ match
7036: foreach my $package (@extension) {
7037: my ($package,$pack_type)=@{$package};
7038: if (defined($packagetab{"$pack_type&$name&default"})) {
7039: return $packagetab{"$pack_type&$name&default"};
7040: }
7041: if (defined($packagetab{$package."&$name&default"})) {
7042: return $packagetab{$package."&$name&default"};
7043: }
7044: }
7045: # look for a global default setting
7046: if ($do_default && defined($packagetab{"default&$name&default"})) {
7047: return $packagetab{"default&$name&default"};
7048: }
1.395 albertel 7049: return undef;
7050: }
7051:
1.334 albertel 7052: sub add_prefix_and_part {
7053: my ($prefix,$part)=@_;
7054: my $keyroot;
7055: if (defined($prefix) && $prefix !~ /^__/) {
7056: # prefix that has a part already
7057: $keyroot=$prefix;
7058: } elsif (defined($prefix)) {
7059: # prefix that is missing a part
7060: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
7061: } else {
7062: # no prefix at all
7063: if (defined($part)) { $keyroot='_'.$part; }
7064: }
7065: return $keyroot;
7066: }
7067:
1.71 www 7068: # ---------------------------------------------------------------- Get metadata
7069:
1.599 albertel 7070: my %metaentry;
1.71 www 7071: sub metadata {
1.176 www 7072: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 7073: $uri=&declutter($uri);
1.288 albertel 7074: # if it is a non metadata possible uri return quickly
1.529 albertel 7075: if (($uri eq '') ||
7076: (($uri =~ m|^/*adm/|) &&
1.698 albertel 7077: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 7078: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
7079: return undef;
7080: }
7081: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
7082: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 7083: return undef;
1.288 albertel 7084: }
1.73 www 7085: my $filename=$uri;
7086: $uri=~s/\.meta$//;
1.172 www 7087: #
7088: # Is the metadata already cached?
1.177 www 7089: # Look at timestamp of caching
1.172 www 7090: # Everything is cached by the main uri, libraries are never directly cached
7091: #
1.428 albertel 7092: if (!defined($liburi)) {
1.599 albertel 7093: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 7094: if (defined($cached)) { return $result->{':'.$what}; }
7095: }
7096: {
1.172 www 7097: #
7098: # Is this a recursive call for a library?
7099: #
1.599 albertel 7100: # if (! exists($metacache{$uri})) {
7101: # $metacache{$uri}={};
7102: # }
1.924 albertel 7103: my $cachetime = 60*60;
1.171 www 7104: if ($liburi) {
7105: $liburi=&declutter($liburi);
7106: $filename=$liburi;
1.401 bowersj2 7107: } else {
1.599 albertel 7108: &devalidate_cache_new('meta',$uri);
7109: undef(%metaentry);
1.401 bowersj2 7110: }
1.140 www 7111: my %metathesekeys=();
1.73 www 7112: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 7113: my $metastring;
1.924 albertel 7114: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 7115: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 7116: $metastring =
1.929 albertel 7117: &Apache::lonnet::ssi_body($which,
1.924 albertel 7118: ('grade_target' => 'meta'));
7119: $cachetime = 1; # only want this cached in the child not long term
7120: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 7121: my $file=&filelocation('',&clutter($filename));
1.599 albertel 7122: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 7123: $metastring=&getfile($file);
1.489 albertel 7124: }
1.208 albertel 7125: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 7126: my $token;
1.140 www 7127: undef %metathesekeys;
1.71 www 7128: while ($token=$parser->get_token) {
1.339 albertel 7129: if ($token->[0] eq 'S') {
7130: if (defined($token->[2]->{'package'})) {
1.172 www 7131: #
7132: # This is a package - get package info
7133: #
1.339 albertel 7134: my $package=$token->[2]->{'package'};
7135: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7136: if (defined($token->[2]->{'id'})) {
7137: $keyroot.='_'.$token->[2]->{'id'};
7138: }
1.599 albertel 7139: if ($metaentry{':packages'}) {
7140: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 7141: } else {
1.599 albertel 7142: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 7143: }
1.736 albertel 7144: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 7145: my $part=$keyroot;
7146: $part=~s/^\_//;
1.736 albertel 7147: if ($pack_entry=~/^\Q$package\E\&/ ||
7148: $pack_entry=~/^\Q$package\E_0\&/) {
7149: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 7150: # ignore package.tab specified default values
7151: # here &package_tab_default() will fetch those
7152: if ($subp eq 'default') { next; }
1.736 albertel 7153: my $value=$packagetab{$pack_entry};
1.432 albertel 7154: my $unikey;
7155: if ($pack =~ /_0$/) {
7156: $unikey='parameter_0_'.$name;
7157: $part=0;
7158: } else {
7159: $unikey='parameter'.$keyroot.'_'.$name;
7160: }
1.339 albertel 7161: if ($subp eq 'display') {
7162: $value.=' [Part: '.$part.']';
7163: }
1.599 albertel 7164: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 7165: $metathesekeys{$unikey}=1;
1.599 albertel 7166: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7167: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 7168: }
1.599 albertel 7169: if (defined($metaentry{':'.$unikey.'.default'})) {
7170: $metaentry{':'.$unikey}=
7171: $metaentry{':'.$unikey.'.default'};
1.356 albertel 7172: }
1.339 albertel 7173: }
7174: }
7175: } else {
1.172 www 7176: #
7177: # This is not a package - some other kind of start tag
1.339 albertel 7178: #
7179: my $entry=$token->[1];
7180: my $unikey;
7181: if ($entry eq 'import') {
7182: $unikey='';
7183: } else {
7184: $unikey=$entry;
7185: }
7186: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7187:
7188: if (defined($token->[2]->{'id'})) {
7189: $unikey.='_'.$token->[2]->{'id'};
7190: }
1.175 www 7191:
1.339 albertel 7192: if ($entry eq 'import') {
1.175 www 7193: #
7194: # Importing a library here
1.339 albertel 7195: #
7196: if ($depthcount<20) {
7197: my $location=$parser->get_text('/import');
7198: my $dir=$filename;
7199: $dir=~s|[^/]*$||;
7200: $location=&filelocation($dir,$location);
1.736 albertel 7201: my $metadata =
7202: &metadata($uri,'keys', $location,$unikey,
7203: $depthcount+1);
7204: foreach my $meta (split(',',$metadata)) {
7205: $metaentry{':'.$meta}=$metaentry{':'.$meta};
7206: $metathesekeys{$meta}=1;
1.339 albertel 7207: }
7208: }
7209: } else {
7210:
7211: if (defined($token->[2]->{'name'})) {
7212: $unikey.='_'.$token->[2]->{'name'};
7213: }
7214: $metathesekeys{$unikey}=1;
1.736 albertel 7215: foreach my $param (@{$token->[3]}) {
7216: $metaentry{':'.$unikey.'.'.$param} =
7217: $token->[2]->{$param};
1.339 albertel 7218: }
7219: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 7220: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 7221: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
7222: # only ws inside the tag, and not in default, so use default
7223: # as value
1.599 albertel 7224: $metaentry{':'.$unikey}=$default;
1.908 albertel 7225: } elsif ( $internaltext =~ /\S/ ) {
7226: # something interesting inside the tag
7227: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 7228: } else {
1.908 albertel 7229: # no interesting values, don't set a default
1.339 albertel 7230: }
1.172 www 7231: # end of not-a-package not-a-library import
1.339 albertel 7232: }
1.172 www 7233: # end of not-a-package start tag
1.339 albertel 7234: }
1.172 www 7235: # the next is the end of "start tag"
1.339 albertel 7236: }
7237: }
1.483 albertel 7238: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 7239: $extension = lc($extension);
7240: if ($extension eq 'htm') { $extension='html'; }
7241:
1.737 albertel 7242: foreach my $key (keys(%packagetab)) {
1.483 albertel 7243: #no specific packages #how's our extension
7244: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 7245: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 7246: \%metathesekeys);
7247: }
1.883 albertel 7248:
7249: if (!exists($metaentry{':packages'})
7250: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 7251: foreach my $key (keys(%packagetab)) {
1.483 albertel 7252: #no specific packages well let's get default then
7253: if ($key!~/^default&/) { next; }
1.488 albertel 7254: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 7255: \%metathesekeys);
7256: }
7257: }
1.338 www 7258: # are there custom rights to evaluate
1.599 albertel 7259: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 7260:
1.338 www 7261: #
7262: # Importing a rights file here
1.339 albertel 7263: #
7264: unless ($depthcount) {
1.599 albertel 7265: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 7266: my $dir=$filename;
7267: $dir=~s|[^/]*$||;
7268: $location=&filelocation($dir,$location);
1.736 albertel 7269: my $rights_metadata =
7270: &metadata($uri,'keys',$location,'_rights',
7271: $depthcount+1);
7272: foreach my $rights (split(',',$rights_metadata)) {
7273: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
7274: $metathesekeys{$rights}=1;
1.339 albertel 7275: }
7276: }
7277: }
1.737 albertel 7278: # uniqifiy package listing
7279: my %seen;
7280: my @uniq_packages =
7281: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
7282: $metaentry{':packages'} = join(',',@uniq_packages);
7283:
7284: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 7285: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
7286: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 7287: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 7288: # this is the end of "was not already recently cached
1.71 www 7289: }
1.599 albertel 7290: return $metaentry{':'.$what};
1.261 albertel 7291: }
7292:
1.488 albertel 7293: sub metadata_create_package_def {
1.483 albertel 7294: my ($uri,$key,$package,$metathesekeys)=@_;
7295: my ($pack,$name,$subp)=split(/\&/,$key);
7296: if ($subp eq 'default') { next; }
7297:
1.599 albertel 7298: if (defined($metaentry{':packages'})) {
7299: $metaentry{':packages'}.=','.$package;
1.483 albertel 7300: } else {
1.599 albertel 7301: $metaentry{':packages'}=$package;
1.483 albertel 7302: }
7303: my $value=$packagetab{$key};
7304: my $unikey;
7305: $unikey='parameter_0_'.$name;
1.599 albertel 7306: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 7307: $$metathesekeys{$unikey}=1;
1.599 albertel 7308: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7309: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 7310: }
1.599 albertel 7311: if (defined($metaentry{':'.$unikey.'.default'})) {
7312: $metaentry{':'.$unikey}=
7313: $metaentry{':'.$unikey.'.default'};
1.483 albertel 7314: }
7315: }
7316:
1.261 albertel 7317: sub metadata_generate_part0 {
7318: my ($metadata,$metacache,$uri) = @_;
7319: my %allnames;
1.737 albertel 7320: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 7321: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 7322: my $part=$$metacache{':'.$metakey.'.part'};
7323: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 7324: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 7325: $allnames{$name}=$part;
7326: }
7327: }
7328: }
7329: foreach my $name (keys(%allnames)) {
7330: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 7331: my $key=":parameter_0_$name";
1.261 albertel 7332: $$metacache{"$key.part"}='0';
7333: $$metacache{"$key.name"}=$name;
1.428 albertel 7334: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 7335: $allnames{$name}.'_'.$name.
7336: '.type'};
1.428 albertel 7337: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 7338: '.display'};
1.644 www 7339: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 7340: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 7341: $$metacache{"$key.display"}=$olddis;
7342: }
1.71 www 7343: }
7344:
1.764 albertel 7345: # ------------------------------------------------------ Devalidate title cache
7346:
7347: sub devalidate_title_cache {
7348: my ($url)=@_;
7349: if (!$env{'request.course.id'}) { return; }
7350: my $symb=&symbread($url);
7351: if (!$symb) { return; }
7352: my $key=$env{'request.course.id'}."\0".$symb;
7353: &devalidate_cache_new('title',$key);
7354: }
7355:
1.301 www 7356: # ------------------------------------------------- Get the title of a resource
7357:
7358: sub gettitle {
7359: my $urlsymb=shift;
7360: my $symb=&symbread($urlsymb);
1.534 albertel 7361: if ($symb) {
1.620 albertel 7362: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 7363: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 7364: if (defined($cached)) {
7365: return $result;
7366: }
1.534 albertel 7367: my ($map,$resid,$url)=&decode_symb($symb);
7368: my $title='';
1.907 albertel 7369: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
7370: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
7371: } else {
7372: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7373: &GDBM_READER(),0640)) {
7374: my $mapid=$bighash{'map_pc_'.&clutter($map)};
7375: $title=$bighash{'title_'.$mapid.'.'.$resid};
7376: untie(%bighash);
7377: }
1.534 albertel 7378: }
7379: $title=~s/\&colon\;/\:/gs;
7380: if ($title) {
1.599 albertel 7381: return &do_cache_new('title',$key,$title,600);
1.534 albertel 7382: }
7383: $urlsymb=$url;
7384: }
7385: my $title=&metadata($urlsymb,'title');
7386: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
7387: return $title;
1.301 www 7388: }
1.613 albertel 7389:
1.614 albertel 7390: sub get_slot {
7391: my ($which,$cnum,$cdom)=@_;
7392: if (!$cnum || !$cdom) {
1.790 albertel 7393: (undef,my $courseid)=&whichuser();
1.620 albertel 7394: $cdom=$env{'course.'.$courseid.'.domain'};
7395: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 7396: }
1.703 albertel 7397: my $key=join("\0",'slots',$cdom,$cnum,$which);
7398: my %slotinfo;
7399: if (exists($remembered{$key})) {
7400: $slotinfo{$which} = $remembered{$key};
7401: } else {
7402: %slotinfo=&get('slots',[$which],$cdom,$cnum);
7403: &Apache::lonhomework::showhash(%slotinfo);
7404: my ($tmp)=keys(%slotinfo);
7405: if ($tmp=~/^error:/) { return (); }
7406: $remembered{$key} = $slotinfo{$which};
7407: }
1.616 albertel 7408: if (ref($slotinfo{$which}) eq 'HASH') {
7409: return %{$slotinfo{$which}};
7410: }
7411: return $slotinfo{$which};
1.614 albertel 7412: }
1.31 www 7413: # ------------------------------------------------- Update symbolic store links
7414:
7415: sub symblist {
7416: my ($mapname,%newhash)=@_;
1.438 www 7417: $mapname=&deversion(&declutter($mapname));
1.31 www 7418: my %hash;
1.620 albertel 7419: if (($env{'request.course.fn'}) && (%newhash)) {
7420: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7421: &GDBM_WRCREAT(),0640)) {
1.711 albertel 7422: foreach my $url (keys %newhash) {
7423: next if ($url eq 'last_known'
7424: && $env{'form.no_update_last_known'});
7425: $hash{declutter($url)}=&encode_symb($mapname,
7426: $newhash{$url}->[1],
7427: $newhash{$url}->[0]);
1.191 harris41 7428: }
1.31 www 7429: if (untie(%hash)) {
7430: return 'ok';
7431: }
7432: }
7433: }
7434: return 'error';
1.212 www 7435: }
7436:
7437: # --------------------------------------------------------------- Verify a symb
7438:
7439: sub symbverify {
1.510 www 7440: my ($symb,$thisurl)=@_;
7441: my $thisfn=$thisurl;
1.439 www 7442: $thisfn=&declutter($thisfn);
1.215 www 7443: # direct jump to resource in page or to a sequence - will construct own symbs
7444: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
7445: # check URL part
1.409 www 7446: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 7447:
1.431 www 7448: unless ($url eq $thisfn) { return 0; }
1.213 www 7449:
1.216 www 7450: $symb=&symbclean($symb);
1.510 www 7451: $thisurl=&deversion($thisurl);
1.439 www 7452: $thisfn=&deversion($thisfn);
1.213 www 7453:
7454: my %bighash;
7455: my $okay=0;
1.431 www 7456:
1.620 albertel 7457: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7458: &GDBM_READER(),0640)) {
1.510 www 7459: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 7460: unless ($ids) {
1.510 www 7461: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 7462: }
7463: if ($ids) {
7464: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 7465: foreach my $id (split(/\,/,$ids)) {
7466: my ($mapid,$resid)=split(/\./,$id);
1.216 www 7467: if (
7468: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
7469: eq $symb) {
1.620 albertel 7470: if (($env{'request.role.adv'}) ||
1.800 albertel 7471: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 7472: $okay=1;
7473: }
7474: }
1.216 www 7475: }
7476: }
1.213 www 7477: untie(%bighash);
7478: }
7479: return $okay;
1.31 www 7480: }
7481:
1.210 www 7482: # --------------------------------------------------------------- Clean-up symb
7483:
7484: sub symbclean {
7485: my $symb=shift;
1.568 albertel 7486: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 7487: # remove version from map
7488: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 7489:
1.210 www 7490: # remove version from URL
7491: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 7492:
1.507 www 7493: # remove wrapper
7494:
1.510 www 7495: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 7496: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 7497: return $symb;
1.409 www 7498: }
7499:
7500: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 7501:
7502: sub encode_symb {
7503: my ($map,$resid,$url)=@_;
7504: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
7505: }
1.409 www 7506:
7507: sub decode_symb {
1.568 albertel 7508: my $symb=shift;
7509: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
7510: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 7511: return (&fixversion($map),$resid,&fixversion($url));
7512: }
7513:
7514: sub fixversion {
7515: my $fn=shift;
1.609 banghart 7516: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 7517: my %bighash;
7518: my $uri=&clutter($fn);
1.620 albertel 7519: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 7520: # is this cached?
1.599 albertel 7521: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 7522: if (defined($cached)) { return $result; }
7523: # unfortunately not cached, or expired
1.620 albertel 7524: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 7525: &GDBM_READER(),0640)) {
7526: if ($bighash{'version_'.$uri}) {
7527: my $version=$bighash{'version_'.$uri};
1.444 www 7528: unless (($version eq 'mostrecent') ||
7529: ($version==&getversion($uri))) {
1.440 www 7530: $uri=~s/\.(\w+)$/\.$version\.$1/;
7531: }
7532: }
7533: untie %bighash;
1.413 www 7534: }
1.599 albertel 7535: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 7536: }
7537:
7538: sub deversion {
7539: my $url=shift;
7540: $url=~s/\.\d+\.(\w+)$/\.$1/;
7541: return $url;
1.210 www 7542: }
7543:
1.31 www 7544: # ------------------------------------------------------ Return symb list entry
7545:
7546: sub symbread {
1.249 www 7547: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 7548: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 7549: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 7550: # no filename provided? try from environment
1.44 www 7551: unless ($thisfn) {
1.620 albertel 7552: if ($env{'request.symb'}) {
7553: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 7554: }
1.620 albertel 7555: $thisfn=$env{'request.filename'};
1.44 www 7556: }
1.569 albertel 7557: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 7558: # is that filename actually a symb? Verify, clean, and return
7559: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 7560: if (&symbverify($thisfn,$1)) {
1.620 albertel 7561: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 7562: }
1.242 www 7563: }
1.44 www 7564: $thisfn=declutter($thisfn);
1.31 www 7565: my %hash;
1.37 www 7566: my %bighash;
7567: my $syval='';
1.620 albertel 7568: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 7569: my $targetfn = $thisfn;
1.609 banghart 7570: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 7571: $targetfn = 'adm/wrapper/'.$thisfn;
7572: }
1.687 albertel 7573: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
7574: $targetfn=$1;
7575: }
1.620 albertel 7576: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7577: &GDBM_READER(),0640)) {
1.481 raeburn 7578: $syval=$hash{$targetfn};
1.37 www 7579: untie(%hash);
7580: }
7581: # ---------------------------------------------------------- There was an entry
7582: if ($syval) {
1.601 albertel 7583: #unless ($syval=~/\_\d+$/) {
1.620 albertel 7584: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 7585: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 7586: #return $env{$cache_str}='';
1.601 albertel 7587: #}
7588: #$syval.=$1;
7589: #}
1.37 www 7590: } else {
7591: # ------------------------------------------------------- Was not in symb table
1.620 albertel 7592: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7593: &GDBM_READER(),0640)) {
1.37 www 7594: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 7595: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 7596: unless ($ids) {
7597: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 7598: }
7599: unless ($ids) {
7600: # alias?
7601: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 7602: }
1.37 www 7603: if ($ids) {
7604: # ------------------------------------------------------------------- Has ID(s)
7605: my @possibilities=split(/\,/,$ids);
1.39 www 7606: if ($#possibilities==0) {
7607: # ----------------------------------------------- There is only one possibility
1.37 www 7608: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 7609: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7610: $resid,$thisfn);
1.249 www 7611: } elsif (!$donotrecurse) {
1.39 www 7612: # ------------------------------------------ There is more than one possibility
7613: my $realpossible=0;
1.800 albertel 7614: foreach my $id (@possibilities) {
7615: my $file=$bighash{'src_'.$id};
1.39 www 7616: if (&allowed('bre',$file)) {
1.800 albertel 7617: my ($mapid,$resid)=split(/\./,$id);
1.39 www 7618: if ($bighash{'map_type_'.$mapid} ne 'page') {
7619: $realpossible++;
1.626 albertel 7620: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7621: $resid,$thisfn);
1.39 www 7622: }
7623: }
1.191 harris41 7624: }
1.39 www 7625: if ($realpossible!=1) { $syval=''; }
1.249 www 7626: } else {
7627: $syval='';
1.37 www 7628: }
7629: }
7630: untie(%bighash)
1.481 raeburn 7631: }
1.31 www 7632: }
1.62 www 7633: if ($syval) {
1.620 albertel 7634: return $env{$cache_str}=$syval;
1.62 www 7635: }
1.31 www 7636: }
1.949 raeburn 7637: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 7638: return $env{$cache_str}='';
1.31 www 7639: }
7640:
7641: # ---------------------------------------------------------- Return random seed
7642:
1.32 www 7643: sub numval {
7644: my $txt=shift;
7645: $txt=~tr/A-J/0-9/;
7646: $txt=~tr/a-j/0-9/;
7647: $txt=~tr/K-T/0-9/;
7648: $txt=~tr/k-t/0-9/;
7649: $txt=~tr/U-Z/0-5/;
7650: $txt=~tr/u-z/0-5/;
7651: $txt=~s/\D//g;
1.564 albertel 7652: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 7653: return int($txt);
1.368 albertel 7654: }
7655:
1.484 albertel 7656: sub numval2 {
7657: my $txt=shift;
7658: $txt=~tr/A-J/0-9/;
7659: $txt=~tr/a-j/0-9/;
7660: $txt=~tr/K-T/0-9/;
7661: $txt=~tr/k-t/0-9/;
7662: $txt=~tr/U-Z/0-5/;
7663: $txt=~tr/u-z/0-5/;
7664: $txt=~s/\D//g;
7665: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7666: my $total;
7667: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 7668: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 7669: return int($total);
7670: }
7671:
1.575 albertel 7672: sub numval3 {
7673: use integer;
7674: my $txt=shift;
7675: $txt=~tr/A-J/0-9/;
7676: $txt=~tr/a-j/0-9/;
7677: $txt=~tr/K-T/0-9/;
7678: $txt=~tr/k-t/0-9/;
7679: $txt=~tr/U-Z/0-5/;
7680: $txt=~tr/u-z/0-5/;
7681: $txt=~s/\D//g;
7682: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7683: my $total;
7684: foreach my $val (@txts) { $total+=$val; }
7685: if ($_64bit) { $total=(($total<<32)>>32); }
7686: return $total;
7687: }
7688:
1.675 albertel 7689: sub digest {
7690: my ($data)=@_;
7691: my $digest=&Digest::MD5::md5($data);
7692: my ($a,$b,$c,$d)=unpack("iiii",$digest);
7693: my ($e,$f);
7694: {
7695: use integer;
7696: $e=($a+$b);
7697: $f=($c+$d);
7698: if ($_64bit) {
7699: $e=(($e<<32)>>32);
7700: $f=(($f<<32)>>32);
7701: }
7702: }
7703: if (wantarray) {
7704: return ($e,$f);
7705: } else {
7706: my $g;
7707: {
7708: use integer;
7709: $g=($e+$f);
7710: if ($_64bit) {
7711: $g=(($g<<32)>>32);
7712: }
7713: }
7714: return $g;
7715: }
7716: }
7717:
1.368 albertel 7718: sub latest_rnd_algorithm_id {
1.675 albertel 7719: return '64bit5';
1.366 albertel 7720: }
1.32 www 7721:
1.503 albertel 7722: sub get_rand_alg {
7723: my ($courseid)=@_;
1.790 albertel 7724: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 7725: if ($courseid) {
1.620 albertel 7726: return $env{"course.$courseid.rndseed"};
1.503 albertel 7727: }
7728: return &latest_rnd_algorithm_id();
7729: }
7730:
1.562 albertel 7731: sub validCODE {
7732: my ($CODE)=@_;
7733: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
7734: return 0;
7735: }
7736:
1.491 albertel 7737: sub getCODE {
1.620 albertel 7738: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 7739: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
7740: defined($Apache::lonhomework::parsing_a_task) ) &&
7741: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 7742: return $Apache::lonhomework::history{'resource.CODE'};
7743: }
7744: return undef;
7745: }
7746:
1.31 www 7747: sub rndseed {
1.155 albertel 7748: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 7749: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 7750: if (!defined($symb)) {
1.366 albertel 7751: unless ($symb=$wsymb) { return time; }
7752: }
7753: if (!$courseid) { $courseid=$wcourseid; }
7754: if (!$domain) { $domain=$wdomain; }
7755: if (!$username) { $username=$wusername }
1.503 albertel 7756: my $which=&get_rand_alg();
1.803 albertel 7757:
1.491 albertel 7758: if (defined(&getCODE())) {
1.675 albertel 7759: if ($which eq '64bit5') {
7760: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
7761: } elsif ($which eq '64bit4') {
1.575 albertel 7762: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
7763: } else {
7764: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
7765: }
1.675 albertel 7766: } elsif ($which eq '64bit5') {
7767: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 7768: } elsif ($which eq '64bit4') {
7769: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 7770: } elsif ($which eq '64bit3') {
7771: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 7772: } elsif ($which eq '64bit2') {
7773: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 7774: } elsif ($which eq '64bit') {
7775: return &rndseed_64bit($symb,$courseid,$domain,$username);
7776: }
7777: return &rndseed_32bit($symb,$courseid,$domain,$username);
7778: }
7779:
7780: sub rndseed_32bit {
7781: my ($symb,$courseid,$domain,$username)=@_;
7782: {
7783: use integer;
7784: my $symbchck=unpack("%32C*",$symb) << 27;
7785: my $symbseed=numval($symb) << 22;
7786: my $namechck=unpack("%32C*",$username) << 17;
7787: my $nameseed=numval($username) << 12;
7788: my $domainseed=unpack("%32C*",$domain) << 7;
7789: my $courseseed=unpack("%32C*",$courseid);
7790: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 7791: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7792: #&logthis("rndseed :$num:$symb");
1.564 albertel 7793: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 7794: return $num;
7795: }
7796: }
7797:
7798: sub rndseed_64bit {
7799: my ($symb,$courseid,$domain,$username)=@_;
7800: {
7801: use integer;
7802: my $symbchck=unpack("%32S*",$symb) << 21;
7803: my $symbseed=numval($symb) << 10;
7804: my $namechck=unpack("%32S*",$username);
7805:
7806: my $nameseed=numval($username) << 21;
7807: my $domainseed=unpack("%32S*",$domain) << 10;
7808: my $courseseed=unpack("%32S*",$courseid);
7809:
7810: my $num1=$symbchck+$symbseed+$namechck;
7811: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7812: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7813: #&logthis("rndseed :$num:$symb");
1.564 albertel 7814: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 7815: return "$num1,$num2";
1.155 albertel 7816: }
1.366 albertel 7817: }
7818:
1.443 albertel 7819: sub rndseed_64bit2 {
7820: my ($symb,$courseid,$domain,$username)=@_;
7821: {
7822: use integer;
7823: # strings need to be an even # of cahracters long, it it is odd the
7824: # last characters gets thrown away
7825: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7826: my $symbseed=numval($symb) << 10;
7827: my $namechck=unpack("%32S*",$username.' ');
7828:
7829: my $nameseed=numval($username) << 21;
1.501 albertel 7830: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7831: my $courseseed=unpack("%32S*",$courseid.' ');
7832:
7833: my $num1=$symbchck+$symbseed+$namechck;
7834: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7835: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7836: #&logthis("rndseed :$num:$symb");
1.803 albertel 7837: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 7838: return "$num1,$num2";
7839: }
7840: }
7841:
7842: sub rndseed_64bit3 {
7843: my ($symb,$courseid,$domain,$username)=@_;
7844: {
7845: use integer;
7846: # strings need to be an even # of cahracters long, it it is odd the
7847: # last characters gets thrown away
7848: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7849: my $symbseed=numval2($symb) << 10;
7850: my $namechck=unpack("%32S*",$username.' ');
7851:
7852: my $nameseed=numval2($username) << 21;
1.443 albertel 7853: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7854: my $courseseed=unpack("%32S*",$courseid.' ');
7855:
7856: my $num1=$symbchck+$symbseed+$namechck;
7857: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7858: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7859: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 7860: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7861:
1.503 albertel 7862: return "$num1:$num2";
1.443 albertel 7863: }
7864: }
7865:
1.575 albertel 7866: sub rndseed_64bit4 {
7867: my ($symb,$courseid,$domain,$username)=@_;
7868: {
7869: use integer;
7870: # strings need to be an even # of cahracters long, it it is odd the
7871: # last characters gets thrown away
7872: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7873: my $symbseed=numval3($symb) << 10;
7874: my $namechck=unpack("%32S*",$username.' ');
7875:
7876: my $nameseed=numval3($username) << 21;
7877: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7878: my $courseseed=unpack("%32S*",$courseid.' ');
7879:
7880: my $num1=$symbchck+$symbseed+$namechck;
7881: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7882: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7883: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 7884: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7885:
7886: return "$num1:$num2";
7887: }
7888: }
7889:
1.675 albertel 7890: sub rndseed_64bit5 {
7891: my ($symb,$courseid,$domain,$username)=@_;
7892: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
7893: return "$num1:$num2";
7894: }
7895:
1.366 albertel 7896: sub rndseed_CODE_64bit {
7897: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 7898: {
1.366 albertel 7899: use integer;
1.443 albertel 7900: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 7901: my $symbseed=numval2($symb);
1.491 albertel 7902: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7903: my $CODEseed=numval(&getCODE());
1.443 albertel 7904: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 7905: my $num1=$symbseed+$CODEchck;
7906: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7907: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7908: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 7909: if ($_64bit) { $num1=(($num1<<32)>>32); }
7910: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 7911: return "$num1:$num2";
1.366 albertel 7912: }
7913: }
7914:
1.575 albertel 7915: sub rndseed_CODE_64bit4 {
7916: my ($symb,$courseid,$domain,$username)=@_;
7917: {
7918: use integer;
7919: my $symbchck=unpack("%32S*",$symb.' ') << 16;
7920: my $symbseed=numval3($symb);
7921: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7922: my $CODEseed=numval3(&getCODE());
7923: my $courseseed=unpack("%32S*",$courseid.' ');
7924: my $num1=$symbseed+$CODEchck;
7925: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7926: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7927: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 7928: if ($_64bit) { $num1=(($num1<<32)>>32); }
7929: if ($_64bit) { $num2=(($num2<<32)>>32); }
7930: return "$num1:$num2";
7931: }
7932: }
7933:
1.675 albertel 7934: sub rndseed_CODE_64bit5 {
7935: my ($symb,$courseid,$domain,$username)=@_;
7936: my $code = &getCODE();
7937: my ($num1,$num2)=&digest("$symb,$courseid,$code");
7938: return "$num1:$num2";
7939: }
7940:
1.366 albertel 7941: sub setup_random_from_rndseed {
7942: my ($rndseed)=@_;
1.503 albertel 7943: if ($rndseed =~/([,:])/) {
7944: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 7945: &Math::Random::random_set_seed(abs($num1),abs($num2));
7946: } else {
7947: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 7948: }
1.36 albertel 7949: }
7950:
1.474 albertel 7951: sub latest_receipt_algorithm_id {
1.835 albertel 7952: return 'receipt3';
1.474 albertel 7953: }
7954:
1.480 www 7955: sub recunique {
7956: my $fucourseid=shift;
7957: my $unique;
1.835 albertel 7958: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
7959: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7960: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 7961: } else {
7962: $unique=$perlvar{'lonReceipt'};
7963: }
7964: return unpack("%32C*",$unique);
7965: }
7966:
7967: sub recprefix {
7968: my $fucourseid=shift;
7969: my $prefix;
1.835 albertel 7970: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
7971: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7972: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 7973: } else {
7974: $prefix=$perlvar{'lonHostID'};
7975: }
7976: return unpack("%32C*",$prefix);
7977: }
7978:
1.76 www 7979: sub ireceipt {
1.474 albertel 7980: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 7981:
7982: my $return =&recprefix($fucourseid).'-';
7983:
7984: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
7985: $env{'request.state'} eq 'construct') {
7986: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
7987: return $return;
7988: }
7989:
1.76 www 7990: my $cuname=unpack("%32C*",$funame);
7991: my $cudom=unpack("%32C*",$fudom);
7992: my $cucourseid=unpack("%32C*",$fucourseid);
7993: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 7994: my $cunique=&recunique($fucourseid);
1.474 albertel 7995: my $cpart=unpack("%32S*",$part);
1.835 albertel 7996: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
7997:
1.790 albertel 7998: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 7999:
8000: $return.= ($cunique%$cuname+
8001: $cunique%$cudom+
8002: $cusymb%$cuname+
8003: $cusymb%$cudom+
8004: $cucourseid%$cuname+
8005: $cucourseid%$cudom+
8006: $cpart%$cuname+
8007: $cpart%$cudom);
8008: } else {
8009: $return.= ($cunique%$cuname+
8010: $cunique%$cudom+
8011: $cusymb%$cuname+
8012: $cusymb%$cudom+
8013: $cucourseid%$cuname+
8014: $cucourseid%$cudom);
8015: }
8016: return $return;
1.76 www 8017: }
8018:
8019: sub receipt {
1.474 albertel 8020: my ($part)=@_;
1.790 albertel 8021: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 8022: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 8023: }
1.260 ng 8024:
1.790 albertel 8025: sub whichuser {
8026: my ($passedsymb)=@_;
8027: my ($symb,$courseid,$domain,$name,$publicuser);
8028: if (defined($env{'form.grade_symb'})) {
8029: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
8030: my $allowed=&allowed('vgr',$tmp_courseid);
8031: if (!$allowed &&
8032: exists($env{'request.course.sec'}) &&
8033: $env{'request.course.sec'} !~ /^\s*$/) {
8034: $allowed=&allowed('vgr',$tmp_courseid.
8035: '/'.$env{'request.course.sec'});
8036: }
8037: if ($allowed) {
8038: ($symb)=&get_env_multiple('form.grade_symb');
8039: $courseid=$tmp_courseid;
8040: ($domain)=&get_env_multiple('form.grade_domain');
8041: ($name)=&get_env_multiple('form.grade_username');
8042: return ($symb,$courseid,$domain,$name,$publicuser);
8043: }
8044: }
8045: if (!$passedsymb) {
8046: $symb=&symbread();
8047: } else {
8048: $symb=$passedsymb;
8049: }
8050: $courseid=$env{'request.course.id'};
8051: $domain=$env{'user.domain'};
8052: $name=$env{'user.name'};
8053: if ($name eq 'public' && $domain eq 'public') {
8054: if (!defined($env{'form.username'})) {
8055: $env{'form.username'}.=time.rand(10000000);
8056: }
8057: $name.=$env{'form.username'};
8058: }
8059: return ($symb,$courseid,$domain,$name,$publicuser);
8060:
8061: }
8062:
1.36 albertel 8063: # ------------------------------------------------------------ Serves up a file
1.472 albertel 8064: # returns either the contents of the file or
8065: # -1 if the file doesn't exist
1.481 raeburn 8066: #
8067: # if the target is a file that was uploaded via DOCS,
8068: # a check will be made to see if a current copy exists on the local server,
8069: # if it does this will be served, otherwise a copy will be retrieved from
8070: # the home server for the course and stored in /home/httpd/html/userfiles on
8071: # the local server.
1.472 albertel 8072:
1.36 albertel 8073: sub getfile {
1.538 albertel 8074: my ($file) = @_;
1.609 banghart 8075: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 8076: &repcopy($file);
8077: return &readfile($file);
8078: }
8079:
8080: sub repcopy_userfile {
8081: my ($file)=@_;
1.609 banghart 8082: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 8083: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 8084: my ($cdom,$cnum,$filename) =
1.811 albertel 8085: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 8086: my $uri="/uploaded/$cdom/$cnum/$filename";
8087: if (-e "$file") {
1.828 www 8088: # we already have a local copy, check it out
1.538 albertel 8089: my @fileinfo = stat($file);
1.828 www 8090: my $rtncode;
8091: my $info;
1.538 albertel 8092: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 8093: if ($lwpresp ne 'ok') {
1.828 www 8094: # there is no such file anymore, even though we had a local copy
1.482 albertel 8095: if ($rtncode eq '404') {
1.538 albertel 8096: unlink($file);
1.482 albertel 8097: }
8098: return -1;
8099: }
8100: if ($info < $fileinfo[9]) {
1.828 www 8101: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 8102: return 'ok';
1.828 www 8103: } else {
8104: # the file is outdated, get rid of it
8105: unlink($file);
1.482 albertel 8106: }
1.828 www 8107: }
8108: # one way or the other, at this point, we don't have the file
8109: # construct the correct path for the file
8110: my @parts = ($cdom,$cnum);
8111: if ($filename =~ m|^(.+)/[^/]+$|) {
8112: push @parts, split(/\//,$1);
8113: }
8114: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
8115: foreach my $part (@parts) {
8116: $path .= '/'.$part;
8117: if (!-e $path) {
8118: mkdir($path,0770);
1.482 albertel 8119: }
8120: }
1.828 www 8121: # now the path exists for sure
8122: # get a user agent
8123: my $ua=new LWP::UserAgent;
8124: my $transferfile=$file.'.in.transfer';
8125: # FIXME: this should flock
8126: if (-e $transferfile) { return 'ok'; }
8127: my $request;
8128: $uri=~s/^\///;
1.838 albertel 8129: $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828 www 8130: my $response=$ua->request($request,$transferfile);
8131: # did it work?
8132: if ($response->is_error()) {
8133: unlink($transferfile);
8134: &logthis("Userfile repcopy failed for $uri");
8135: return -1;
8136: }
8137: # worked, rename the transfer file
8138: rename($transferfile,$file);
1.607 raeburn 8139: return 'ok';
1.481 raeburn 8140: }
8141:
1.517 albertel 8142: sub tokenwrapper {
8143: my $uri=shift;
1.552 albertel 8144: $uri=~s|^http\://([^/]+)||;
8145: $uri=~s|^/||;
1.620 albertel 8146: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 8147: my $token=$1;
1.552 albertel 8148: my (undef,$udom,$uname,$file)=split('/',$uri,4);
8149: if ($udom && $uname && $file) {
8150: $file=~s|(\?\.*)*$||;
1.949 raeburn 8151: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.838 albertel 8152: return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517 albertel 8153: (($uri=~/\?/)?'&':'?').'token='.$token.
8154: '&tokenissued='.$perlvar{'lonHostID'};
8155: } else {
8156: return '/adm/notfound.html';
8157: }
8158: }
8159:
1.828 www 8160: # call with reqtype HEAD: get last modification time
8161: # call with reqtype GET: get the file contents
8162: # Do not call this with reqtype GET for large files! It loads everything into memory
8163: #
1.481 raeburn 8164: sub getuploaded {
8165: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
8166: $uri=~s/^\///;
1.838 albertel 8167: $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481 raeburn 8168: my $ua=new LWP::UserAgent;
8169: my $request=new HTTP::Request($reqtype,$uri);
8170: my $response=$ua->request($request);
8171: $$rtncode = $response->code;
1.482 albertel 8172: if (! $response->is_success()) {
8173: return 'failed';
8174: }
8175: if ($reqtype eq 'HEAD') {
1.486 www 8176: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 8177: } elsif ($reqtype eq 'GET') {
8178: $$info = $response->content;
1.472 albertel 8179: }
1.482 albertel 8180: return 'ok';
1.36 albertel 8181: }
8182:
1.481 raeburn 8183: sub readfile {
8184: my $file = shift;
8185: if ( (! -e $file ) || ($file eq '') ) { return -1; };
8186: my $fh;
8187: open($fh,"<$file");
8188: my $a='';
1.800 albertel 8189: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 8190: return $a;
8191: }
8192:
1.36 albertel 8193: sub filelocation {
1.590 banghart 8194: my ($dir,$file) = @_;
8195: my $location;
8196: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 8197:
8198: if ($file =~ m-^/adm/-) {
8199: $file=~s-^/adm/wrapper/-/-;
8200: $file=~s-^/adm/coursedocs/showdoc/-/-;
8201: }
1.882 albertel 8202:
1.590 banghart 8203: if ($file=~m:^/~:) { # is a contruction space reference
8204: $location = $file;
8205: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 8206: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 8207: # is a correct contruction space reference
8208: $location = $file;
1.956 raeburn 8209: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
8210: $location = $file;
1.609 banghart 8211: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 8212: my ($udom,$uname,$filename)=
1.811 albertel 8213: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 8214: my $home=&homeserver($uname,$udom);
8215: my $is_me=0;
8216: my @ids=¤t_machine_ids();
8217: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
8218: if ($is_me) {
1.955 raeburn 8219: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 8220: } else {
8221: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
8222: $udom.'/'.$uname.'/'.$filename;
8223: }
1.882 albertel 8224: } elsif ($file =~ m-^/adm/-) {
8225: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 8226: } else {
8227: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
8228: $file=~s:^/res/:/:;
8229: if ( !( $file =~ m:^/:) ) {
8230: $location = $dir. '/'.$file;
8231: } else {
8232: $location = '/home/httpd/html/res'.$file;
8233: }
1.59 albertel 8234: }
1.590 banghart 8235: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 8236: while ($location=~m{/\.\./}) {
8237: if ($location =~ m{/[^/]+/\.\./}) {
8238: $location=~ s{/[^/]+/\.\./}{/}g;
8239: } else {
8240: $location=~ s{/\.\./}{/}g;
8241: }
8242: } #remove dir/..
1.590 banghart 8243: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
8244: return $location;
1.46 www 8245: }
1.36 albertel 8246:
1.46 www 8247: sub hreflocation {
8248: my ($dir,$file)=@_;
1.460 albertel 8249: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666 albertel 8250: $file=filelocation($dir,$file);
1.700 albertel 8251: } elsif ($file=~m-^/adm/-) {
8252: $file=~s-^/adm/wrapper/-/-;
8253: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 8254: }
8255: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
8256: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 8257: } elsif ($file=~m-/home/($match_username)/public_html/-) {
8258: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 8259: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 8260: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 8261: -/uploaded/$1/$2/-x;
1.46 www 8262: }
1.913 albertel 8263: if ($file=~ m{^/userfiles/}) {
8264: $file =~ s{^/userfiles/}{/uploaded/};
8265: }
1.462 albertel 8266: return $file;
1.465 albertel 8267: }
8268:
8269: sub current_machine_domains {
1.853 albertel 8270: return &machine_domains(&hostname($perlvar{'lonHostID'}));
8271: }
8272:
8273: sub machine_domains {
8274: my ($hostname) = @_;
1.465 albertel 8275: my @domains;
1.838 albertel 8276: my %hostname = &all_hostnames();
1.465 albertel 8277: while( my($id, $name) = each(%hostname)) {
1.467 matthew 8278: # &logthis("-$id-$name-$hostname-");
1.465 albertel 8279: if ($hostname eq $name) {
1.844 albertel 8280: push(@domains,&host_domain($id));
1.465 albertel 8281: }
8282: }
8283: return @domains;
8284: }
8285:
8286: sub current_machine_ids {
1.853 albertel 8287: return &machine_ids(&hostname($perlvar{'lonHostID'}));
8288: }
8289:
8290: sub machine_ids {
8291: my ($hostname) = @_;
8292: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 8293: my @ids;
1.888 albertel 8294: my %name_to_host = &all_names();
1.889 albertel 8295: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
8296: return @{ $name_to_host{$hostname} };
8297: }
8298: return;
1.31 www 8299: }
8300:
1.824 raeburn 8301: sub additional_machine_domains {
8302: my @domains;
8303: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
8304: while( my $line = <$fh>) {
8305: $line =~ s/\s//g;
8306: push(@domains,$line);
8307: }
8308: return @domains;
8309: }
8310:
8311: sub default_login_domain {
8312: my $domain = $perlvar{'lonDefDomain'};
8313: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
8314: foreach my $posdom (¤t_machine_domains(),
8315: &additional_machine_domains()) {
8316: if (lc($posdom) eq lc($testdomain)) {
8317: $domain=$posdom;
8318: last;
8319: }
8320: }
8321: return $domain;
8322: }
8323:
1.31 www 8324: # ------------------------------------------------------------- Declutters URLs
8325:
8326: sub declutter {
8327: my $thisfn=shift;
1.569 albertel 8328: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 8329: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 8330: $thisfn=~s/^\///;
1.697 albertel 8331: $thisfn=~s|^adm/wrapper/||;
8332: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 8333: $thisfn=~s/^res\///;
1.235 www 8334: $thisfn=~s/\?.+$//;
1.268 www 8335: return $thisfn;
8336: }
8337:
8338: # ------------------------------------------------------------- Clutter up URLs
8339:
8340: sub clutter {
8341: my $thisfn='/'.&declutter(shift);
1.887 albertel 8342: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 8343: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 8344: $thisfn='/res'.$thisfn;
8345: }
1.694 albertel 8346: if ($thisfn !~m|/adm|) {
1.695 albertel 8347: if ($thisfn =~ m|/ext/|) {
1.694 albertel 8348: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 8349: } else {
8350: my ($ext) = ($thisfn =~ /\.(\w+)$/);
8351: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 8352: if ($embstyle eq 'ssi'
8353: || ($embstyle eq 'hdn')
8354: || ($embstyle eq 'rat')
8355: || ($embstyle eq 'prv')
8356: || ($embstyle eq 'ign')) {
8357: #do nothing with these
8358: } elsif (($embstyle eq 'img')
1.695 albertel 8359: || ($embstyle eq 'emb')
8360: || ($embstyle eq 'wrp')) {
8361: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 8362: } elsif ($embstyle eq 'unk'
8363: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 8364: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 8365: } else {
1.718 www 8366: # &logthis("Got a blank emb style");
1.695 albertel 8367: }
1.694 albertel 8368: }
8369: }
1.31 www 8370: return $thisfn;
1.12 www 8371: }
8372:
1.787 albertel 8373: sub clutter_with_no_wrapper {
8374: my $uri = &clutter(shift);
8375: if ($uri =~ m-^/adm/-) {
8376: $uri =~ s-^/adm/wrapper/-/-;
8377: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
8378: }
8379: return $uri;
8380: }
8381:
1.557 albertel 8382: sub freeze_escape {
8383: my ($value)=@_;
8384: if (ref($value)) {
8385: $value=&nfreeze($value);
8386: return '__FROZEN__'.&escape($value);
8387: }
8388: return &escape($value);
8389: }
8390:
1.11 www 8391:
1.557 albertel 8392: sub thaw_unescape {
8393: my ($value)=@_;
8394: if ($value =~ /^__FROZEN__/) {
8395: substr($value,0,10,undef);
8396: $value=&unescape($value);
8397: return &thaw($value);
8398: }
8399: return &unescape($value);
8400: }
8401:
1.436 albertel 8402: sub correct_line_ends {
8403: my ($result)=@_;
8404: $$result =~s/\r\n/\n/mg;
8405: $$result =~s/\r/\n/mg;
1.415 albertel 8406: }
1.1 albertel 8407: # ================================================================ Main Program
8408:
1.184 www 8409: sub goodbye {
1.204 albertel 8410: &logthis("Starting Shut down");
1.443 albertel 8411: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 8412: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 8413: #converted
1.599 albertel 8414: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 8415: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
8416: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
8417: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 8418: #1.1 only
1.870 albertel 8419: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
8420: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
8421: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
8422: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
8423: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 8424: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
8425: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 8426: &flushcourselogs();
8427: &logthis("Shutting down");
8428: }
8429:
1.852 albertel 8430: sub get_dns {
1.869 albertel 8431: my ($url,$func,$ignore_cache) = @_;
8432: if (!$ignore_cache) {
8433: my ($content,$cached)=
8434: &Apache::lonnet::is_cached_new('dns',$url);
8435: if ($cached) {
8436: &$func($content);
8437: return;
8438: }
8439: }
8440:
8441: my %alldns;
1.852 albertel 8442: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8443: foreach my $dns (<$config>) {
8444: next if ($dns !~ /^\^(\S*)/x);
1.869 albertel 8445: $alldns{$1} = 1;
8446: }
8447: while (%alldns) {
8448: my ($dns) = keys(%alldns);
8449: delete($alldns{$dns});
1.852 albertel 8450: my $ua=new LWP::UserAgent;
8451: my $request=new HTTP::Request('GET',"http://$dns$url");
8452: my $response=$ua->request($request);
8453: next if ($response->is_error());
8454: my @content = split("\n",$response->content);
1.869 albertel 8455: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 8456: &$func(\@content);
1.869 albertel 8457: return;
1.852 albertel 8458: }
8459: close($config);
1.871 albertel 8460: my $which = (split('/',$url))[3];
8461: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
8462: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 8463: my @content = <$config>;
8464: &$func(\@content);
8465: return;
1.852 albertel 8466: }
1.327 albertel 8467: # ------------------------------------------------------------ Read domain file
8468: {
1.852 albertel 8469: my $loaded;
1.846 albertel 8470: my %domain;
8471:
1.852 albertel 8472: sub parse_domain_tab {
8473: my ($lines) = @_;
8474: foreach my $line (@$lines) {
8475: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 8476:
1.846 albertel 8477: chomp($line);
1.852 albertel 8478: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 8479: my %this_domain;
8480: foreach my $field ('description', 'auth_def', 'auth_arg_def',
8481: 'lang_def', 'city', 'longi', 'lati',
8482: 'primary') {
8483: $this_domain{$field} = shift(@elements);
8484: }
8485: $domain{$name} = \%this_domain;
1.852 albertel 8486: }
8487: }
1.864 albertel 8488:
8489: sub reset_domain_info {
8490: undef($loaded);
8491: undef(%domain);
8492: }
8493:
1.852 albertel 8494: sub load_domain_tab {
1.869 albertel 8495: my ($ignore_cache) = @_;
8496: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 8497: my $fh;
8498: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
8499: my @lines = <$fh>;
8500: &parse_domain_tab(\@lines);
1.448 albertel 8501: }
1.852 albertel 8502: close($fh);
8503: $loaded = 1;
1.327 albertel 8504: }
1.846 albertel 8505:
8506: sub domain {
1.852 albertel 8507: &load_domain_tab() if (!$loaded);
8508:
1.846 albertel 8509: my ($name,$what) = @_;
8510: return if ( !exists($domain{$name}) );
8511:
8512: if (!$what) {
8513: return $domain{$name}{'description'};
8514: }
8515: return $domain{$name}{$what};
8516: }
1.327 albertel 8517: }
8518:
8519:
1.1 albertel 8520: # ------------------------------------------------------------- Read hosts file
8521: {
1.838 albertel 8522: my %hostname;
1.844 albertel 8523: my %hostdom;
1.845 albertel 8524: my %libserv;
1.852 albertel 8525: my $loaded;
1.888 albertel 8526: my %name_to_host;
1.852 albertel 8527:
8528: sub parse_hosts_tab {
8529: my ($file) = @_;
8530: foreach my $configline (@$file) {
8531: next if ($configline =~ /^(\#|\s*$ )/x);
8532: next if ($configline =~ /^\^/);
8533: chomp($configline);
8534: my ($id,$domain,$role,$name)=split(/:/,$configline);
8535: $name=~s/\s//g;
8536: if ($id && $domain && $role && $name) {
8537: $hostname{$id}=$name;
1.888 albertel 8538: push(@{$name_to_host{$name}}, $id);
1.852 albertel 8539: $hostdom{$id}=$domain;
8540: if ($role eq 'library') { $libserv{$id}=$name; }
8541: }
8542: }
8543: }
1.864 albertel 8544:
8545: sub reset_hosts_info {
1.897 albertel 8546: &purge_remembered();
1.864 albertel 8547: &reset_domain_info();
8548: &reset_hosts_ip_info();
1.892 albertel 8549: undef(%name_to_host);
1.864 albertel 8550: undef(%hostname);
8551: undef(%hostdom);
8552: undef(%libserv);
8553: undef($loaded);
8554: }
1.1 albertel 8555:
1.852 albertel 8556: sub load_hosts_tab {
1.869 albertel 8557: my ($ignore_cache) = @_;
8558: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 8559: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8560: my @config = <$config>;
8561: &parse_hosts_tab(\@config);
8562: close($config);
8563: $loaded=1;
1.1 albertel 8564: }
1.852 albertel 8565:
1.838 albertel 8566: sub hostname {
1.852 albertel 8567: &load_hosts_tab() if (!$loaded);
8568:
1.838 albertel 8569: my ($lonid) = @_;
8570: return $hostname{$lonid};
8571: }
1.845 albertel 8572:
1.838 albertel 8573: sub all_hostnames {
1.852 albertel 8574: &load_hosts_tab() if (!$loaded);
8575:
1.838 albertel 8576: return %hostname;
8577: }
1.845 albertel 8578:
1.888 albertel 8579: sub all_names {
8580: &load_hosts_tab() if (!$loaded);
8581:
8582: return %name_to_host;
8583: }
8584:
1.845 albertel 8585: sub is_library {
1.852 albertel 8586: &load_hosts_tab() if (!$loaded);
8587:
1.845 albertel 8588: return exists($libserv{$_[0]});
8589: }
8590:
8591: sub all_library {
1.852 albertel 8592: &load_hosts_tab() if (!$loaded);
8593:
1.845 albertel 8594: return %libserv;
8595: }
8596:
1.841 albertel 8597: sub get_servers {
1.852 albertel 8598: &load_hosts_tab() if (!$loaded);
8599:
1.841 albertel 8600: my ($domain,$type) = @_;
8601: my %possible_hosts = ($type eq 'library') ? %libserv
8602: : %hostname;
8603: my %result;
1.842 albertel 8604: if (ref($domain) eq 'ARRAY') {
8605: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 8606: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 8607: $result{$host} = $hostname;
8608: }
8609: }
8610: } else {
8611: while ( my ($host,$hostname) = each(%possible_hosts)) {
8612: if ($hostdom{$host} eq $domain) {
8613: $result{$host} = $hostname;
8614: }
1.841 albertel 8615: }
8616: }
8617: return %result;
8618: }
1.845 albertel 8619:
1.844 albertel 8620: sub host_domain {
1.852 albertel 8621: &load_hosts_tab() if (!$loaded);
8622:
1.844 albertel 8623: my ($lonid) = @_;
8624: return $hostdom{$lonid};
8625: }
8626:
1.841 albertel 8627: sub all_domains {
1.852 albertel 8628: &load_hosts_tab() if (!$loaded);
8629:
1.841 albertel 8630: my %seen;
8631: my @uniq = grep(!$seen{$_}++, values(%hostdom));
8632: return @uniq;
8633: }
1.1 albertel 8634: }
8635:
1.847 albertel 8636: {
8637: my %iphost;
1.856 albertel 8638: my %name_to_ip;
8639: my %lonid_to_ip;
1.869 albertel 8640:
1.847 albertel 8641: sub get_hosts_from_ip {
8642: my ($ip) = @_;
8643: my %iphosts = &get_iphost();
8644: if (ref($iphosts{$ip})) {
8645: return @{$iphosts{$ip}};
8646: }
8647: return;
1.839 albertel 8648: }
1.864 albertel 8649:
8650: sub reset_hosts_ip_info {
8651: undef(%iphost);
8652: undef(%name_to_ip);
8653: undef(%lonid_to_ip);
8654: }
1.856 albertel 8655:
8656: sub get_host_ip {
8657: my ($lonid) = @_;
8658: if (exists($lonid_to_ip{$lonid})) {
8659: return $lonid_to_ip{$lonid};
8660: }
8661: my $name=&hostname($lonid);
8662: my $ip = gethostbyname($name);
8663: return if (!$ip || length($ip) ne 4);
8664: $ip=inet_ntoa($ip);
8665: $name_to_ip{$name} = $ip;
8666: $lonid_to_ip{$lonid} = $ip;
8667: return $ip;
8668: }
1.847 albertel 8669:
8670: sub get_iphost {
1.869 albertel 8671: my ($ignore_cache) = @_;
1.894 albertel 8672:
1.869 albertel 8673: if (!$ignore_cache) {
8674: if (%iphost) {
8675: return %iphost;
8676: }
8677: my ($ip_info,$cached)=
8678: &Apache::lonnet::is_cached_new('iphost','iphost');
8679: if ($cached) {
8680: %iphost = %{$ip_info->[0]};
8681: %name_to_ip = %{$ip_info->[1]};
8682: %lonid_to_ip = %{$ip_info->[2]};
8683: return %iphost;
8684: }
8685: }
1.894 albertel 8686:
8687: # get yesterday's info for fallback
8688: my %old_name_to_ip;
8689: my ($ip_info,$cached)=
8690: &Apache::lonnet::is_cached_new('iphost','iphost');
8691: if ($cached) {
8692: %old_name_to_ip = %{$ip_info->[1]};
8693: }
8694:
1.888 albertel 8695: my %name_to_host = &all_names();
8696: foreach my $name (keys(%name_to_host)) {
1.847 albertel 8697: my $ip;
8698: if (!exists($name_to_ip{$name})) {
8699: $ip = gethostbyname($name);
8700: if (!$ip || length($ip) ne 4) {
1.894 albertel 8701: if (defined($old_name_to_ip{$name})) {
8702: $ip = $old_name_to_ip{$name};
8703: &logthis("Can't find $name defaulting to old $ip");
8704: } else {
8705: &logthis("Name $name no IP found");
8706: next;
8707: }
8708: } else {
8709: $ip=inet_ntoa($ip);
1.847 albertel 8710: }
8711: $name_to_ip{$name} = $ip;
8712: } else {
8713: $ip = $name_to_ip{$name};
1.653 albertel 8714: }
1.888 albertel 8715: foreach my $id (@{ $name_to_host{$name} }) {
8716: $lonid_to_ip{$id} = $ip;
8717: }
8718: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 8719: }
1.869 albertel 8720: &Apache::lonnet::do_cache_new('iphost','iphost',
8721: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 8722: 48*60*60);
1.869 albertel 8723:
1.847 albertel 8724: return %iphost;
1.598 albertel 8725: }
8726: }
8727:
1.862 albertel 8728: BEGIN {
8729:
8730: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
8731: unless ($readit) {
8732: {
8733: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
8734: %perlvar = (%perlvar,%{$configvars});
8735: }
8736:
8737:
1.1 albertel 8738: # ------------------------------------------------------ Read spare server file
8739: {
1.448 albertel 8740: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 8741:
8742: while (my $configline=<$config>) {
8743: chomp($configline);
1.284 matthew 8744: if ($configline) {
1.784 albertel 8745: my ($host,$type) = split(':',$configline,2);
1.785 albertel 8746: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 8747: push(@{ $spareid{$type} }, $host);
1.1 albertel 8748: }
8749: }
1.448 albertel 8750: close($config);
1.1 albertel 8751: }
1.11 www 8752: # ------------------------------------------------------------ Read permissions
8753: {
1.448 albertel 8754: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 8755:
8756: while (my $configline=<$config>) {
1.448 albertel 8757: chomp($configline);
8758: if ($configline) {
8759: my ($role,$perm)=split(/ /,$configline);
8760: if ($perm ne '') { $pr{$role}=$perm; }
8761: }
1.11 www 8762: }
1.448 albertel 8763: close($config);
1.11 www 8764: }
8765:
8766: # -------------------------------------------- Read plain texts for permissions
8767: {
1.448 albertel 8768: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 8769:
8770: while (my $configline=<$config>) {
1.448 albertel 8771: chomp($configline);
8772: if ($configline) {
1.742 raeburn 8773: my ($short,@plain)=split(/:/,$configline);
8774: %{$prp{$short}} = ();
8775: if (@plain > 0) {
8776: $prp{$short}{'std'} = $plain[0];
8777: for (my $i=1; $i<@plain; $i++) {
8778: $prp{$short}{'alt'.$i} = $plain[$i];
8779: }
8780: }
1.448 albertel 8781: }
1.135 www 8782: }
1.448 albertel 8783: close($config);
1.135 www 8784: }
8785:
8786: # ---------------------------------------------------------- Read package table
8787: {
1.448 albertel 8788: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 8789:
8790: while (my $configline=<$config>) {
1.483 albertel 8791: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 8792: chomp($configline);
8793: my ($short,$plain)=split(/:/,$configline);
8794: my ($pack,$name)=split(/\&/,$short);
8795: if ($plain ne '') {
8796: $packagetab{$pack.'&'.$name.'&name'}=$name;
8797: $packagetab{$short}=$plain;
8798: }
1.11 www 8799: }
1.448 albertel 8800: close($config);
1.329 matthew 8801: }
8802:
8803: # ------------- set up temporary directory
8804: {
8805: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
8806:
1.11 www 8807: }
8808:
1.794 albertel 8809: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
8810: 'compress_threshold'=> 20_000,
8811: });
1.185 www 8812:
1.281 www 8813: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 8814: $dumpcount=0;
1.958 www 8815: $locknum=0;
1.22 www 8816:
1.163 harris41 8817: &logtouch();
1.672 albertel 8818: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 8819: $readit=1;
1.564 albertel 8820: {
8821: use integer;
8822: my $test=(2**32)+1;
1.568 albertel 8823: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 8824: &logthis(" Detected 64bit platform ($_64bit)");
8825: }
1.195 www 8826: }
1.1 albertel 8827: }
1.179 www 8828:
1.1 albertel 8829: 1;
1.191 harris41 8830: __END__
8831:
1.243 albertel 8832: =pod
8833:
1.191 harris41 8834: =head1 NAME
8835:
1.243 albertel 8836: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 8837:
8838: =head1 SYNOPSIS
8839:
1.243 albertel 8840: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 8841:
8842: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
8843:
1.243 albertel 8844: Common parameters:
8845:
8846: =over 4
8847:
8848: =item *
8849:
8850: $uname : an internal username (if $cname expecting a course Id specifically)
8851:
8852: =item *
8853:
8854: $udom : a domain (if $cdom expecting a course's domain specifically)
8855:
8856: =item *
8857:
8858: $symb : a resource instance identifier
8859:
8860: =item *
8861:
8862: $namespace : the name of a .db file that contains the data needed or
8863: being set.
8864:
8865: =back
8866:
1.394 bowersj2 8867: =head1 OVERVIEW
1.191 harris41 8868:
1.394 bowersj2 8869: lonnet provides subroutines which interact with the
8870: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
8871: about classes, users, and resources.
1.243 albertel 8872:
8873: For many of these objects you can also use this to store data about
8874: them or modify them in various ways.
1.191 harris41 8875:
1.394 bowersj2 8876: =head2 Symbs
1.191 harris41 8877:
1.394 bowersj2 8878: To identify a specific instance of a resource, LON-CAPA uses symbols
8879: or "symbs"X<symb>. These identifiers are built from the URL of the
8880: map, the resource number of the resource in the map, and the URL of
8881: the resource itself. The latter is somewhat redundant, but might help
8882: if maps change.
8883:
8884: An example is
8885:
8886: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
8887:
8888: The respective map entry is
8889:
8890: <resource id="19" src="/res/msu/korte/tests/part12.problem"
8891: title="Problem 2">
8892: </resource>
8893:
8894: Symbs are used by the random number generator, as well as to store and
8895: restore data specific to a certain instance of for example a problem.
8896:
8897: =head2 Storing And Retrieving Data
8898:
8899: X<store()>X<cstore()>X<restore()>Three of the most important functions
8900: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
8901: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
8902: is is the non-critical message twin of cstore. These functions are for
8903: handlers to store a perl hash to a user's permanent data space in an
8904: easy manner, and to retrieve it again on another call. It is expected
8905: that a handler would use this once at the beginning to retrieve data,
8906: and then again once at the end to send only the new data back.
8907:
8908: The data is stored in the user's data directory on the user's
8909: homeserver under the ID of the course.
8910:
8911: The hash that is returned by restore will have all of the previous
8912: value for all of the elements of the hash.
8913:
8914: Example:
8915:
8916: #creating a hash
8917: my %hash;
8918: $hash{'foo'}='bar';
8919:
8920: #storing it
8921: &Apache::lonnet::cstore(\%hash);
8922:
8923: #changing a value
8924: $hash{'foo'}='notbar';
8925:
8926: #adding a new value
8927: $hash{'bar'}='foo';
8928: &Apache::lonnet::cstore(\%hash);
8929:
8930: #retrieving the hash
8931: my %history=&Apache::lonnet::restore();
8932:
8933: #print the hash
8934: foreach my $key (sort(keys(%history))) {
8935: print("\%history{$key} = $history{$key}");
8936: }
8937:
8938: Will print out:
1.191 harris41 8939:
1.394 bowersj2 8940: %history{1:foo} = bar
8941: %history{1:keys} = foo:timestamp
8942: %history{1:timestamp} = 990455579
8943: %history{2:bar} = foo
8944: %history{2:foo} = notbar
8945: %history{2:keys} = foo:bar:timestamp
8946: %history{2:timestamp} = 990455580
8947: %history{bar} = foo
8948: %history{foo} = notbar
8949: %history{timestamp} = 990455580
8950: %history{version} = 2
8951:
8952: Note that the special hash entries C<keys>, C<version> and
8953: C<timestamp> were added to the hash. C<version> will be equal to the
8954: total number of versions of the data that have been stored. The
8955: C<timestamp> attribute will be the UNIX time the hash was
8956: stored. C<keys> is available in every historical section to list which
8957: keys were added or changed at a specific historical revision of a
8958: hash.
8959:
8960: B<Warning>: do not store the hash that restore returns directly. This
8961: will cause a mess since it will restore the historical keys as if the
8962: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 8963:
1.394 bowersj2 8964: Calling convention:
1.191 harris41 8965:
1.394 bowersj2 8966: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
8967: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 8968:
1.394 bowersj2 8969: For more detailed information, see lonnet specific documentation.
1.191 harris41 8970:
1.394 bowersj2 8971: =head1 RETURN MESSAGES
1.191 harris41 8972:
1.394 bowersj2 8973: =over 4
1.191 harris41 8974:
1.394 bowersj2 8975: =item * B<con_lost>: unable to contact remote host
1.191 harris41 8976:
1.394 bowersj2 8977: =item * B<con_delayed>: unable to contact remote host, message will be delivered
8978: when the connection is brought back up
1.191 harris41 8979:
1.394 bowersj2 8980: =item * B<con_failed>: unable to contact remote host and unable to save message
8981: for later delivery
1.191 harris41 8982:
1.394 bowersj2 8983: =item * B<error:>: an error a occured, a description of the error follows the :
1.191 harris41 8984:
1.394 bowersj2 8985: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 8986: that was requested
1.191 harris41 8987:
1.243 albertel 8988: =back
1.191 harris41 8989:
1.243 albertel 8990: =head1 PUBLIC SUBROUTINES
1.191 harris41 8991:
1.243 albertel 8992: =head2 Session Environment Functions
1.191 harris41 8993:
1.243 albertel 8994: =over 4
1.191 harris41 8995:
1.394 bowersj2 8996: =item *
8997: X<appenv()>
1.949 raeburn 8998: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 8999: the user envirnoment file, and will be restored for each access this
1.620 albertel 9000: user makes during this session, also modifies the %env for the current
1.949 raeburn 9001: process. Optional rolesarrayref - if defined contains a reference to an array
9002: of roles which are exempt from the restriction on modifying user.role entries
9003: in the user's environment.db and in %env.
1.191 harris41 9004:
9005: =item *
1.394 bowersj2 9006: X<delenv()>
9007: B<delenv($regexp)>: removes all items from the session
9008: environment file that matches the regular expression in $regexp. The
1.620 albertel 9009: values are also delted from the current processes %env.
1.191 harris41 9010:
1.795 albertel 9011: =item * get_env_multiple($name)
9012:
9013: gets $name from the %env hash, it seemlessly handles the cases where multiple
9014: values may be defined and end up as an array ref.
9015:
9016: returns an array of values
9017:
1.243 albertel 9018: =back
9019:
9020: =head2 User Information
1.191 harris41 9021:
1.243 albertel 9022: =over 4
1.191 harris41 9023:
9024: =item *
1.394 bowersj2 9025: X<queryauthenticate()>
9026: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 9027: authentication scheme
9028:
9029: =item *
1.394 bowersj2 9030: X<authenticate()>
9031: B<authenticate($uname,$upass,$udom)>: try to
9032: authenticate user from domain's lib servers (first use the current
9033: one). C<$upass> should be the users password.
1.191 harris41 9034:
9035: =item *
1.394 bowersj2 9036: X<homeserver()>
9037: B<homeserver($uname,$udom)>: find the server which has
9038: the user's directory and files (there must be only one), this caches
9039: the answer, and also caches if there is a borken connection.
1.191 harris41 9040:
9041: =item *
1.394 bowersj2 9042: X<idget()>
9043: B<idget($udom,@ids)>: find the usernames behind a list of IDs
9044: (IDs are a unique resource in a domain, there must be only 1 ID per
9045: username, and only 1 username per ID in a specific domain) (returns
9046: hash: id=>name,id=>name)
1.191 harris41 9047:
9048: =item *
1.394 bowersj2 9049: X<idrget()>
9050: B<idrget($udom,@unames)>: find the IDs behind a list of
9051: usernames (returns hash: name=>id,name=>id)
1.191 harris41 9052:
9053: =item *
1.394 bowersj2 9054: X<idput()>
9055: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 9056:
9057: =item *
1.394 bowersj2 9058: X<rolesinit()>
9059: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 9060:
9061: =item *
1.551 albertel 9062: X<getsection()>
9063: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 9064: course $cname, return section name/number or '' for "not in course"
9065: and '-1' for "no section"
9066:
9067: =item *
1.394 bowersj2 9068: X<userenvironment()>
9069: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 9070: passed in @what from the requested user's environment, returns a hash
9071:
1.858 raeburn 9072: =item *
9073: X<userlog_query()>
1.859 albertel 9074: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
9075: activity.log file. %filters defines filters applied when parsing the
9076: log file. These can be start or end timestamps, or the type of action
9077: - log to look for Login or Logout events, check for Checkin or
9078: Checkout, role for role selection. The response is in the form
9079: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
9080: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 9081:
1.243 albertel 9082: =back
9083:
9084: =head2 User Roles
9085:
9086: =over 4
9087:
9088: =item *
9089:
1.810 raeburn 9090: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 9091: F: full access
9092: U,I,K: authentication modes (cxx only)
9093: '': forbidden
9094: 1: user needs to choose course
9095: 2: browse allowed
1.766 albertel 9096: A: passphrase authentication needed
1.243 albertel 9097:
9098: =item *
9099:
9100: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
9101: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
9102: and course level
9103:
9104: =item *
9105:
9106: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
9107: explanation of a user role term
9108:
1.832 raeburn 9109: =item *
9110:
1.935 raeburn 9111: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 9112: All arguments are optional. Returns a hash of a roles, either for
9113: co-author/assistant author roles for a user's Construction Space
1.906 albertel 9114: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 9115: In the hash, keys are set to colon-separated $uname,$udom,$role, and
9116: (optionally) if $withsec is true, a fourth colon-separated item - $section.
9117: For each key, value is set to colon-separated start and end times for
9118: the role. If no username and domain are specified, will default to
1.934 raeburn 9119: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 9120: of role statuses (active, future or previous), roles
9121: (e.g., cc,in, st etc.) and domains of the roles which can be used
9122: to restrict the list of roles reported. If no array ref is
9123: provided for types, will default to return only active roles.
1.834 albertel 9124:
1.243 albertel 9125: =back
9126:
9127: =head2 User Modification
9128:
9129: =over 4
9130:
9131: =item *
9132:
1.957 raeburn 9133: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 9134: user for the level given by URL. Optional start and end dates (leave empty
9135: string or zero for "no date")
1.191 harris41 9136:
9137: =item *
9138:
1.243 albertel 9139: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
9140: change a users, password, possible return values are: ok,
9141: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
9142: refused
1.191 harris41 9143:
9144: =item *
9145:
1.243 albertel 9146: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 9147:
9148: =item *
9149:
1.243 albertel 9150: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
9151: modify user
1.191 harris41 9152:
9153: =item *
9154:
1.286 matthew 9155: modifystudent
9156:
1.957 raeburn 9157: modify a student's enrollment and identification information.
1.286 matthew 9158: The course id is resolved based on the current users environment.
9159: This means the envoking user must be a course coordinator or otherwise
9160: associated with a course.
9161:
1.297 matthew 9162: This call is essentially a wrapper for lonnet::modifyuser and
9163: lonnet::modify_student_enrollment
1.286 matthew 9164:
9165: Inputs:
9166:
9167: =over 4
9168:
1.957 raeburn 9169: =item B<$udom> Student's loncapa domain
1.286 matthew 9170:
1.957 raeburn 9171: =item B<$uname> Student's loncapa login name
1.286 matthew 9172:
1.957 raeburn 9173: =item B<$uid> Student's id/student number
1.286 matthew 9174:
1.957 raeburn 9175: =item B<$umode> Student's authentication mode
1.286 matthew 9176:
1.957 raeburn 9177: =item B<$upass> Student's password
1.286 matthew 9178:
1.957 raeburn 9179: =item B<$first> Student's first name
1.286 matthew 9180:
1.957 raeburn 9181: =item B<$middle> Student's middle name
1.286 matthew 9182:
1.957 raeburn 9183: =item B<$last> Student's last name
1.286 matthew 9184:
1.957 raeburn 9185: =item B<$gene> Student's generation
1.286 matthew 9186:
1.957 raeburn 9187: =item B<$usec> Student's section in course
1.286 matthew 9188:
9189: =item B<$end> Unix time of the roles expiration
9190:
9191: =item B<$start> Unix time of the roles start date
9192:
9193: =item B<$forceid> If defined, allow $uid to be changed
9194:
9195: =item B<$desiredhome> server to use as home server for student
9196:
1.957 raeburn 9197: =item B<$email> Student's permanent e-mail address
9198:
9199: =item B<$type> Type of enrollment (auto or manual)
9200:
9201: =item B<$locktype>
9202:
9203: =item B<$cid>
9204:
9205: =item B<$selfenroll>
9206:
9207: =item B<$context>
9208:
1.286 matthew 9209: =back
1.297 matthew 9210:
9211: =item *
9212:
9213: modify_student_enrollment
9214:
9215: Change a students enrollment status in a class. The environment variable
9216: 'role.request.course' must be defined for this function to proceed.
9217:
9218: Inputs:
9219:
9220: =over 4
9221:
9222: =item $udom, students domain
9223:
9224: =item $uname, students name
9225:
9226: =item $uid, students user id
9227:
9228: =item $first, students first name
9229:
9230: =item $middle
9231:
9232: =item $last
9233:
9234: =item $gene
9235:
9236: =item $usec
9237:
9238: =item $end
9239:
9240: =item $start
9241:
1.957 raeburn 9242: =item $type
9243:
9244: =item $locktype
9245:
9246: =item $cid
9247:
9248: =item $selfenroll
9249:
9250: =item $context
9251:
1.297 matthew 9252: =back
9253:
1.191 harris41 9254:
9255: =item *
9256:
1.243 albertel 9257: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
9258: custom role; give a custom role to a user for the level given by URL. Specify
9259: name and domain of role author, and role name
1.191 harris41 9260:
9261: =item *
9262:
1.243 albertel 9263: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 9264:
9265: =item *
9266:
1.243 albertel 9267: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
9268:
9269: =back
9270:
9271: =head2 Course Infomation
9272:
9273: =over 4
1.191 harris41 9274:
9275: =item *
9276:
1.631 albertel 9277: coursedescription($courseid) : returns a hash of information about the
9278: specified course id, including all environment settings for the
9279: course, the description of the course will be in the hash under the
9280: key 'description'
1.191 harris41 9281:
9282: =item *
9283:
1.624 albertel 9284: resdata($name,$domain,$type,@which) : request for current parameter
9285: setting for a specific $type, where $type is either 'course' or 'user',
9286: @what should be a list of parameters to ask about. This routine caches
9287: answers for 5 minutes.
1.243 albertel 9288:
1.877 foxr 9289: =item *
9290:
9291: get_courseresdata($courseid, $domain) : dump the entire course resource
9292: data base, returning a hash that is keyed by the resource name and has
9293: values that are the resource value. I believe that the timestamps and
9294: versions are also returned.
9295:
9296:
1.243 albertel 9297: =back
9298:
9299: =head2 Course Modification
9300:
9301: =over 4
1.191 harris41 9302:
9303: =item *
9304:
1.243 albertel 9305: writecoursepref($courseid,%prefs) : write preferences (environment
9306: database) for a course
1.191 harris41 9307:
9308: =item *
9309:
1.243 albertel 9310: createcourse($udom,$description,$url) : make/modify course
9311:
9312: =back
9313:
9314: =head2 Resource Subroutines
9315:
9316: =over 4
1.191 harris41 9317:
9318: =item *
9319:
1.243 albertel 9320: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 9321:
9322: =item *
9323:
1.243 albertel 9324: repcopy($filename) : subscribes to the requested file, and attempts to
9325: replicate from the owning library server, Might return
1.607 raeburn 9326: 'unavailable', 'not_found', 'forbidden', 'ok', or
9327: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 9328: resource. Expects the local filesystem pathname
9329: (/home/httpd/html/res/....)
9330:
9331: =back
9332:
9333: =head2 Resource Information
9334:
9335: =over 4
1.191 harris41 9336:
9337: =item *
9338:
1.243 albertel 9339: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
9340: a vairety of different possible values, $varname should be a request
9341: string, and the other parameters can be used to specify who and what
9342: one is asking about.
9343:
9344: Possible values for $varname are environment.lastname (or other item
9345: from the envirnment hash), user.name (or someother aspect about the
9346: user), resource.0.maxtries (or some other part and parameter of a
9347: resource)
1.204 albertel 9348:
9349: =item *
9350:
1.243 albertel 9351: directcondval($number) : get current value of a condition; reads from a state
9352: string
1.204 albertel 9353:
9354: =item *
9355:
1.243 albertel 9356: condval($condidx) : value of condition index based on state
1.204 albertel 9357:
9358: =item *
9359:
1.243 albertel 9360: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
9361: resource's metadata, $what should be either a specific key, or either
9362: 'keys' (to get a list of possible keys) or 'packages' to get a list of
9363: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
9364:
9365: this function automatically caches all requests
1.191 harris41 9366:
9367: =item *
9368:
1.243 albertel 9369: metadata_query($query,$custom,$customshow) : make a metadata query against the
9370: network of library servers; returns file handle of where SQL and regex results
9371: will be stored for query
1.191 harris41 9372:
9373: =item *
9374:
1.243 albertel 9375: symbread($filename) : return symbolic list entry (filename argument optional);
9376: returns the data handle
1.191 harris41 9377:
9378: =item *
9379:
1.243 albertel 9380: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 9381: a possible symb for the URL in $thisfn, and if is an encryypted
9382: resource that the user accessed using /enc/ returns a 1 on success, 0
9383: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 9384: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 9385:
1.191 harris41 9386:
9387: =item *
9388:
1.243 albertel 9389: symbclean($symb) : removes versions numbers from a symb, returns the
9390: cleaned symb
1.191 harris41 9391:
9392: =item *
9393:
1.243 albertel 9394: is_on_map($uri) : checks if the $uri is somewhere on the current
9395: course map, user must be in a course for it to work.
1.191 harris41 9396:
9397: =item *
9398:
1.243 albertel 9399: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 9400:
9401: =item *
9402:
1.243 albertel 9403: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
9404: a random seed, all arguments are optional, if they aren't sent it uses the
9405: environment to derive them. Note: if symb isn't sent and it can't get one
9406: from &symbread it will use the current time as its return value
1.191 harris41 9407:
9408: =item *
9409:
1.243 albertel 9410: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
9411: unfakeable, receipt
1.191 harris41 9412:
9413: =item *
9414:
1.620 albertel 9415: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 9416:
9417: =item *
9418:
1.243 albertel 9419: countacc($url) : count the number of accesses to a given URL
1.191 harris41 9420:
9421: =item *
9422:
1.243 albertel 9423: 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 9424:
9425: =item *
9426:
1.243 albertel 9427: 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 9428:
9429: =item *
9430:
1.243 albertel 9431: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 9432:
9433: =item *
9434:
1.243 albertel 9435: devalidate($symb) : devalidate temporary spreadsheet calculations,
9436: forcing spreadsheet to reevaluate the resource scores next time.
9437:
9438: =back
9439:
9440: =head2 Storing/Retreiving Data
9441:
9442: =over 4
1.191 harris41 9443:
9444: =item *
9445:
1.243 albertel 9446: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
9447: for this url; hashref needs to be given and should be a \%hashname; the
9448: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 9449: be derived from the env
1.191 harris41 9450:
9451: =item *
9452:
1.243 albertel 9453: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
9454: uses critical subroutine
1.191 harris41 9455:
9456: =item *
9457:
1.243 albertel 9458: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
9459: all args are optional
1.191 harris41 9460:
9461: =item *
9462:
1.717 albertel 9463: dumpstore($namespace,$udom,$uname,$regexp,$range) :
9464: dumps the complete (or key matching regexp) namespace into a hash
9465: ($udom, $uname, $regexp, $range are optional) for a namespace that is
9466: normally &store()ed into
9467:
9468: $range should be either an integer '100' (give me the first 100
9469: matching records)
9470: or be two integers sperated by a - with no spaces
9471: '30-50' (give me the 30th through the 50th matching
9472: records)
9473:
9474:
9475: =item *
9476:
9477: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
9478: replaces a &store() version of data with a replacement set of data
9479: for a particular resource in a namespace passed in the $storehash hash
9480: reference
9481:
9482: =item *
9483:
1.243 albertel 9484: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
9485: works very similar to store/cstore, but all data is stored in a
9486: temporary location and can be reset using tmpreset, $storehash should
9487: be a hash reference, returns nothing on success
1.191 harris41 9488:
9489: =item *
9490:
1.243 albertel 9491: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
9492: similar to restore, but all data is stored in a temporary location and
9493: can be reset using tmpreset. Returns a hash of values on success,
9494: error string otherwise.
1.191 harris41 9495:
9496: =item *
9497:
1.243 albertel 9498: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
9499: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 9500:
9501: =item *
9502:
1.243 albertel 9503: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9504: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 9505:
9506: =item *
9507:
1.243 albertel 9508: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
9509: namesp ($udom and $uname are optional)
1.191 harris41 9510:
9511: =item *
9512:
1.702 albertel 9513: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 9514: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 9515: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 9516:
1.702 albertel 9517: $range should be either an integer '100' (give me the first 100
9518: matching records)
9519: or be two integers sperated by a - with no spaces
9520: '30-50' (give me the 30th through the 50th matching
9521: records)
1.449 matthew 9522: =item *
9523:
9524: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
9525: $store can be a scalar, an array reference, or if the amount to be
9526: incremented is > 1, a hash reference.
9527:
9528: ($udom and $uname are optional)
1.191 harris41 9529:
9530: =item *
9531:
1.243 albertel 9532: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
9533: ($udom and $uname are optional)
1.191 harris41 9534:
9535: =item *
9536:
1.243 albertel 9537: cput($namespace,$storehash,$udom,$uname) : critical put
9538: ($udom and $uname are optional)
1.191 harris41 9539:
9540: =item *
9541:
1.748 albertel 9542: newput($namespace,$storehash,$udom,$uname) :
9543:
9544: Attempts to store the items in the $storehash, but only if they don't
9545: currently exist, if this succeeds you can be certain that you have
9546: successfully created a new key value pair in the $namespace db.
9547:
9548:
9549: Args:
9550: $namespace: name of database to store values to
9551: $storehash: hashref to store to the db
9552: $udom: (optional) domain of user containing the db
9553: $uname: (optional) name of user caontaining the db
9554:
9555: Returns:
9556: 'ok' -> succeeded in storing all keys of $storehash
9557: 'key_exists: <key>' -> failed to anything out of $storehash, as at
9558: least <key> already existed in the db (other
9559: requested keys may also already exist)
9560: 'error: <msg>' -> unable to tie the DB or other erorr occured
9561: 'con_lost' -> unable to contact request server
9562: 'refused' -> action was not allowed by remote machine
9563:
9564:
9565: =item *
9566:
1.243 albertel 9567: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9568: reference filled in from namesp (encrypts the return communication)
9569: ($udom and $uname are optional)
1.191 harris41 9570:
9571: =item *
9572:
1.243 albertel 9573: log($udom,$name,$home,$message) : write to permanent log for user; use
9574: critical subroutine
9575:
1.806 raeburn 9576: =item *
9577:
1.860 raeburn 9578: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
9579: array reference filled in from namespace found in domain level on either
9580: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 9581:
9582: =item *
9583:
1.860 raeburn 9584: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
9585: domain level either on specified domain server ($uhome) or primary domain
9586: server ($udom and $uhome are optional)
1.806 raeburn 9587:
1.943 raeburn 9588: =item *
9589:
9590: get_domain_defaults($target_domain) : returns hash with defaults for
9591: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
9592: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
9593: or localauth), initial password or a kerberos realm, language (e.g., en-us).
9594: Values are retrieved from cache (if current), or from domain's configuration.db
9595: (if available), or lastly from values in lonTabs/dns_domain,tab,
9596: or lonTabs/domain.tab.
9597:
9598: %domdefaults = &get_auth_defaults($target_domain);
9599:
1.243 albertel 9600: =back
9601:
9602: =head2 Network Status Functions
9603:
9604: =over 4
1.191 harris41 9605:
9606: =item *
9607:
9608: dirlist($uri) : return directory list based on URI
9609:
9610: =item *
9611:
1.243 albertel 9612: spareserver() : find server with least workload from spare.tab
9613:
9614: =back
9615:
9616: =head2 Apache Request
9617:
9618: =over 4
1.191 harris41 9619:
9620: =item *
9621:
1.243 albertel 9622: ssi($url,%hash) : server side include, does a complete request cycle on url to
9623: localhost, posts hash
9624:
9625: =back
9626:
9627: =head2 Data to String to Data
9628:
9629: =over 4
1.191 harris41 9630:
9631: =item *
9632:
1.243 albertel 9633: hash2str(%hash) : convert a hash into a string complete with escaping and '='
9634: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 9635:
9636: =item *
9637:
1.243 albertel 9638: hashref2str($hashref) : convert a hashref into a string complete with
9639: escaping and '=' and '&' separators, supports elements that are
9640: arrayrefs and hashrefs
1.191 harris41 9641:
9642: =item *
9643:
1.243 albertel 9644: arrayref2str($arrayref) : convert an arrayref into a string complete
9645: with escaping and '&' separators, supports elements that are arrayrefs
9646: and hashrefs
1.191 harris41 9647:
9648: =item *
9649:
1.243 albertel 9650: str2hash($string) : convert string to hash using unescaping and
9651: splitting on '=' and '&', supports elements that are arrayrefs and
9652: hashrefs
1.191 harris41 9653:
9654: =item *
9655:
1.243 albertel 9656: str2array($string) : convert string to hash using unescaping and
9657: splitting on '&', supports elements that are arrayrefs and hashrefs
9658:
9659: =back
9660:
9661: =head2 Logging Routines
9662:
9663: =over 4
9664:
9665: These routines allow one to make log messages in the lonnet.log and
9666: lonnet.perm logfiles.
1.191 harris41 9667:
9668: =item *
9669:
1.243 albertel 9670: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 9671:
9672: =item *
9673:
1.243 albertel 9674: logthis() : append message to the normal lonnet.log file, it gets
9675: preiodically rolled over and deleted.
1.191 harris41 9676:
9677: =item *
9678:
1.243 albertel 9679: logperm() : append a permanent message to lonnet.perm.log, this log
9680: file never gets deleted by any automated portion of the system, only
9681: messages of critical importance should go in here.
9682:
9683: =back
9684:
9685: =head2 General File Helper Routines
9686:
9687: =over 4
1.191 harris41 9688:
9689: =item *
9690:
1.481 raeburn 9691: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
9692: (a) files in /uploaded
9693: (i) If a local copy of the file exists -
9694: compares modification date of local copy with last-modified date for
9695: definitive version stored on home server for course. If local copy is
9696: stale, requests a new version from the home server and stores it.
9697: If the original has been removed from the home server, then local copy
9698: is unlinked.
9699: (ii) If local copy does not exist -
9700: requests the file from the home server and stores it.
9701:
9702: If $caller is 'uploadrep':
9703: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
9704: for request for files originally uploaded via DOCS.
9705: - returns 'ok' if fresh local copy now available, -1 otherwise.
9706:
9707: Otherwise:
9708: This indicates a call from the content generation phase of the request.
9709: - returns the entire contents of the file or -1.
9710:
9711: (b) files in /res
9712: - returns the entire contents of a file or -1;
9713: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 9714:
1.712 albertel 9715:
9716: =item *
9717:
9718: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
9719: reference
9720:
9721: returns either a stat() list of data about the file or an empty list
9722: if the file doesn't exist or couldn't find out about it (connection
9723: problems or user unknown)
9724:
1.191 harris41 9725: =item *
9726:
1.243 albertel 9727: filelocation($dir,$file) : returns file system location of a file
9728: based on URI; meant to be "fairly clean" absolute reference, $dir is a
9729: directory that relative $file lookups are to looked in ($dir of /a/dir
9730: and a file of ../bob will become /a/bob)
1.191 harris41 9731:
9732: =item *
9733:
9734: hreflocation($dir,$file) : returns file system location or a URL; same as
9735: filelocation except for hrefs
9736:
9737: =item *
9738:
9739: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
9740:
1.243 albertel 9741: =back
9742:
1.608 albertel 9743: =head2 Usererfile file routines (/uploaded*)
9744:
9745: =over 4
9746:
9747: =item *
9748:
9749: userfileupload(): main rotine for putting a file in a user or course's
9750: filespace, arguments are,
9751:
1.620 albertel 9752: formname - required - this is the name of the element in $env where the
1.608 albertel 9753: filename, and the contents of the file to create/modifed exist
1.620 albertel 9754: the filename is in $env{'form.'.$formname.'.filename'} and the
9755: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 9756: coursedoc - if true, store the file in the course of the active role
9757: of the current user
9758: subdir - required - subdirectory to put the file in under ../userfiles/
9759: if undefined, it will be placed in "unknown"
9760:
9761: (This routine calls clean_filename() to remove any dangerous
9762: characters from the filename, and then calls finuserfileupload() to
9763: complete the transaction)
9764:
9765: returns either the url of the uploaded file (/uploaded/....) if successful
9766: and /adm/notfound.html if unsuccessful
9767:
9768: =item *
9769:
9770: clean_filename(): routine for cleaing a filename up for storage in
9771: userfile space, argument is:
9772:
9773: filename - proposed filename
9774:
9775: returns: the new clean filename
9776:
9777: =item *
9778:
9779: finishuserfileupload(): routine that creaes and sends the file to
9780: userspace, probably shouldn't be called directly
9781:
9782: docuname: username or courseid of destination for the file
9783: docudom: domain of user/course of destination for the file
9784: formname: same as for userfileupload()
9785: fname: filename (inculding subdirectories) for the file
9786:
9787: returns either the url of the uploaded file (/uploaded/....) if successful
9788: and /adm/notfound.html if unsuccessful
9789:
9790: =item *
9791:
9792: renameuserfile(): renames an existing userfile to a new name
9793:
9794: Args:
9795: docuname: username or courseid of destination for the file
9796: docudom: domain of user/course of destination for the file
9797: old: current file name (including any subdirs under userfiles)
9798: new: desired file name (including any subdirs under userfiles)
9799:
9800: =item *
9801:
9802: mkdiruserfile(): creates a directory is a userfiles dir
9803:
9804: Args:
9805: docuname: username or courseid of destination for the file
9806: docudom: domain of user/course of destination for the file
9807: dir: dir to create (including any subdirs under userfiles)
9808:
9809: =item *
9810:
9811: removeuserfile(): removes a file that exists in userfiles
9812:
9813: Args:
9814: docuname: username or courseid of destination for the file
9815: docudom: domain of user/course of destination for the file
9816: fname: filname to delete (including any subdirs under userfiles)
9817:
9818: =item *
9819:
9820: removeuploadedurl(): convience function for removeuserfile()
9821:
9822: Args:
9823: url: a full /uploaded/... url to delete
9824:
1.747 albertel 9825: =item *
9826:
9827: get_portfile_permissions():
9828: Args:
9829: domain: domain of user or course contain the portfolio files
9830: user: name of user or num of course contain the portfolio files
9831: Returns:
9832: hashref of a dump of the proper file_permissions.db
9833:
9834:
9835: =item *
9836:
9837: get_access_controls():
9838:
9839: Args:
9840: current_permissions: the hash ref returned from get_portfile_permissions()
9841: group: (optional) the group you want the files associated with
9842: file: (optional) the file you want access info on
9843:
9844: Returns:
1.749 raeburn 9845: a hash (keys are file names) of hashes containing
9846: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
9847: values are XML containing access control settings (see below)
1.747 albertel 9848:
9849: Internal notes:
9850:
1.749 raeburn 9851: access controls are stored in file_permissions.db as key=value pairs.
9852: key -> path to file/file_name\0uniqueID:scope_end_start
9853: where scope -> public,guest,course,group,domains or users.
9854: end -> UNIX time for end of access (0 -> no end date)
9855: start -> UNIX time for start of access
9856:
9857: value -> XML description of access control
9858: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
9859: <start></start>
9860: <end></end>
9861:
9862: <password></password> for scope type = guest
9863:
9864: <domain></domain> for scope type = course or group
9865: <number></number>
9866: <roles id="">
9867: <role></role>
9868: <access></access>
9869: <section></section>
9870: <group></group>
9871: </roles>
9872:
9873: <dom></dom> for scope type = domains
9874:
9875: <users> for scope type = users
9876: <user>
9877: <uname></uname>
9878: <udom></udom>
9879: </user>
9880: </users>
9881: </scope>
9882:
9883: Access data is also aggregated for each file in an additional key=value pair:
9884: key -> path to file/file_name\0accesscontrol
9885: value -> reference to hash
9886: hash contains key = value pairs
9887: where key = uniqueID:scope_end_start
9888: value = UNIX time record was last updated
9889:
9890: Used to improve speed of look-ups of access controls for each file.
9891:
9892: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
9893:
9894: modify_access_controls():
9895:
9896: Modifies access controls for a portfolio file
9897: Args
9898: 1. file name
9899: 2. reference to hash of required changes,
9900: 3. domain
9901: 4. username
9902: where domain,username are the domain of the portfolio owner
9903: (either a user or a course)
9904:
9905: Returns:
9906: 1. result of additions or updates ('ok' or 'error', with error message).
9907: 2. result of deletions ('ok' or 'error', with error message).
9908: 3. reference to hash of any new or updated access controls.
9909: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
9910: key = integer (inbound ID)
9911: value = uniqueID
1.747 albertel 9912:
1.608 albertel 9913: =back
9914:
1.243 albertel 9915: =head2 HTTP Helper Routines
9916:
9917: =over 4
9918:
1.191 harris41 9919: =item *
9920:
9921: escape() : unpack non-word characters into CGI-compatible hex codes
9922:
9923: =item *
9924:
9925: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
9926:
1.243 albertel 9927: =back
9928:
9929: =head1 PRIVATE SUBROUTINES
9930:
9931: =head2 Underlying communication routines (Shouldn't call)
9932:
9933: =over 4
9934:
9935: =item *
9936:
9937: subreply() : tries to pass a message to lonc, returns con_lost if incapable
9938:
9939: =item *
9940:
9941: reply() : uses subreply to send a message to remote machine, logs all failures
9942:
9943: =item *
9944:
9945: critical() : passes a critical message to another server; if cannot
9946: get through then place message in connection buffer directory and
9947: returns con_delayed, if incapable of saving message, returns
9948: con_failed
9949:
9950: =item *
9951:
9952: reconlonc() : tries to reconnect lonc client processes.
9953:
9954: =back
9955:
9956: =head2 Resource Access Logging
9957:
9958: =over 4
9959:
9960: =item *
9961:
9962: flushcourselogs() : flush (save) buffer logs and access logs
9963:
9964: =item *
9965:
9966: courselog($what) : save message for course in hash
9967:
9968: =item *
9969:
9970: courseacclog($what) : save message for course using &courselog(). Perform
9971: special processing for specific resource types (problems, exams, quizzes, etc).
9972:
1.191 harris41 9973: =item *
9974:
9975: goodbye() : flush course logs and log shutting down; it is called in srm.conf
9976: as a PerlChildExitHandler
1.243 albertel 9977:
9978: =back
9979:
9980: =head2 Other
9981:
9982: =over 4
9983:
9984: =item *
9985:
9986: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 9987:
9988: =back
9989:
9990: =cut
1.877 foxr 9991:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>