Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.970
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.970 ! raeburn 4: # $Id: lonnet.pm,v 1.969 2008/09/29 22:49:05 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
1.968 raeburn 37: $_64bit %env %protocol);
1.871 albertel 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.968 raeburn 646: my $protocol = 'http';
647: if ($protocol{$spare_server} eq 'https') {
648: $protocol = $protocol{$spare_server};
649: }
650: $spare_server = $protocol.'://'.&hostname($spare_server);
1.784 albertel 651: }
652: return $spare_server;
653: }
654:
655: sub compare_server_load {
656: my ($try_server, $spare_server, $lowest_load) = @_;
657:
658: my $loadans = &reply('load', $try_server);
659: my $userloadans = &reply('userload',$try_server);
660:
661: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
662: next; #didn't get a number from the server
663: }
664:
665: my $load;
666: if ($loadans =~ /\d/) {
667: if ($userloadans =~ /\d/) {
668: #both are numbers, pick the bigger one
669: $load = ($loadans > $userloadans) ? $loadans
670: : $userloadans;
1.411 albertel 671: } else {
1.784 albertel 672: $load = $loadans;
1.411 albertel 673: }
1.784 albertel 674: } else {
675: $load = $userloadans;
676: }
677:
678: if (($load =~ /\d/) && ($load < $lowest_load)) {
679: $spare_server = $try_server;
680: $lowest_load = $load;
1.370 albertel 681: }
1.784 albertel 682: return ($spare_server,$lowest_load);
1.202 matthew 683: }
1.914 albertel 684:
685: # --------------------------- ask offload servers if user already has a session
686: sub find_existing_session {
687: my ($udom,$uname) = @_;
688: foreach my $try_server (@{ $spareid{'primary'} },
689: @{ $spareid{'default'} }) {
690: return $try_server if (&has_user_session($try_server, $udom, $uname));
691: }
692: return;
693: }
694:
695: # -------------------------------- ask if server already has a session for user
696: sub has_user_session {
697: my ($lonid,$udom,$uname) = @_;
698: my $result = &reply(join(':','userhassession',
699: map {&escape($_)} ($udom,$uname)),$lonid);
700: return 1 if ($result eq 'ok');
701:
702: return 0;
703: }
704:
1.202 matthew 705: # --------------------------------------------- Try to change a user's password
706:
707: sub changepass {
1.799 raeburn 708: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 709: $currentpass = &escape($currentpass);
710: $newpass = &escape($newpass);
1.799 raeburn 711: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202 matthew 712: $server);
713: if (! $answer) {
714: &logthis("No reply on password change request to $server ".
715: "by $uname in domain $udom.");
716: } elsif ($answer =~ "^ok") {
717: &logthis("$uname in $udom successfully changed their password ".
718: "on $server.");
719: } elsif ($answer =~ "^pwchange_failure") {
720: &logthis("$uname in $udom was unable to change their password ".
721: "on $server. The action was blocked by either lcpasswd ".
722: "or pwchange");
723: } elsif ($answer =~ "^non_authorized") {
724: &logthis("$uname in $udom did not get their password correct when ".
725: "attempting to change it on $server.");
726: } elsif ($answer =~ "^auth_mode_error") {
727: &logthis("$uname in $udom attempted to change their password despite ".
728: "not being locally or internally authenticated on $server.");
729: } elsif ($answer =~ "^unknown_user") {
730: &logthis("$uname in $udom attempted to change their password ".
731: "on $server but were unable to because $server is not ".
732: "their home server.");
733: } elsif ($answer =~ "^refused") {
734: &logthis("$server refused to change $uname in $udom password because ".
735: "it was sent an unencrypted request to change the password.");
736: }
737: return $answer;
1.1 albertel 738: }
739:
1.169 harris41 740: # ----------------------- Try to determine user's current authentication scheme
741:
742: sub queryauthenticate {
743: my ($uname,$udom)=@_;
1.456 albertel 744: my $uhome=&homeserver($uname,$udom);
745: if (!$uhome) {
746: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
747: return 'no_host';
748: }
749: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
750: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
751: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 752: }
1.456 albertel 753: return $answer;
1.169 harris41 754: }
755:
1.1 albertel 756: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 757:
1.1 albertel 758: sub authenticate {
1.952 raeburn 759: my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807 albertel 760: $upass=&escape($upass);
761: $uname= &LONCAPA::clean_username($uname);
1.836 www 762: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 763: my $newhome;
1.836 www 764: if ((!$uhome) || ($uhome eq 'no_host')) {
765: # Maybe the machine was offline and only re-appeared again recently?
766: &reconlonc();
767: # One more
1.952 raeburn 768: $uhome=&homeserver($uname,$udom,1);
769: if (($uhome eq 'no_host') && $checkdefauth) {
770: if (defined(&domain($udom,'primary'))) {
771: $newhome=&domain($udom,'primary');
772: }
773: if ($newhome ne '') {
774: $uhome = $newhome;
775: }
776: }
1.836 www 777: if ((!$uhome) || ($uhome eq 'no_host')) {
778: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 779: return 'no_host';
780: }
1.1 albertel 781: }
1.952 raeburn 782: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471 albertel 783: if ($answer eq 'authorized') {
1.952 raeburn 784: if ($newhome) {
785: &logthis("User $uname at $udom authorized by $uhome, but needs account");
786: return 'no_account_on_host';
787: } else {
788: &logthis("User $uname at $udom authorized by $uhome");
789: return $uhome;
790: }
1.471 albertel 791: }
792: if ($answer eq 'non_authorized') {
793: &logthis("User $uname at $udom rejected by $uhome");
794: return 'no_host';
1.9 www 795: }
1.471 albertel 796: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 797: return 'no_host';
798: }
799:
800: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 801:
1.599 albertel 802: my %homecache;
1.1 albertel 803: sub homeserver {
1.230 stredwic 804: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 805: my $index="$uname:$udom";
1.426 albertel 806:
1.599 albertel 807: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 808:
809: my %servers = &get_servers($udom,'library');
810: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 811: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 812: exists($badServerCache{$tryserver}));
1.841 albertel 813:
814: my $answer=reply("home:$udom:$uname",$tryserver);
815: if ($answer eq 'found') {
816: delete($badServerCache{$tryserver});
817: return $homecache{$index}=$tryserver;
818: } elsif ($answer eq 'no_host') {
819: $badServerCache{$tryserver}=1;
820: }
1.1 albertel 821: }
822: return 'no_host';
1.70 www 823: }
824:
825: # ------------------------------------- Find the usernames behind a list of IDs
826:
827: sub idget {
828: my ($udom,@ids)=@_;
829: my %returnhash=();
830:
1.841 albertel 831: my %servers = &get_servers($udom,'library');
832: foreach my $tryserver (keys(%servers)) {
833: my $idlist=join('&',@ids);
834: $idlist=~tr/A-Z/a-z/;
835: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
836: my @answer=();
837: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
838: @answer=split(/\&/,$reply);
839: } ;
840: my $i;
841: for ($i=0;$i<=$#ids;$i++) {
842: if ($answer[$i]) {
843: $returnhash{$ids[$i]}=$answer[$i];
844: }
845: }
846: }
1.70 www 847: return %returnhash;
848: }
849:
850: # ------------------------------------- Find the IDs behind a list of usernames
851:
852: sub idrget {
853: my ($udom,@unames)=@_;
854: my %returnhash=();
1.800 albertel 855: foreach my $uname (@unames) {
856: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 857: }
1.70 www 858: return %returnhash;
859: }
860:
861: # ------------------------------- Store away a list of names and associated IDs
862:
863: sub idput {
864: my ($udom,%ids)=@_;
865: my %servers=();
1.800 albertel 866: foreach my $uname (keys(%ids)) {
867: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
868: my $uhom=&homeserver($uname,$udom);
1.70 www 869: if ($uhom ne 'no_host') {
1.800 albertel 870: my $id=&escape($ids{$uname});
1.70 www 871: $id=~tr/A-Z/a-z/;
1.800 albertel 872: my $esc_unam=&escape($uname);
1.70 www 873: if ($servers{$uhom}) {
1.800 albertel 874: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 875: } else {
1.800 albertel 876: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 877: }
878: }
1.191 harris41 879: }
1.800 albertel 880: foreach my $server (keys(%servers)) {
881: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 882: }
1.344 www 883: }
884:
1.806 raeburn 885: # ------------------------------------------- get items from domain db files
886:
887: sub get_dom {
1.860 raeburn 888: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 889: my $items='';
890: foreach my $item (@$storearr) {
891: $items.=&escape($item).'&';
892: }
893: $items=~s/\&$//;
1.860 raeburn 894: if (!$udom) {
895: $udom=$env{'user.domain'};
896: if (defined(&domain($udom,'primary'))) {
897: $uhome=&domain($udom,'primary');
898: } else {
1.874 albertel 899: undef($uhome);
1.860 raeburn 900: }
901: } else {
902: if (!$uhome) {
903: if (defined(&domain($udom,'primary'))) {
904: $uhome=&domain($udom,'primary');
905: }
906: }
907: }
908: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 909: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 910: my %returnhash;
1.875 albertel 911: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 912: return %returnhash;
913: }
1.806 raeburn 914: my @pairs=split(/\&/,$rep);
915: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
916: return @pairs;
917: }
918: my $i=0;
919: foreach my $item (@$storearr) {
920: $returnhash{$item}=&thaw_unescape($pairs[$i]);
921: $i++;
922: }
923: return %returnhash;
924: } else {
1.880 banghart 925: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 926: }
927: }
928:
929: # -------------------------------------------- put items in domain db files
930:
931: sub put_dom {
1.860 raeburn 932: my ($namespace,$storehash,$udom,$uhome)=@_;
933: if (!$udom) {
934: $udom=$env{'user.domain'};
935: if (defined(&domain($udom,'primary'))) {
936: $uhome=&domain($udom,'primary');
937: } else {
1.874 albertel 938: undef($uhome);
1.860 raeburn 939: }
940: } else {
941: if (!$uhome) {
942: if (defined(&domain($udom,'primary'))) {
943: $uhome=&domain($udom,'primary');
944: }
945: }
946: }
947: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 948: my $items='';
949: foreach my $item (keys(%$storehash)) {
950: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
951: }
952: $items=~s/\&$//;
953: return &reply("putdom:$udom:$namespace:$items",$uhome);
954: } else {
1.860 raeburn 955: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 956: }
957: }
958:
1.837 raeburn 959: sub retrieve_inst_usertypes {
960: my ($udom) = @_;
961: my (%returnhash,@order);
1.846 albertel 962: if (defined(&domain($udom,'primary'))) {
963: my $uhome=&domain($udom,'primary');
1.837 raeburn 964: my $rep=&reply("inst_usertypes:$udom",$uhome);
1.960 raeburn 965: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
966: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
967: return (\%returnhash,\@order);
968: }
1.837 raeburn 969: my ($hashitems,$orderitems) = split(/:/,$rep);
970: my @pairs=split(/\&/,$hashitems);
971: foreach my $item (@pairs) {
972: my ($key,$value)=split(/=/,$item,2);
973: $key = &unescape($key);
974: next if ($key =~ /^error: 2 /);
975: $returnhash{$key}=&thaw_unescape($value);
976: }
977: my @esc_order = split(/\&/,$orderitems);
978: foreach my $item (@esc_order) {
979: push(@order,&unescape($item));
980: }
981: } else {
982: &logthis("get_dom failed - no primary domain server for $udom");
983: }
984: return (\%returnhash,\@order);
985: }
986:
1.868 raeburn 987: sub is_domainimage {
988: my ($url) = @_;
989: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
990: if (&domain($1) ne '') {
991: return '1';
992: }
993: }
994: return;
995: }
996:
1.899 raeburn 997: sub inst_directory_query {
998: my ($srch) = @_;
999: my $udom = $srch->{'srchdomain'};
1000: my %results;
1001: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1002: my $outcome;
1.899 raeburn 1003: if ($homeserver ne '') {
1.904 albertel 1004: my $queryid=&reply("querysend:instdirsearch:".
1005: &escape($srch->{'srchby'}).':'.
1006: &escape($srch->{'srchterm'}).':'.
1007: &escape($srch->{'srchtype'}),$homeserver);
1008: my $host=&hostname($homeserver);
1009: if ($queryid !~/^\Q$host\E\_/) {
1010: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1011: return;
1012: }
1013: my $response = &get_query_reply($queryid);
1014: my $maxtries = 5;
1015: my $tries = 1;
1016: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1017: $response = &get_query_reply($queryid);
1018: $tries ++;
1019: }
1020:
1021: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1022: if ($response eq 'unavailable') {
1023: $outcome = $response;
1024: } else {
1025: $outcome = 'ok';
1026: my @matches = split(/\n/,$response);
1027: foreach my $match (@matches) {
1028: my ($key,$value) = split(/=/,$match);
1029: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1030: }
1.899 raeburn 1031: }
1032: }
1033: }
1.909 raeburn 1034: return ($outcome,%results);
1.899 raeburn 1035: }
1036:
1037: sub usersearch {
1038: my ($srch) = @_;
1039: my $dom = $srch->{'srchdomain'};
1040: my %results;
1041: my %libserv = &all_library();
1042: my $query = 'usersearch';
1043: foreach my $tryserver (keys(%libserv)) {
1044: if (&host_domain($tryserver) eq $dom) {
1045: my $host=&hostname($tryserver);
1046: my $queryid=
1.911 raeburn 1047: &reply("querysend:".&escape($query).':'.
1048: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1049: &escape($srch->{'srchtype'}).':'.
1050: &escape($srch->{'srchterm'}),$tryserver);
1051: if ($queryid !~/^\Q$host\E\_/) {
1052: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1053: next;
1.899 raeburn 1054: }
1055: my $reply = &get_query_reply($queryid);
1056: my $maxtries = 1;
1057: my $tries = 1;
1058: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1059: $reply = &get_query_reply($queryid);
1060: $tries ++;
1061: }
1062: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1063: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1064: } else {
1.911 raeburn 1065: my @matches;
1066: if ($reply =~ /\n/) {
1067: @matches = split(/\n/,$reply);
1068: } else {
1069: @matches = split(/\&/,$reply);
1070: }
1.899 raeburn 1071: foreach my $match (@matches) {
1072: my ($uname,$udom,%userhash);
1.911 raeburn 1073: foreach my $entry (split(/:/,$match)) {
1074: my ($key,$value) =
1075: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1076: $userhash{$key} = $value;
1077: if ($key eq 'username') {
1078: $uname = $value;
1079: } elsif ($key eq 'domain') {
1080: $udom = $value;
1.911 raeburn 1081: }
1.899 raeburn 1082: }
1083: $results{$uname.':'.$udom} = \%userhash;
1084: }
1085: }
1086: }
1087: }
1088: return %results;
1089: }
1090:
1.912 raeburn 1091: sub get_instuser {
1092: my ($udom,$uname,$id) = @_;
1093: my $homeserver = &domain($udom,'primary');
1094: my ($outcome,%results);
1095: if ($homeserver ne '') {
1096: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1097: &escape($id).':'.&escape($udom),$homeserver);
1098: my $host=&hostname($homeserver);
1099: if ($queryid !~/^\Q$host\E\_/) {
1100: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1101: return;
1102: }
1103: my $response = &get_query_reply($queryid);
1104: my $maxtries = 5;
1105: my $tries = 1;
1106: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1107: $response = &get_query_reply($queryid);
1108: $tries ++;
1109: }
1110: if (!&error($response) && $response ne 'refused') {
1111: if ($response eq 'unavailable') {
1112: $outcome = $response;
1113: } else {
1114: $outcome = 'ok';
1115: my @matches = split(/\n/,$response);
1116: foreach my $match (@matches) {
1117: my ($key,$value) = split(/=/,$match);
1118: $results{&unescape($key)} = &thaw_unescape($value);
1119: }
1120: }
1121: }
1122: }
1123: my %userinfo;
1124: if (ref($results{$uname}) eq 'HASH') {
1125: %userinfo = %{$results{$uname}};
1126: }
1127: return ($outcome,%userinfo);
1128: }
1129:
1130: sub inst_rulecheck {
1.923 raeburn 1131: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1132: my %returnhash;
1133: if ($udom ne '') {
1134: if (ref($rules) eq 'ARRAY') {
1135: @{$rules} = map {&escape($_);} (@{$rules});
1136: my $rulestr = join(':',@{$rules});
1137: my $homeserver=&domain($udom,'primary');
1138: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1139: my $response;
1140: if ($item eq 'username') {
1141: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1142: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1143: $homeserver));
1.923 raeburn 1144: } elsif ($item eq 'id') {
1145: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1146: ':'.&escape($id).':'.$rulestr,
1147: $homeserver));
1.945 raeburn 1148: } elsif ($item eq 'selfcreate') {
1149: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1150: &escape($udom).':'.&escape($uname).
1151: ':'.$rulestr,$homeserver));
1.923 raeburn 1152: }
1.912 raeburn 1153: if ($response ne 'refused') {
1154: my @pairs=split(/\&/,$response);
1155: foreach my $item (@pairs) {
1156: my ($key,$value)=split(/=/,$item,2);
1157: $key = &unescape($key);
1158: next if ($key =~ /^error: 2 /);
1159: $returnhash{$key}=&thaw_unescape($value);
1160: }
1161: }
1162: }
1163: }
1164: }
1165: return %returnhash;
1166: }
1167:
1168: sub inst_userrules {
1.923 raeburn 1169: my ($udom,$check) = @_;
1.912 raeburn 1170: my (%ruleshash,@ruleorder);
1171: if ($udom ne '') {
1172: my $homeserver=&domain($udom,'primary');
1173: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1174: my $response;
1175: if ($check eq 'id') {
1176: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1177: $homeserver);
1.943 raeburn 1178: } elsif ($check eq 'email') {
1179: $response=&reply('instemailrules:'.&escape($udom),
1180: $homeserver);
1.923 raeburn 1181: } else {
1182: $response=&reply('instuserrules:'.&escape($udom),
1183: $homeserver);
1184: }
1.912 raeburn 1185: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1186: ($response ne 'unknown_cmd') &&
1.912 raeburn 1187: ($response ne 'no_such_host')) {
1188: my ($hashitems,$orderitems) = split(/:/,$response);
1189: my @pairs=split(/\&/,$hashitems);
1190: foreach my $item (@pairs) {
1191: my ($key,$value)=split(/=/,$item,2);
1192: $key = &unescape($key);
1193: next if ($key =~ /^error: 2 /);
1194: $ruleshash{$key}=&thaw_unescape($value);
1195: }
1196: my @esc_order = split(/\&/,$orderitems);
1197: foreach my $item (@esc_order) {
1198: push(@ruleorder,&unescape($item));
1199: }
1200: }
1201: }
1202: }
1203: return (\%ruleshash,\@ruleorder);
1204: }
1205:
1.943 raeburn 1206: # ------------------------- Get Authentication and Language Defaults for Domain
1207:
1208: sub get_domain_defaults {
1209: my ($domain) = @_;
1210: my $cachetime = 60*60*24;
1211: my ($defauthtype,$defautharg,$deflang);
1212: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1213: if (defined($cached)) {
1214: if (ref($result) eq 'HASH') {
1215: return %{$result};
1216: }
1217: }
1218: my %domdefaults;
1219: my %domconfig =
1220: &Apache::lonnet::get_dom('configuration',['defaults'],$domain);
1221: if (ref($domconfig{'defaults'}) eq 'HASH') {
1222: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1223: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1224: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1225: } else {
1226: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1227: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1228: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1229: }
1230: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1231: $cachetime);
1232: return %domdefaults;
1233: }
1234:
1.344 www 1235: # --------------------------------------------------- Assign a key to a student
1236:
1237: sub assign_access_key {
1.364 www 1238: #
1239: # a valid key looks like uname:udom#comments
1240: # comments are being appended
1241: #
1.498 www 1242: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1243: $kdom=
1.620 albertel 1244: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1245: $knum=
1.620 albertel 1246: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1247: $cdom=
1.620 albertel 1248: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1249: $cnum=
1.620 albertel 1250: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1251: $udom=$env{'user.name'} unless (defined($udom));
1252: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1253: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1254: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1255: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1256: # assigned to this person
1257: # - this should not happen,
1.345 www 1258: # unless something went wrong
1259: # the first time around
1260: # ready to assign
1.364 www 1261: $logentry=$1.'; '.$logentry;
1.496 www 1262: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1263: $kdom,$knum) eq 'ok') {
1.345 www 1264: # key now belongs to user
1.346 www 1265: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1266: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1267: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1268: return 'ok';
1269: } else {
1270: return
1271: 'error: Count not permanently assign key, will need to be re-entered later.';
1272: }
1273: } else {
1274: return 'error: Could not assign key, try again later.';
1275: }
1.364 www 1276: } elsif (!$existing{$ckey}) {
1.345 www 1277: # the key does not exist
1278: return 'error: The key does not exist';
1279: } else {
1280: # the key is somebody else's
1281: return 'error: The key is already in use';
1282: }
1.344 www 1283: }
1284:
1.364 www 1285: # ------------------------------------------ put an additional comment on a key
1286:
1287: sub comment_access_key {
1288: #
1289: # a valid key looks like uname:udom#comments
1290: # comments are being appended
1291: #
1292: my ($ckey,$cdom,$cnum,$logentry)=@_;
1293: $cdom=
1.620 albertel 1294: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1295: $cnum=
1.620 albertel 1296: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1297: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1298: if ($existing{$ckey}) {
1299: $existing{$ckey}.='; '.$logentry;
1300: # ready to assign
1.367 www 1301: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1302: $cdom,$cnum) eq 'ok') {
1303: return 'ok';
1304: } else {
1305: return 'error: Count not store comment.';
1306: }
1307: } else {
1308: # the key does not exist
1309: return 'error: The key does not exist';
1310: }
1311: }
1312:
1.344 www 1313: # ------------------------------------------------------ Generate a set of keys
1314:
1315: sub generate_access_keys {
1.364 www 1316: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1317: $cdom=
1.620 albertel 1318: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1319: $cnum=
1.620 albertel 1320: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1321: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1322: unless (($cdom) && ($cnum)) { return 0; }
1323: if ($number>10000) { return 0; }
1324: sleep(2); # make sure don't get same seed twice
1325: srand(time()^($$+($$<<15))); # from "Programming Perl"
1326: my $total=0;
1327: for (my $i=1;$i<=$number;$i++) {
1328: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1329: sprintf("%lx",int(100000*rand)).'-'.
1330: sprintf("%lx",int(100000*rand));
1331: $newkey=~s/1/g/g; # folks mix up 1 and l
1332: $newkey=~s/0/h/g; # and also 0 and O
1333: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1334: if ($existing{$newkey}) {
1335: $i--;
1336: } else {
1.364 www 1337: if (&put('accesskeys',
1338: { $newkey => '# generated '.localtime().
1.620 albertel 1339: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1340: '; '.$logentry },
1341: $cdom,$cnum) eq 'ok') {
1.344 www 1342: $total++;
1343: }
1344: }
1345: }
1.620 albertel 1346: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1347: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1348: return $total;
1349: }
1350:
1351: # ------------------------------------------------------- Validate an accesskey
1352:
1353: sub validate_access_key {
1354: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1355: $cdom=
1.620 albertel 1356: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1357: $cnum=
1.620 albertel 1358: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1359: $udom=$env{'user.domain'} unless (defined($udom));
1360: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1361: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1362: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1363: }
1364:
1365: # ------------------------------------- Find the section of student in a course
1.652 albertel 1366: sub devalidate_getsection_cache {
1367: my ($udom,$unam,$courseid)=@_;
1368: my $hashid="$udom:$unam:$courseid";
1369: &devalidate_cache_new('getsection',$hashid);
1370: }
1.298 matthew 1371:
1.815 albertel 1372: sub courseid_to_courseurl {
1373: my ($courseid) = @_;
1374: #already url style courseid
1375: return $courseid if ($courseid =~ m{^/});
1376:
1377: if (exists($env{'course.'.$courseid.'.num'})) {
1378: my $cnum = $env{'course.'.$courseid.'.num'};
1379: my $cdom = $env{'course.'.$courseid.'.domain'};
1380: return "/$cdom/$cnum";
1381: }
1382:
1383: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1384: if (exists($courseinfo{'num'})) {
1385: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1386: }
1387:
1388: return undef;
1389: }
1390:
1.298 matthew 1391: sub getsection {
1392: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1393: my $cachetime=1800;
1.551 albertel 1394:
1395: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1396: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1397: if (defined($cached)) { return $result; }
1398:
1.298 matthew 1399: my %Pending;
1400: my %Expired;
1401: #
1402: # Each role can either have not started yet (pending), be active,
1403: # or have expired.
1404: #
1405: # If there is an active role, we are done.
1406: #
1407: # If there is more than one role which has not started yet,
1408: # choose the one which will start sooner
1409: # If there is one role which has not started yet, return it.
1410: #
1411: # If there is more than one expired role, choose the one which ended last.
1412: # If there is a role which has expired, return it.
1413: #
1.815 albertel 1414: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1415: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1416: foreach my $key (keys(%roleshash)) {
1.479 albertel 1417: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1418: my $section=$1;
1419: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1420: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1421: my $now=time;
1.548 albertel 1422: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1423: $Expired{$end}=$section;
1424: next;
1425: }
1.548 albertel 1426: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1427: $Pending{$start}=$section;
1428: next;
1429: }
1.599 albertel 1430: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1431: }
1432: #
1433: # Presumedly there will be few matching roles from the above
1434: # loop and the sorting time will be negligible.
1435: if (scalar(keys(%Pending))) {
1436: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1437: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1438: }
1439: if (scalar(keys(%Expired))) {
1440: my @sorted = sort {$a <=> $b} keys(%Expired);
1441: my $time = pop(@sorted);
1.599 albertel 1442: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1443: }
1.599 albertel 1444: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1445: }
1.70 www 1446:
1.599 albertel 1447: sub save_cache {
1448: &purge_remembered();
1.722 albertel 1449: #&Apache::loncommon::validate_page();
1.620 albertel 1450: undef(%env);
1.780 albertel 1451: undef($env_loaded);
1.599 albertel 1452: }
1.452 albertel 1453:
1.599 albertel 1454: my $to_remember=-1;
1455: my %remembered;
1456: my %accessed;
1457: my $kicks=0;
1458: my $hits=0;
1.849 albertel 1459: sub make_key {
1460: my ($name,$id) = @_;
1.872 albertel 1461: if (length($id) > 65
1462: && length(&escape($id)) > 200) {
1463: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1464: }
1.849 albertel 1465: return &escape($name.':'.$id);
1466: }
1467:
1.599 albertel 1468: sub devalidate_cache_new {
1469: my ($name,$id,$debug) = @_;
1470: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1471: $id=&make_key($name,$id);
1.599 albertel 1472: $memcache->delete($id);
1473: delete($remembered{$id});
1474: delete($accessed{$id});
1475: }
1476:
1477: sub is_cached_new {
1478: my ($name,$id,$debug) = @_;
1.849 albertel 1479: $id=&make_key($name,$id);
1.599 albertel 1480: if (exists($remembered{$id})) {
1481: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1482: $accessed{$id}=[&gettimeofday()];
1483: $hits++;
1484: return ($remembered{$id},1);
1485: }
1486: my $value = $memcache->get($id);
1487: if (!(defined($value))) {
1488: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1489: return (undef,undef);
1.416 albertel 1490: }
1.599 albertel 1491: if ($value eq '__undef__') {
1492: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1493: $value=undef;
1494: }
1495: &make_room($id,$value,$debug);
1496: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1497: return ($value,1);
1498: }
1499:
1500: sub do_cache_new {
1501: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1502: $id=&make_key($name,$id);
1.599 albertel 1503: my $setvalue=$value;
1504: if (!defined($setvalue)) {
1505: $setvalue='__undef__';
1506: }
1.623 albertel 1507: if (!defined($time) ) {
1508: $time=600;
1509: }
1.599 albertel 1510: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1511: my $result = $memcache->set($id,$setvalue,$time);
1512: if (! $result) {
1.872 albertel 1513: &logthis("caching of id -> $id failed");
1.910 albertel 1514: $memcache->disconnect_all();
1.872 albertel 1515: }
1.600 albertel 1516: # need to make a copy of $value
1.919 albertel 1517: &make_room($id,$value,$debug);
1.599 albertel 1518: return $value;
1519: }
1520:
1521: sub make_room {
1522: my ($id,$value,$debug)=@_;
1.919 albertel 1523:
1524: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1525: : $value;
1.599 albertel 1526: if ($to_remember<0) { return; }
1527: $accessed{$id}=[&gettimeofday()];
1528: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1529: my $to_kick;
1530: my $max_time=0;
1531: foreach my $other (keys(%accessed)) {
1532: if (&tv_interval($accessed{$other}) > $max_time) {
1533: $to_kick=$other;
1534: $max_time=&tv_interval($accessed{$other});
1535: }
1536: }
1537: delete($remembered{$to_kick});
1538: delete($accessed{$to_kick});
1539: $kicks++;
1540: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1541: return;
1542: }
1543:
1.599 albertel 1544: sub purge_remembered {
1.604 albertel 1545: #&logthis("Tossing ".scalar(keys(%remembered)));
1546: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1547: undef(%remembered);
1548: undef(%accessed);
1.428 albertel 1549: }
1.70 www 1550: # ------------------------------------- Read an entry from a user's environment
1551:
1552: sub userenvironment {
1553: my ($udom,$unam,@what)=@_;
1554: my %returnhash=();
1555: my @answer=split(/\&/,
1556: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
1557: &homeserver($unam,$udom)));
1558: my $i;
1559: for ($i=0;$i<=$#what;$i++) {
1560: $returnhash{$what[$i]}=&unescape($answer[$i]);
1561: }
1562: return %returnhash;
1.1 albertel 1563: }
1564:
1.617 albertel 1565: # ---------------------------------------------------------- Get a studentphoto
1566: sub studentphoto {
1567: my ($udom,$unam,$ext) = @_;
1568: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1569: if (defined($env{'request.course.id'})) {
1.708 raeburn 1570: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1571: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1572: return(&retrievestudentphoto($udom,$unam,$ext));
1573: } else {
1574: my ($result,$perm_reqd)=
1.707 albertel 1575: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1576: if ($result eq 'ok') {
1577: if (!($perm_reqd eq 'yes')) {
1578: return(&retrievestudentphoto($udom,$unam,$ext));
1579: }
1580: }
1581: }
1582: }
1583: } else {
1584: my ($result,$perm_reqd) =
1.707 albertel 1585: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1586: if ($result eq 'ok') {
1587: if (!($perm_reqd eq 'yes')) {
1588: return(&retrievestudentphoto($udom,$unam,$ext));
1589: }
1590: }
1591: }
1592: return '/adm/lonKaputt/lonlogo_broken.gif';
1593: }
1594:
1595: sub retrievestudentphoto {
1596: my ($udom,$unam,$ext,$type) = @_;
1597: my $home=&Apache::lonnet::homeserver($unam,$udom);
1598: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1599: if ($ret eq 'ok') {
1600: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1601: if ($type eq 'thumbnail') {
1602: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1603: }
1604: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1605: return $tokenurl;
1606: } else {
1607: if ($type eq 'thumbnail') {
1608: return '/adm/lonKaputt/genericstudent_tn.gif';
1609: } else {
1610: return '/adm/lonKaputt/lonlogo_broken.gif';
1611: }
1.617 albertel 1612: }
1613: }
1614:
1.263 www 1615: # -------------------------------------------------------------------- New chat
1616:
1617: sub chatsend {
1.724 raeburn 1618: my ($newentry,$anon,$group)=@_;
1.620 albertel 1619: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1620: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1621: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1622: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1623: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1624: &escape($newentry)).':'.$group,$chome);
1.292 www 1625: }
1626:
1627: # ------------------------------------------ Find current version of a resource
1628:
1629: sub getversion {
1630: my $fname=&clutter(shift);
1631: unless ($fname=~/^\/res\//) { return -1; }
1632: return ¤tversion(&filelocation('',$fname));
1633: }
1634:
1635: sub currentversion {
1636: my $fname=shift;
1.599 albertel 1637: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1638: if (defined($cached)) { return $result; }
1.292 www 1639: my $author=$fname;
1640: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1641: my ($udom,$uname)=split(/\//,$author);
1642: my $home=homeserver($uname,$udom);
1643: if ($home eq 'no_host') {
1644: return -1;
1645: }
1646: my $answer=reply("currentversion:$fname",$home);
1647: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1648: return -1;
1649: }
1.599 albertel 1650: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1651: }
1652:
1.1 albertel 1653: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1654:
1.1 albertel 1655: sub subscribe {
1656: my $fname=shift;
1.761 raeburn 1657: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1658: $fname=~s/[\n\r]//g;
1.1 albertel 1659: my $author=$fname;
1660: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1661: my ($udom,$uname)=split(/\//,$author);
1662: my $home=homeserver($uname,$udom);
1.335 albertel 1663: if ($home eq 'no_host') {
1664: return 'not_found';
1.1 albertel 1665: }
1666: my $answer=reply("sub:$fname",$home);
1.64 www 1667: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1668: $answer.=' by '.$home;
1669: }
1.1 albertel 1670: return $answer;
1671: }
1672:
1.8 www 1673: # -------------------------------------------------------------- Replicate file
1674:
1675: sub repcopy {
1676: my $filename=shift;
1.23 www 1677: $filename=~s/\/+/\//g;
1.607 raeburn 1678: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1679: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1680: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1681: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1682: return &repcopy_userfile($filename);
1683: }
1.532 albertel 1684: $filename=~s/[\n\r]//g;
1.8 www 1685: my $transname="$filename.in.transfer";
1.828 www 1686: # FIXME: this should flock
1.607 raeburn 1687: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1688: my $remoteurl=subscribe($filename);
1.64 www 1689: if ($remoteurl =~ /^con_lost by/) {
1690: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1691: return 'unavailable';
1.8 www 1692: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1693: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1694: return 'not_found';
1.64 www 1695: } elsif ($remoteurl =~ /^rejected by/) {
1696: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1697: return 'forbidden';
1.20 www 1698: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1699: return 'ok';
1.8 www 1700: } else {
1.290 www 1701: my $author=$filename;
1702: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1703: my ($udom,$uname)=split(/\//,$author);
1704: my $home=homeserver($uname,$udom);
1705: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1706: my @parts=split(/\//,$filename);
1707: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1708: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1709: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1710: return 'bad_request';
1.8 www 1711: }
1712: my $count;
1713: for ($count=5;$count<$#parts;$count++) {
1714: $path.="/$parts[$count]";
1715: if ((-e $path)!=1) {
1716: mkdir($path,0777);
1717: }
1718: }
1719: my $ua=new LWP::UserAgent;
1720: my $request=new HTTP::Request('GET',"$remoteurl");
1721: my $response=$ua->request($request,$transname);
1722: if ($response->is_error()) {
1723: unlink($transname);
1724: my $message=$response->status_line;
1.672 albertel 1725: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1726: ." LWP get: $message: $filename</font>");
1.607 raeburn 1727: return 'unavailable';
1.8 www 1728: } else {
1.16 www 1729: if ($remoteurl!~/\.meta$/) {
1730: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1731: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1732: if ($mresponse->is_error()) {
1733: unlink($filename.'.meta');
1734: &logthis(
1.672 albertel 1735: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1736: }
1737: }
1.8 www 1738: rename($transname,$filename);
1.607 raeburn 1739: return 'ok';
1.8 www 1740: }
1.290 www 1741: }
1.8 www 1742: }
1.330 www 1743: }
1744:
1745: # ------------------------------------------------ Get server side include body
1746: sub ssi_body {
1.381 albertel 1747: my ($filelink,%form)=@_;
1.606 matthew 1748: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1749: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1750: }
1.953 www 1751: my $output='';
1752: my $response;
1753: if ($filelink=~/^http\:/) {
1.954 raeburn 1754: ($output,$response)=&externalssi($filelink);
1.953 www 1755: } else {
1756: ($output,$response)=&ssi($filelink,%form);
1757: }
1.778 albertel 1758: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1759: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 1760: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 1761: if (wantarray) {
1762: return ($output, $response);
1763: } else {
1764: return $output;
1765: }
1.8 www 1766: }
1767:
1.15 www 1768: # --------------------------------------------------------- Server Side Include
1769:
1.782 albertel 1770: sub absolute_url {
1771: my ($host_name) = @_;
1772: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1773: if ($host_name eq '') {
1774: $host_name = $ENV{'SERVER_NAME'};
1775: }
1776: return $protocol.$host_name;
1777: }
1778:
1.942 foxr 1779: #
1780: # Server side include.
1781: # Parameters:
1782: # fn Possibly encrypted resource name/id.
1783: # form Hash that describes how the rendering should be done
1784: # and other things.
1.944 foxr 1785: # Returns:
1.950 raeburn 1786: # Scalar context: The content of the response.
1787: # Array context: 2 element list of the content and the full response object.
1.942 foxr 1788: #
1.15 www 1789: sub ssi {
1790:
1.944 foxr 1791: my ($fn,%form)=@_;
1.15 www 1792: my $ua=new LWP::UserAgent;
1.23 www 1793: my $request;
1.711 albertel 1794:
1795: $form{'no_update_last_known'}=1;
1.895 albertel 1796: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 1797: if (%form) {
1.782 albertel 1798: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201 albertel 1799: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23 www 1800: } else {
1.782 albertel 1801: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1802: }
1803:
1.15 www 1804: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1805: my $response=$ua->request($request);
1806:
1.944 foxr 1807: if (wantarray) {
1808: return ($response->content, $response);
1809: } else {
1810: return $response->content;
1.942 foxr 1811: }
1.324 www 1812: }
1813:
1814: sub externalssi {
1815: my ($url)=@_;
1816: my $ua=new LWP::UserAgent;
1817: my $request=new HTTP::Request('GET',$url);
1818: my $response=$ua->request($request);
1.954 raeburn 1819: if (wantarray) {
1820: return ($response->content, $response);
1821: } else {
1822: return $response->content;
1823: }
1.15 www 1824: }
1.254 www 1825:
1.492 albertel 1826: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1827:
1828: sub allowuploaded {
1829: my ($srcurl,$url)=@_;
1830: $url=&clutter(&declutter($url));
1831: my $dir=$url;
1832: $dir=~s/\/[^\/]+$//;
1833: my %httpref=();
1834: my $httpurl=&hreflocation('',$url);
1835: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 1836: &Apache::lonnet::appenv(\%httpref);
1.254 www 1837: }
1.477 raeburn 1838:
1.478 albertel 1839: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1840: # input: action, courseID, current domain, intended
1.637 raeburn 1841: # path to file, source of file, instruction to parse file for objects,
1842: # ref to hash for embedded objects,
1843: # ref to hash for codebase of java objects.
1844: #
1.485 raeburn 1845: # output: url to file (if action was uploaddoc),
1846: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 1847: #
1.478 albertel 1848: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1849: # course.
1.477 raeburn 1850: #
1.478 albertel 1851: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1852: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1853: # course's home server.
1.477 raeburn 1854: #
1.478 albertel 1855: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1856: # be copied from $source (current location) to
1857: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1858: # and will then be copied to
1859: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1860: # course's home server.
1.485 raeburn 1861: #
1.481 raeburn 1862: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 1863: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 1864: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1865: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1866: # in course's home server.
1.637 raeburn 1867: #
1.477 raeburn 1868:
1869: sub process_coursefile {
1.638 albertel 1870: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 1871: my $fetchresult;
1.638 albertel 1872: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 1873: if ($action eq 'propagate') {
1.638 albertel 1874: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1875: $home);
1.481 raeburn 1876: } else {
1.477 raeburn 1877: my $fpath = '';
1878: my $fname = $file;
1.478 albertel 1879: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 1880: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 1881: my $filepath = &build_filepath($fpath);
1.481 raeburn 1882: if ($action eq 'copy') {
1883: if ($source eq '') {
1884: $fetchresult = 'no source file';
1885: return $fetchresult;
1886: } else {
1887: my $destination = $filepath.'/'.$fname;
1888: rename($source,$destination);
1889: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1890: $home);
1.481 raeburn 1891: }
1892: } elsif ($action eq 'uploaddoc') {
1893: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 1894: print $fh $env{'form.'.$source};
1.481 raeburn 1895: close($fh);
1.637 raeburn 1896: if ($parser eq 'parse') {
1.961 raeburn 1897: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637 raeburn 1898: unless ($parse_result eq 'ok') {
1899: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1900: }
1901: }
1.477 raeburn 1902: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1903: $home);
1.481 raeburn 1904: if ($fetchresult eq 'ok') {
1905: return '/uploaded/'.$fpath.'/'.$fname;
1906: } else {
1907: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1908: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 1909: return '/adm/notfound.html';
1910: }
1.477 raeburn 1911: }
1912: }
1.485 raeburn 1913: unless ( $fetchresult eq 'ok') {
1.477 raeburn 1914: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1915: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 1916: }
1917: return $fetchresult;
1918: }
1919:
1.637 raeburn 1920: sub build_filepath {
1921: my ($fpath) = @_;
1922: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1923: unless ($fpath eq '') {
1924: my @parts=split('/',$fpath);
1925: foreach my $part (@parts) {
1926: $filepath.= '/'.$part;
1927: if ((-e $filepath)!=1) {
1928: mkdir($filepath,0777);
1929: }
1930: }
1931: }
1932: return $filepath;
1933: }
1934:
1935: sub store_edited_file {
1.638 albertel 1936: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 1937: my $file = $primary_url;
1938: $file =~ s#^/uploaded/$docudom/$docuname/##;
1939: my $fpath = '';
1940: my $fname = $file;
1941: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1942: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1943: my $filepath = &build_filepath($fpath);
1944: open(my $fh,'>'.$filepath.'/'.$fname);
1945: print $fh $content;
1946: close($fh);
1.638 albertel 1947: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 1948: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1949: $home);
1.637 raeburn 1950: if ($$fetchresult eq 'ok') {
1951: return '/uploaded/'.$fpath.'/'.$fname;
1952: } else {
1.638 albertel 1953: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1954: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 1955: return '/adm/notfound.html';
1956: }
1957: }
1958:
1.531 albertel 1959: sub clean_filename {
1.831 albertel 1960: my ($fname,$args)=@_;
1.315 www 1961: # Replace Windows backslashes by forward slashes
1.257 www 1962: $fname=~s/\\/\//g;
1.831 albertel 1963: if (!$args->{'keep_path'}) {
1964: # Get rid of everything but the actual filename
1965: $fname=~s/^.*\/([^\/]+)$/$1/;
1966: }
1.315 www 1967: # Replace spaces by underscores
1968: $fname=~s/\s+/\_/g;
1969: # Replace all other weird characters by nothing
1.831 albertel 1970: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 1971: # Replace all .\d. sequences with _\d. so they no longer look like version
1972: # numbers
1973: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 1974: return $fname;
1975: }
1976:
1.608 albertel 1977: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 1978: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 1979: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 1980: # $coursedoc - if true up to the current course
1981: # if false
1982: # $subdir - directory in userfile to store the file into
1.858 raeburn 1983: # $parser - instruction to parse file for objects ($parser = parse)
1984: # $allfiles - reference to hash for embedded objects
1985: # $codebase - reference to hash for codebase of java objects
1986: # $desuname - username for permanent storage of uploaded file
1987: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 1988: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
1989: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858 raeburn 1990: #
1.686 albertel 1991: # output: url of file in userspace, or error: <message>
1992: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 1993:
1994:
1.531 albertel 1995: sub userfileupload {
1.860 raeburn 1996: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1997: $destudom,$thumbwidth,$thumbheight)=@_;
1.531 albertel 1998: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 1999: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2000: $fname=&clean_filename($fname);
1.315 www 2001: # See if there is anything left
1.257 www 2002: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2003: chop($env{'form.'.$formname});
1.523 raeburn 2004: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2005: my $now = time;
2006: my $filepath = 'tmp/helprequests/'.$now;
2007: my @parts=split(/\//,$filepath);
2008: my $fullpath = $perlvar{'lonDaemons'};
2009: for (my $i=0;$i<@parts;$i++) {
2010: $fullpath .= '/'.$parts[$i];
2011: if ((-e $fullpath)!=1) {
2012: mkdir($fullpath,0777);
2013: }
2014: }
2015: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2016: print $fh $env{'form.'.$formname};
1.523 raeburn 2017: close($fh);
1.741 raeburn 2018: return $fullpath.'/'.$fname;
2019: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2020: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2021: '_'.$env{'user.domain'}.'/pending';
2022: my @parts=split(/\//,$filepath);
2023: my $fullpath = $perlvar{'lonDaemons'};
2024: for (my $i=0;$i<@parts;$i++) {
2025: $fullpath .= '/'.$parts[$i];
2026: if ((-e $fullpath)!=1) {
2027: mkdir($fullpath,0777);
2028: }
2029: }
2030: open(my $fh,'>'.$fullpath.'/'.$fname);
2031: print $fh $env{'form.'.$formname};
2032: close($fh);
2033: return $fullpath.'/'.$fname;
1.523 raeburn 2034: }
1.719 banghart 2035:
1.258 www 2036: # Create the directory if not present
1.493 albertel 2037: $fname="$subdir/$fname";
1.259 www 2038: if ($coursedoc) {
1.638 albertel 2039: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2040: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2041: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2042: return &finishuserfileupload($docuname,$docudom,
2043: $formname,$fname,$parser,$allfiles,
1.860 raeburn 2044: $codebase,$thumbwidth,$thumbheight);
1.481 raeburn 2045: } else {
1.620 albertel 2046: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2047: return &process_coursefile('uploaddoc',$docuname,$docudom,
2048: $fname,$formname,$parser,
2049: $allfiles,$codebase);
1.481 raeburn 2050: }
1.719 banghart 2051: } elsif (defined($destuname)) {
2052: my $docuname=$destuname;
2053: my $docudom=$destudom;
1.860 raeburn 2054: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2055: $parser,$allfiles,$codebase,
2056: $thumbwidth,$thumbheight);
1.719 banghart 2057:
1.259 www 2058: } else {
1.638 albertel 2059: my $docuname=$env{'user.name'};
2060: my $docudom=$env{'user.domain'};
1.714 raeburn 2061: if (exists($env{'form.group'})) {
2062: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2063: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2064: }
1.860 raeburn 2065: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2066: $parser,$allfiles,$codebase,
2067: $thumbwidth,$thumbheight);
1.259 www 2068: }
1.271 www 2069: }
2070:
2071: sub finishuserfileupload {
1.860 raeburn 2072: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2073: $thumbwidth,$thumbheight) = @_;
1.477 raeburn 2074: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2075: my $filepath=$perlvar{'lonDocRoot'};
1.860 raeburn 2076: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2077: $file=$fname;
2078: if ($fname=~m|/|) {
2079: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2080: $path.=$fnamepath.'/';
2081: }
1.259 www 2082: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2083: my $count;
2084: for ($count=4;$count<=$#parts;$count++) {
2085: $filepath.="/$parts[$count]";
2086: if ((-e $filepath)!=1) {
2087: mkdir($filepath,0777);
2088: }
2089: }
2090: # Save the file
2091: {
1.701 albertel 2092: if (!open(FH,'>'.$filepath.'/'.$file)) {
2093: &logthis('Failed to create '.$filepath.'/'.$file);
2094: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2095: return '/adm/notfound.html';
2096: }
2097: if (!print FH ($env{'form.'.$formname})) {
2098: &logthis('Failed to write to '.$filepath.'/'.$file);
2099: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2100: return '/adm/notfound.html';
2101: }
1.570 albertel 2102: close(FH);
1.258 www 2103: }
1.637 raeburn 2104: if ($parser eq 'parse') {
1.961 raeburn 2105: my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638 albertel 2106: $codebase);
1.637 raeburn 2107: unless ($parse_result eq 'ok') {
1.638 albertel 2108: &logthis('Failed to parse '.$filepath.$file.
2109: ' for embedded media: '.$parse_result);
1.637 raeburn 2110: }
2111: }
1.860 raeburn 2112: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2113: my $input = $filepath.'/'.$file;
2114: my $output = $filepath.'/'.'tn-'.$file;
2115: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2116: system("convert -sample $thumbsize $input $output");
2117: if (-e $filepath.'/'.'tn-'.$file) {
2118: $fetchthumb = 1;
2119: }
2120: }
1.858 raeburn 2121:
1.259 www 2122: # Notify homeserver to grep it
2123: #
1.638 albertel 2124: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2125: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2126: if ($fetchresult eq 'ok') {
1.860 raeburn 2127: if ($fetchthumb) {
2128: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2129: if ($thumbresult ne 'ok') {
2130: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2131: $docuhome.': '.$thumbresult);
2132: }
2133: }
1.259 www 2134: #
1.258 www 2135: # Return the URL to it
1.494 albertel 2136: return '/uploaded/'.$path.$file;
1.263 www 2137: } else {
1.494 albertel 2138: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2139: ': '.$fetchresult);
1.263 www 2140: return '/adm/notfound.html';
1.858 raeburn 2141: }
1.493 albertel 2142: }
2143:
1.637 raeburn 2144: sub extract_embedded_items {
1.961 raeburn 2145: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2146: my @state = ();
2147: my %javafiles = (
2148: codebase => '',
2149: code => '',
2150: archive => ''
2151: );
2152: my %mediafiles = (
2153: src => '',
2154: movie => '',
2155: );
1.648 raeburn 2156: my $p;
2157: if ($content) {
2158: $p = HTML::LCParser->new($content);
2159: } else {
1.961 raeburn 2160: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2161: }
1.641 albertel 2162: while (my $t=$p->get_token()) {
1.640 albertel 2163: if ($t->[0] eq 'S') {
2164: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2165: push(@state, $tagname);
1.648 raeburn 2166: if (lc($tagname) eq 'allow') {
2167: &add_filetype($allfiles,$attr->{'src'},'src');
2168: }
1.640 albertel 2169: if (lc($tagname) eq 'img') {
2170: &add_filetype($allfiles,$attr->{'src'},'src');
2171: }
1.886 albertel 2172: if (lc($tagname) eq 'a') {
2173: &add_filetype($allfiles,$attr->{'href'},'href');
2174: }
1.645 raeburn 2175: if (lc($tagname) eq 'script') {
2176: if ($attr->{'archive'} =~ /\.jar$/i) {
2177: &add_filetype($allfiles,$attr->{'archive'},'archive');
2178: } else {
2179: &add_filetype($allfiles,$attr->{'src'},'src');
2180: }
2181: }
2182: if (lc($tagname) eq 'link') {
2183: if (lc($attr->{'rel'}) eq 'stylesheet') {
2184: &add_filetype($allfiles,$attr->{'href'},'href');
2185: }
2186: }
1.640 albertel 2187: if (lc($tagname) eq 'object' ||
2188: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2189: foreach my $item (keys(%javafiles)) {
2190: $javafiles{$item} = '';
2191: }
2192: }
2193: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2194: my $name = lc($attr->{'name'});
2195: foreach my $item (keys(%javafiles)) {
2196: if ($name eq $item) {
2197: $javafiles{$item} = $attr->{'value'};
2198: last;
2199: }
2200: }
2201: foreach my $item (keys(%mediafiles)) {
2202: if ($name eq $item) {
2203: &add_filetype($allfiles, $attr->{'value'}, 'value');
2204: last;
2205: }
2206: }
2207: }
2208: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2209: foreach my $item (keys(%javafiles)) {
2210: if ($attr->{$item}) {
2211: $javafiles{$item} = $attr->{$item};
2212: last;
2213: }
2214: }
2215: foreach my $item (keys(%mediafiles)) {
2216: if ($attr->{$item}) {
2217: &add_filetype($allfiles,$attr->{$item},$item);
2218: last;
2219: }
2220: }
2221: }
2222: } elsif ($t->[0] eq 'E') {
2223: my ($tagname) = ($t->[1]);
2224: if ($javafiles{'codebase'} ne '') {
2225: $javafiles{'codebase'} .= '/';
2226: }
2227: if (lc($tagname) eq 'applet' ||
2228: lc($tagname) eq 'object' ||
2229: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2230: ) {
2231: foreach my $item (keys(%javafiles)) {
2232: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2233: my $file=$javafiles{'codebase'}.$javafiles{$item};
2234: &add_filetype($allfiles,$file,$item);
2235: }
2236: }
2237: }
2238: pop @state;
2239: }
2240: }
1.637 raeburn 2241: return 'ok';
2242: }
2243:
1.639 albertel 2244: sub add_filetype {
2245: my ($allfiles,$file,$type)=@_;
2246: if (exists($allfiles->{$file})) {
2247: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2248: push(@{$allfiles->{$file}}, &escape($type));
2249: }
2250: } else {
2251: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2252: }
2253: }
2254:
1.493 albertel 2255: sub removeuploadedurl {
2256: my ($url)=@_;
2257: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2258: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2259: }
2260:
2261: sub removeuserfile {
2262: my ($docuname,$docudom,$fname)=@_;
2263: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2264: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
2265: if ($result eq 'ok') {
2266: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2267: my $metafile = $fname.'.meta';
2268: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2269: my $url = "/uploaded/$docudom/$docuname/$fname";
2270: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2271: my $sqlresult =
1.823 albertel 2272: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2273: 'portfolio_metadata',$group,
2274: 'delete');
1.798 raeburn 2275: }
2276: }
2277: return $result;
1.257 www 2278: }
1.15 www 2279:
1.530 albertel 2280: sub mkdiruserfile {
2281: my ($docuname,$docudom,$dir)=@_;
2282: my $home=&homeserver($docuname,$docudom);
2283: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2284: }
2285:
1.531 albertel 2286: sub renameuserfile {
2287: my ($docuname,$docudom,$old,$new)=@_;
2288: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2289: my $result = &reply("renameuserfile:$docudom:$docuname:".
2290: &escape("$old").':'.&escape("$new"),$home);
2291: if ($result eq 'ok') {
2292: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2293: my $oldmeta = $old.'.meta';
2294: my $newmeta = $new.'.meta';
2295: my $metaresult =
2296: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2297: my $url = "/uploaded/$docudom/$docuname/$old";
2298: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2299: my $sqlresult =
1.823 albertel 2300: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2301: 'portfolio_metadata',$group,
2302: 'delete');
1.798 raeburn 2303: }
2304: }
2305: return $result;
1.531 albertel 2306: }
2307:
1.14 www 2308: # ------------------------------------------------------------------------- Log
2309:
2310: sub log {
2311: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2312: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2313: }
2314:
2315: # ------------------------------------------------------------------ Course Log
1.352 www 2316: #
2317: # This routine flushes several buffers of non-mission-critical nature
2318: #
1.157 www 2319:
2320: sub flushcourselogs {
1.352 www 2321: &logthis('Flushing log buffers');
2322: #
2323: # course logs
2324: # This is a log of all transactions in a course, which can be used
2325: # for data mining purposes
2326: #
2327: # It also collects the courseid database, which lists last transaction
2328: # times and course titles for all courseids
2329: #
2330: my %courseidbuffer=();
1.921 raeburn 2331: foreach my $crsid (keys(%courselogs)) {
1.352 www 2332: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2333: &escape($courselogs{$crsid}),
2334: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2335: delete $courselogs{$crsid};
2336: } else {
2337: &logthis('Failed to flush log buffer for '.$crsid);
2338: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2339: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2340: " exceeded maximum size, deleting.</font>");
2341: delete $courselogs{$crsid};
2342: }
1.352 www 2343: }
1.920 raeburn 2344: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2345: 'description' => $coursedescrbuf{$crsid},
2346: 'inst_code' => $courseinstcodebuf{$crsid},
2347: 'type' => $coursetypebuf{$crsid},
2348: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2349: };
1.191 harris41 2350: }
1.352 www 2351: #
2352: # Write course id database (reverse lookup) to homeserver of courses
2353: # Is used in pickcourse
2354: #
1.840 albertel 2355: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2356: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2357: $courseidbuffer{$crs_home},
2358: $crs_home,'timeonly');
1.352 www 2359: }
2360: #
2361: # File accesses
2362: # Writes to the dynamic metadata of resources to get hit counts, etc.
2363: #
1.449 matthew 2364: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2365: if ($entry =~ /___count$/) {
2366: my ($dom,$name);
1.807 albertel 2367: ($dom,$name,undef)=
1.811 albertel 2368: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2369: if (! defined($dom) || $dom eq '' ||
2370: ! defined($name) || $name eq '') {
1.620 albertel 2371: my $cid = $env{'request.course.id'};
2372: $dom = $env{'request.'.$cid.'.domain'};
2373: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2374: }
1.450 matthew 2375: my $value = $accesshash{$entry};
2376: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2377: my %temphash=($url => $value);
1.449 matthew 2378: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2379: if ($result eq 'ok') {
2380: delete $accesshash{$entry};
2381: } elsif ($result eq 'unknown_cmd') {
2382: # Target server has old code running on it.
1.450 matthew 2383: my %temphash=($entry => $value);
1.449 matthew 2384: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2385: delete $accesshash{$entry};
2386: }
2387: }
2388: } else {
1.811 albertel 2389: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2390: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2391: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2392: delete $accesshash{$entry};
2393: }
1.185 www 2394: }
1.191 harris41 2395: }
1.352 www 2396: #
2397: # Roles
2398: # Reverse lookup of user roles for course faculty/staff and co-authorship
2399: #
1.800 albertel 2400: foreach my $entry (keys(%userrolehash)) {
1.351 www 2401: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2402: split(/\:/,$entry);
2403: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2404: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2405: $rudom,$runame) eq 'ok') {
2406: delete $userrolehash{$entry};
2407: }
2408: }
1.662 raeburn 2409: #
2410: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2411: #
2412: my %domrolebuffer = ();
2413: foreach my $entry (keys %domainrolehash) {
1.901 albertel 2414: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2415: if ($domrolebuffer{$rudom}) {
2416: $domrolebuffer{$rudom}.='&'.&escape($entry).
2417: '='.&escape($domainrolehash{$entry});
2418: } else {
2419: $domrolebuffer{$rudom}.=&escape($entry).
2420: '='.&escape($domainrolehash{$entry});
2421: }
2422: delete $domainrolehash{$entry};
2423: }
2424: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2425: my %servers = &get_servers($dom,'library');
2426: foreach my $tryserver (keys(%servers)) {
2427: unless (&reply('domroleput:'.$dom.':'.
2428: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2429: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2430: }
1.662 raeburn 2431: }
2432: }
1.186 www 2433: $dumpcount++;
1.157 www 2434: }
2435:
2436: sub courselog {
2437: my $what=shift;
1.158 www 2438: $what=time.':'.$what;
1.620 albertel 2439: unless ($env{'request.course.id'}) { return ''; }
2440: $coursedombuf{$env{'request.course.id'}}=
2441: $env{'course.'.$env{'request.course.id'}.'.domain'};
2442: $coursenumbuf{$env{'request.course.id'}}=
2443: $env{'course.'.$env{'request.course.id'}.'.num'};
2444: $coursehombuf{$env{'request.course.id'}}=
2445: $env{'course.'.$env{'request.course.id'}.'.home'};
2446: $coursedescrbuf{$env{'request.course.id'}}=
2447: $env{'course.'.$env{'request.course.id'}.'.description'};
2448: $courseinstcodebuf{$env{'request.course.id'}}=
2449: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2450: $courseownerbuf{$env{'request.course.id'}}=
2451: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2452: $coursetypebuf{$env{'request.course.id'}}=
2453: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2454: if (defined $courselogs{$env{'request.course.id'}}) {
2455: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2456: } else {
1.620 albertel 2457: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2458: }
1.620 albertel 2459: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2460: &flushcourselogs();
2461: }
1.158 www 2462: }
2463:
2464: sub courseacclog {
2465: my $fnsymb=shift;
1.620 albertel 2466: unless ($env{'request.course.id'}) { return ''; }
2467: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2468: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2469: $what.=':POST';
1.583 matthew 2470: # FIXME: Probably ought to escape things....
1.800 albertel 2471: foreach my $key (keys(%env)) {
2472: if ($key=~/^form\.(.*)/) {
2473: $what.=':'.$1.'='.$env{$key};
1.158 www 2474: }
1.191 harris41 2475: }
1.583 matthew 2476: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2477: # FIXME: We should not be depending on a form parameter that someone
2478: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2479: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2480: $what.= ':POST';
2481: # FIXME: Probably ought to escape things....
2482: foreach my $element ('courseexp','crsfulltext','crsrelated',
2483: 'crsdiscuss') {
1.620 albertel 2484: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2485: }
2486: }
1.158 www 2487: }
2488: &courselog($what);
1.149 www 2489: }
2490:
1.185 www 2491: sub countacc {
2492: my $url=&declutter(shift);
1.458 matthew 2493: return if (! defined($url) || $url eq '');
1.620 albertel 2494: unless ($env{'request.course.id'}) { return ''; }
2495: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2496: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2497: $accesshash{$key}++;
1.185 www 2498: }
1.349 www 2499:
1.361 www 2500: sub linklog {
2501: my ($from,$to)=@_;
2502: $from=&declutter($from);
2503: $to=&declutter($to);
2504: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2505: $accesshash{$to.'___'.$from.'___goto'}=1;
2506: }
2507:
1.349 www 2508: sub userrolelog {
2509: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2510: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2511: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2512: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2513: ($trole=~/^ta/)) {
1.350 www 2514: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2515: $userrolehash
2516: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2517: =$tend.':'.$tstart;
1.662 raeburn 2518: }
1.898 albertel 2519: if (($env{'request.role'} =~ /dc\./) &&
2520: (($trole=~/^au/) || ($trole=~/^in/) ||
2521: ($trole=~/^cc/) || ($trole=~/^ep/) ||
2522: ($trole=~/^cr/) || ($trole=~/^ta/))) {
2523: $userrolehash
2524: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2525: =$tend.':'.$tstart;
2526: }
1.662 raeburn 2527: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2528: ($trole=~/^li/) || ($trole=~/^li/) ||
2529: ($trole=~/^au/) || ($trole=~/^dg/) ||
2530: ($trole=~/^sc/)) {
2531: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2532: $domainrolehash
2533: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2534: = $tend.':'.$tstart;
2535: }
1.351 www 2536: }
2537:
1.957 raeburn 2538: sub courserolelog {
2539: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2540: if (($trole eq 'cc') || ($trole eq 'in') ||
2541: ($trole eq 'ep') || ($trole eq 'ad') ||
2542: ($trole eq 'ta') || ($trole eq 'st') ||
2543: ($trole=~/^cr/) || ($trole eq 'gr')) {
2544: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2545: my $cdom = $1;
2546: my $cnum = $2;
2547: my $sec = $3;
2548: my $namespace = 'rolelog';
2549: my %storehash = (
2550: role => $trole,
2551: start => $tstart,
2552: end => $tend,
2553: selfenroll => $selfenroll,
2554: context => $context,
2555: );
2556: if ($trole eq 'gr') {
2557: $namespace = 'groupslog';
2558: $storehash{'group'} = $sec;
2559: } else {
2560: $storehash{'section'} = $sec;
2561: }
2562: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
2563: }
2564: }
2565: return;
2566: }
2567:
1.351 www 2568: sub get_course_adv_roles {
1.948 raeburn 2569: my ($cid,$codes) = @_;
1.620 albertel 2570: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2571: my %coursehash=&coursedescription($cid);
1.470 www 2572: my %nothide=();
1.800 albertel 2573: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2574: if ($user !~ /:/) {
2575: $nothide{join(':',split(/[\@]/,$user))}=1;
2576: } else {
2577: $nothide{$user}=1;
2578: }
1.470 www 2579: }
1.351 www 2580: my %returnhash=();
2581: my %dumphash=
2582: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2583: my $now=time;
1.800 albertel 2584: foreach my $entry (keys %dumphash) {
2585: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2586: if (($tstart) && ($tstart<0)) { next; }
2587: if (($tend) && ($tend<$now)) { next; }
2588: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2589: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2590: if ($username eq '' || $domain eq '') { next; }
1.470 www 2591: if ((&privileged($username,$domain)) &&
2592: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2593: if ($role eq 'cr') { next; }
1.948 raeburn 2594: if ($codes) {
2595: if ($section) { $role .= ':'.$section; }
2596: if ($returnhash{$role}) {
2597: $returnhash{$role}.=','.$username.':'.$domain;
2598: } else {
2599: $returnhash{$role}=$username.':'.$domain;
2600: }
1.351 www 2601: } else {
1.948 raeburn 2602: my $key=&plaintext($role);
2603: if ($section) { $key.=' (Section '.$section.')'; }
2604: if ($returnhash{$key}) {
2605: $returnhash{$key}.=','.$username.':'.$domain;
2606: } else {
2607: $returnhash{$key}=$username.':'.$domain;
2608: }
1.351 www 2609: }
1.948 raeburn 2610: }
1.400 www 2611: return %returnhash;
2612: }
2613:
2614: sub get_my_roles {
1.937 raeburn 2615: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 2616: unless (defined($uname)) { $uname=$env{'user.name'}; }
2617: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 2618: my (%dumphash,%nothide);
1.858 raeburn 2619: if ($context eq 'userroles') {
2620: %dumphash = &dump('roles',$udom,$uname);
2621: } else {
2622: %dumphash=
1.400 www 2623: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 2624: if ($hidepriv) {
2625: my %coursehash=&coursedescription($udom.'_'.$uname);
2626: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2627: if ($user !~ /:/) {
2628: $nothide{join(':',split(/[\@]/,$user))} = 1;
2629: } else {
2630: $nothide{$user} = 1;
2631: }
2632: }
2633: }
1.858 raeburn 2634: }
1.400 www 2635: my %returnhash=();
2636: my $now=time;
1.800 albertel 2637: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2638: my ($role,$tend,$tstart);
2639: if ($context eq 'userroles') {
2640: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2641: } else {
2642: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2643: }
1.400 www 2644: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2645: my $status = 'active';
1.939 raeburn 2646: if (($tend) && ($tend<=$now)) {
1.832 raeburn 2647: $status = 'previous';
2648: }
2649: if (($tstart) && ($now<$tstart)) {
2650: $status = 'future';
2651: }
2652: if (ref($types) eq 'ARRAY') {
2653: if (!grep(/^\Q$status\E$/,@{$types})) {
2654: next;
2655: }
2656: } else {
2657: if ($status ne 'active') {
2658: next;
2659: }
2660: }
1.867 raeburn 2661: my ($rolecode,$username,$domain,$section,$area);
2662: if ($context eq 'userroles') {
2663: ($area,$rolecode) = split(/_/,$entry);
2664: (undef,$domain,$username,$section) = split(/\//,$area);
2665: } else {
2666: ($role,$username,$domain,$section) = split(/\:/,$entry);
2667: }
1.832 raeburn 2668: if (ref($roledoms) eq 'ARRAY') {
2669: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2670: next;
2671: }
2672: }
2673: if (ref($roles) eq 'ARRAY') {
2674: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 2675: if ($role =~ /^cr\//) {
2676: if (!grep(/^cr$/,@{$roles})) {
2677: next;
2678: }
2679: } else {
2680: next;
2681: }
1.832 raeburn 2682: }
1.867 raeburn 2683: }
1.937 raeburn 2684: if ($hidepriv) {
2685: if ((&privileged($username,$domain)) &&
2686: (!$nothide{$username.':'.$domain})) {
2687: next;
2688: }
2689: }
1.933 raeburn 2690: if ($withsec) {
2691: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2692: $tstart.':'.$tend;
2693: } else {
2694: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2695: }
1.832 raeburn 2696: }
1.373 www 2697: return %returnhash;
1.399 www 2698: }
2699:
2700: # ----------------------------------------------------- Frontpage Announcements
2701: #
2702: #
2703:
2704: sub postannounce {
2705: my ($server,$text)=@_;
1.844 albertel 2706: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2707: unless ($text=~/\w/) { $text=''; }
2708: return &reply('setannounce:'.&escape($text),$server);
2709: }
2710:
2711: sub getannounce {
1.448 albertel 2712:
2713: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 2714: my $announcement='';
1.800 albertel 2715: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 2716: close($fh);
1.399 www 2717: if ($announcement=~/\w/) {
2718: return
2719: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 2720: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 2721: } else {
2722: return '';
2723: }
2724: } else {
2725: return '';
2726: }
1.351 www 2727: }
1.353 www 2728:
2729: # ---------------------------------------------------------- Course ID routines
2730: # Deal with domain's nohist_courseid.db files
2731: #
2732:
2733: sub courseidput {
1.921 raeburn 2734: my ($domain,$storehash,$coursehome,$caller) = @_;
2735: my $outcome;
2736: if ($caller eq 'timeonly') {
2737: my $cids = '';
2738: foreach my $item (keys(%$storehash)) {
2739: $cids.=&escape($item).'&';
2740: }
2741: $cids=~s/\&$//;
2742: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
2743: $coursehome);
2744: } else {
2745: my $items = '';
2746: foreach my $item (keys(%$storehash)) {
2747: $items.= &escape($item).'='.
2748: &freeze_escape($$storehash{$item}).'&';
2749: }
2750: $items=~s/\&$//;
2751: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
2752: $coursehome);
1.918 raeburn 2753: }
2754: if ($outcome eq 'unknown_cmd') {
2755: my $what;
2756: foreach my $cid (keys(%$storehash)) {
2757: $what .= &escape($cid).'=';
1.921 raeburn 2758: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 2759: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 2760: }
2761: $what =~ s/\:$/&/;
2762: }
2763: $what =~ s/\&$//;
2764: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2765: } else {
2766: return $outcome;
2767: }
1.353 www 2768: }
2769:
2770: sub courseiddump {
1.921 raeburn 2771: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 2772: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962 raeburn 2773: $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918 raeburn 2774: my $as_hash = 1;
2775: my %returnhash;
2776: if (!$domfilter) { $domfilter=''; }
1.845 albertel 2777: my %libserv = &all_library();
2778: foreach my $tryserver (keys(%libserv)) {
2779: if ( ( $hostidflag == 1
2780: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
2781: || (!defined($hostidflag)) ) {
2782:
1.918 raeburn 2783: if (($domfilter eq '') ||
2784: (&host_domain($tryserver) eq $domfilter)) {
2785: my $rep =
2786: &reply('courseiddump:'.&host_domain($tryserver).':'.
2787: $sincefilter.':'.&escape($descfilter).':'.
2788: &escape($instcodefilter).':'.&escape($ownerfilter).
2789: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 2790: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 2791: &escape($selfenrollonly).':'.&escape($catfilter).':'.
2792: $showhidden.':'.$caller,$tryserver);
1.918 raeburn 2793: my @pairs=split(/\&/,$rep);
2794: foreach my $item (@pairs) {
2795: my ($key,$value)=split(/\=/,$item,2);
2796: $key = &unescape($key);
2797: next if ($key =~ /^error: 2 /);
2798: my $result = &thaw_unescape($value);
2799: if (ref($result) eq 'HASH') {
2800: $returnhash{$key}=$result;
2801: } else {
1.921 raeburn 2802: my @responses = split(/:/,$value);
2803: my @items = ('description','inst_code','owner','type');
1.918 raeburn 2804: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 2805: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 2806: }
2807: }
1.353 www 2808: }
2809: }
2810: }
2811: }
2812: return %returnhash;
2813: }
2814:
1.658 raeburn 2815: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 2816:
2817: sub dcmailput {
1.685 raeburn 2818: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 2819: my $status = &Apache::lonnet::critical(
1.740 www 2820: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2821: &escape($message),$server);
1.662 raeburn 2822: return $status;
2823: }
2824:
1.658 raeburn 2825: sub dcmaildump {
2826: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 2827: my %returnhash=();
1.846 albertel 2828:
2829: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 2830: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2831: &escape($enddate).':';
2832: my @esc_senders=map { &escape($_)} @$senders;
2833: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 2834: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 2835: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 2836: if (($key) && ($value)) {
2837: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 2838: }
2839: }
2840: }
2841: return %returnhash;
2842: }
1.662 raeburn 2843: # ---------------------------------------------------------- Domain roles
2844:
2845: sub get_domain_roles {
2846: my ($dom,$roles,$startdate,$enddate)=@_;
2847: if (undef($startdate) || $startdate eq '') {
2848: $startdate = '.';
2849: }
2850: if (undef($enddate) || $enddate eq '') {
2851: $enddate = '.';
2852: }
1.922 raeburn 2853: my $rolelist;
2854: if (ref($roles) eq 'ARRAY') {
2855: $rolelist = join(':',@{$roles});
2856: }
1.662 raeburn 2857: my %personnel = ();
1.841 albertel 2858:
2859: my %servers = &get_servers($dom,'library');
2860: foreach my $tryserver (keys(%servers)) {
2861: %{$personnel{$tryserver}}=();
2862: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
2863: &escape($startdate).':'.
2864: &escape($enddate).':'.
2865: &escape($rolelist), $tryserver))) {
2866: my ($key,$value) = split(/\=/,$line,2);
2867: if (($key) && ($value)) {
2868: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2869: }
2870: }
1.662 raeburn 2871: }
2872: return %personnel;
2873: }
1.658 raeburn 2874:
1.149 www 2875: # ----------------------------------------------------------- Check out an item
2876:
1.504 albertel 2877: sub get_first_access {
2878: my ($type,$argsymb)=@_;
1.790 albertel 2879: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2880: if ($argsymb) { $symb=$argsymb; }
2881: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 2882: if ($type eq 'course') {
2883: $res='course';
2884: } elsif ($type eq 'map') {
1.588 albertel 2885: $res=&symbread($map);
2886: } else {
2887: $res=$symb;
2888: }
2889: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2890: return $times{"$courseid\0$res"};
1.504 albertel 2891: }
2892:
2893: sub set_first_access {
2894: my ($type)=@_;
1.790 albertel 2895: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2896: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 2897: if ($type eq 'course') {
2898: $res='course';
2899: } elsif ($type eq 'map') {
1.588 albertel 2900: $res=&symbread($map);
2901: } else {
2902: $res=$symb;
2903: }
2904: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 2905: if (!$firstaccess) {
1.588 albertel 2906: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 2907: }
2908: return 'already_set';
1.504 albertel 2909: }
2910:
1.149 www 2911: sub checkout {
2912: my ($symb,$tuname,$tudom,$tcrsid)=@_;
2913: my $now=time;
2914: my $lonhost=$perlvar{'lonHostID'};
2915: my $infostr=&escape(
1.234 www 2916: 'CHECKOUTTOKEN&'.
1.149 www 2917: $tuname.'&'.
2918: $tudom.'&'.
2919: $tcrsid.'&'.
2920: $symb.'&'.
2921: $now.'&'.$ENV{'REMOTE_ADDR'});
2922: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 2923: if ($token=~/^error\:/) {
1.672 albertel 2924: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2925: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
2926: "</font>");
2927: return '';
2928: }
2929:
1.149 www 2930: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
2931: $token=~tr/a-z/A-Z/;
2932:
1.153 www 2933: my %infohash=('resource.0.outtoken' => $token,
2934: 'resource.0.checkouttime' => $now,
2935: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 2936:
2937: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2938: return '';
1.151 www 2939: } else {
1.672 albertel 2940: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2941: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
2942: "</font>");
1.149 www 2943: }
2944:
2945: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2946: &escape('Checkout '.$infostr.' - '.
2947: $token)) ne 'ok') {
2948: return '';
1.151 www 2949: } else {
1.672 albertel 2950: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2951: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
2952: "</font>");
1.149 www 2953: }
1.151 www 2954: return $token;
1.149 www 2955: }
2956:
2957: # ------------------------------------------------------------ Check in an item
2958:
2959: sub checkin {
2960: my $token=shift;
1.150 www 2961: my $now=time;
2962: my ($ta,$tb,$lonhost)=split(/\*/,$token);
2963: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 2964: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 2965: $dtoken=~s/\W/\_/g;
1.234 www 2966: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 2967: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
2968:
1.154 www 2969: unless (($tuname) && ($tudom)) {
2970: &logthis('Check in '.$token.' ('.$dtoken.') failed');
2971: return '';
2972: }
2973:
2974: unless (&allowed('mgr',$tcrsid)) {
2975: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 2976: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 2977: return '';
2978: }
2979:
1.153 www 2980: my %infohash=('resource.0.intoken' => $token,
2981: 'resource.0.checkintime' => $now,
2982: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 2983:
2984: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2985: return '';
2986: }
2987:
2988: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2989: &escape('Checkin - '.$token)) ne 'ok') {
2990: return '';
2991: }
2992:
2993: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 2994: }
2995:
2996: # --------------------------------------------- Set Expire Date for Spreadsheet
2997:
2998: sub expirespread {
2999: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3000: my $cid=$env{'request.course.id'};
1.110 www 3001: if ($cid) {
3002: my $now=time;
3003: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3004: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3005: $env{'course.'.$cid.'.num'}.
1.110 www 3006: ':nohist_expirationdates:'.
3007: &escape($key).'='.$now,
1.620 albertel 3008: $env{'course.'.$cid.'.home'})
1.110 www 3009: }
3010: return 'ok';
1.14 www 3011: }
3012:
1.109 www 3013: # ----------------------------------------------------- Devalidate Spreadsheets
3014:
3015: sub devalidate {
1.325 www 3016: my ($symb,$uname,$udom)=@_;
1.620 albertel 3017: my $cid=$env{'request.course.id'};
1.109 www 3018: if ($cid) {
1.391 matthew 3019: # delete the stored spreadsheets for
3020: # - the student level sheet of this user in course's homespace
3021: # - the assessment level sheet for this resource
3022: # for this user in user's homespace
1.553 albertel 3023: # - current conditional state info
1.325 www 3024: my $key=$uname.':'.$udom.':';
1.109 www 3025: my $status=
1.299 matthew 3026: &del('nohist_calculatedsheets',
1.391 matthew 3027: [$key.'studentcalc:'],
1.620 albertel 3028: $env{'course.'.$cid.'.domain'},
3029: $env{'course.'.$cid.'.num'})
1.133 albertel 3030: .' '.
3031: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3032: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3033: unless ($status eq 'ok ok') {
3034: &logthis('Could not devalidate spreadsheet '.
1.325 www 3035: $uname.' at '.$udom.' for '.
1.109 www 3036: $symb.': '.$status);
1.133 albertel 3037: }
1.553 albertel 3038: &delenv('user.state.'.$cid);
1.109 www 3039: }
3040: }
3041:
1.265 albertel 3042: sub get_scalar {
3043: my ($string,$end) = @_;
3044: my $value;
3045: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3046: $value = $1;
3047: } elsif ($$string =~ s/^([^&]*?)&//) {
3048: $value = $1;
3049: }
3050: return &unescape($value);
3051: }
3052:
3053: sub array2str {
3054: my (@array) = @_;
3055: my $result=&arrayref2str(\@array);
3056: $result=~s/^__ARRAY_REF__//;
3057: $result=~s/__END_ARRAY_REF__$//;
3058: return $result;
3059: }
3060:
1.204 albertel 3061: sub arrayref2str {
3062: my ($arrayref) = @_;
1.265 albertel 3063: my $result='__ARRAY_REF__';
1.204 albertel 3064: foreach my $elem (@$arrayref) {
1.265 albertel 3065: if(ref($elem) eq 'ARRAY') {
3066: $result.=&arrayref2str($elem).'&';
3067: } elsif(ref($elem) eq 'HASH') {
3068: $result.=&hashref2str($elem).'&';
3069: } elsif(ref($elem)) {
3070: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3071: } else {
3072: $result.=&escape($elem).'&';
3073: }
3074: }
3075: $result=~s/\&$//;
1.265 albertel 3076: $result .= '__END_ARRAY_REF__';
1.204 albertel 3077: return $result;
3078: }
3079:
1.168 albertel 3080: sub hash2str {
1.204 albertel 3081: my (%hash) = @_;
3082: my $result=&hashref2str(\%hash);
1.265 albertel 3083: $result=~s/^__HASH_REF__//;
3084: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3085: return $result;
3086: }
3087:
3088: sub hashref2str {
3089: my ($hashref)=@_;
1.265 albertel 3090: my $result='__HASH_REF__';
1.800 albertel 3091: foreach my $key (sort(keys(%$hashref))) {
3092: if (ref($key) eq 'ARRAY') {
3093: $result.=&arrayref2str($key).'=';
3094: } elsif (ref($key) eq 'HASH') {
3095: $result.=&hashref2str($key).'=';
3096: } elsif (ref($key)) {
1.265 albertel 3097: $result.='=';
1.800 albertel 3098: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3099: } else {
1.800 albertel 3100: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3101: }
3102:
1.800 albertel 3103: if(ref($hashref->{$key}) eq 'ARRAY') {
3104: $result.=&arrayref2str($hashref->{$key}).'&';
3105: } elsif(ref($hashref->{$key}) eq 'HASH') {
3106: $result.=&hashref2str($hashref->{$key}).'&';
3107: } elsif(ref($hashref->{$key})) {
1.265 albertel 3108: $result.='&';
1.800 albertel 3109: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3110: } else {
1.800 albertel 3111: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3112: }
3113: }
1.168 albertel 3114: $result=~s/\&$//;
1.265 albertel 3115: $result .= '__END_HASH_REF__';
1.168 albertel 3116: return $result;
3117: }
3118:
3119: sub str2hash {
1.265 albertel 3120: my ($string)=@_;
3121: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3122: return %$hash;
3123: }
3124:
3125: sub str2hashref {
1.168 albertel 3126: my ($string) = @_;
1.265 albertel 3127:
3128: my %hash;
3129:
3130: if($string !~ /^__HASH_REF__/) {
3131: if (! ($string eq '' || !defined($string))) {
3132: $hash{'error'}='Not hash reference';
3133: }
3134: return (\%hash, $string);
3135: }
3136:
3137: $string =~ s/^__HASH_REF__//;
3138:
3139: while($string !~ /^__END_HASH_REF__/) {
3140: #key
3141: my $key='';
3142: if($string =~ /^__HASH_REF__/) {
3143: ($key, $string)=&str2hashref($string);
3144: if(defined($key->{'error'})) {
3145: $hash{'error'}='Bad data';
3146: return (\%hash, $string);
3147: }
3148: } elsif($string =~ /^__ARRAY_REF__/) {
3149: ($key, $string)=&str2arrayref($string);
3150: if($key->[0] eq 'Array reference error') {
3151: $hash{'error'}='Bad data';
3152: return (\%hash, $string);
3153: }
3154: } else {
3155: $string =~ s/^(.*?)=//;
1.267 albertel 3156: $key=&unescape($1);
1.265 albertel 3157: }
3158: $string =~ s/^=//;
3159:
3160: #value
3161: my $value='';
3162: if($string =~ /^__HASH_REF__/) {
3163: ($value, $string)=&str2hashref($string);
3164: if(defined($value->{'error'})) {
3165: $hash{'error'}='Bad data';
3166: return (\%hash, $string);
3167: }
3168: } elsif($string =~ /^__ARRAY_REF__/) {
3169: ($value, $string)=&str2arrayref($string);
3170: if($value->[0] eq 'Array reference error') {
3171: $hash{'error'}='Bad data';
3172: return (\%hash, $string);
3173: }
3174: } else {
3175: $value=&get_scalar(\$string,'__END_HASH_REF__');
3176: }
3177: $string =~ s/^&//;
3178:
3179: $hash{$key}=$value;
1.204 albertel 3180: }
1.265 albertel 3181:
3182: $string =~ s/^__END_HASH_REF__//;
3183:
3184: return (\%hash, $string);
1.204 albertel 3185: }
3186:
3187: sub str2array {
1.265 albertel 3188: my ($string)=@_;
3189: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3190: return @$array;
3191: }
3192:
3193: sub str2arrayref {
1.204 albertel 3194: my ($string) = @_;
1.265 albertel 3195: my @array;
3196:
3197: if($string !~ /^__ARRAY_REF__/) {
3198: if (! ($string eq '' || !defined($string))) {
3199: $array[0]='Array reference error';
3200: }
3201: return (\@array, $string);
3202: }
3203:
3204: $string =~ s/^__ARRAY_REF__//;
3205:
3206: while($string !~ /^__END_ARRAY_REF__/) {
3207: my $value='';
3208: if($string =~ /^__HASH_REF__/) {
3209: ($value, $string)=&str2hashref($string);
3210: if(defined($value->{'error'})) {
3211: $array[0] ='Array reference error';
3212: return (\@array, $string);
3213: }
3214: } elsif($string =~ /^__ARRAY_REF__/) {
3215: ($value, $string)=&str2arrayref($string);
3216: if($value->[0] eq 'Array reference error') {
3217: $array[0] ='Array reference error';
3218: return (\@array, $string);
3219: }
3220: } else {
3221: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3222: }
3223: $string =~ s/^&//;
3224:
3225: push(@array, $value);
1.191 harris41 3226: }
1.265 albertel 3227:
3228: $string =~ s/^__END_ARRAY_REF__//;
3229:
3230: return (\@array, $string);
1.168 albertel 3231: }
3232:
1.167 albertel 3233: # -------------------------------------------------------------------Temp Store
3234:
1.168 albertel 3235: sub tmpreset {
3236: my ($symb,$namespace,$domain,$stuname) = @_;
3237: if (!$symb) {
3238: $symb=&symbread();
1.620 albertel 3239: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3240: }
3241: $symb=escape($symb);
3242:
1.620 albertel 3243: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3244: $namespace=~s/\//\_/g;
3245: $namespace=~s/\W//g;
3246:
1.620 albertel 3247: if (!$domain) { $domain=$env{'user.domain'}; }
3248: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3249: if ($domain eq 'public' && $stuname eq 'public') {
3250: $stuname=$ENV{'REMOTE_ADDR'};
3251: }
1.168 albertel 3252: my $path=$perlvar{'lonDaemons'}.'/tmp';
3253: my %hash;
3254: if (tie(%hash,'GDBM_File',
3255: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3256: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3257: foreach my $key (keys %hash) {
1.180 albertel 3258: if ($key=~ /:$symb/) {
1.168 albertel 3259: delete($hash{$key});
3260: }
3261: }
3262: }
3263: }
3264:
1.167 albertel 3265: sub tmpstore {
1.168 albertel 3266: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3267:
3268: if (!$symb) {
3269: $symb=&symbread();
1.620 albertel 3270: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3271: }
3272: $symb=escape($symb);
3273:
3274: if (!$namespace) {
3275: # I don't think we would ever want to store this for a course.
3276: # it seems this will only be used if we don't have a course.
1.620 albertel 3277: #$namespace=$env{'request.course.id'};
1.168 albertel 3278: #if (!$namespace) {
1.620 albertel 3279: $namespace=$env{'request.state'};
1.168 albertel 3280: #}
3281: }
3282: $namespace=~s/\//\_/g;
3283: $namespace=~s/\W//g;
1.620 albertel 3284: if (!$domain) { $domain=$env{'user.domain'}; }
3285: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3286: if ($domain eq 'public' && $stuname eq 'public') {
3287: $stuname=$ENV{'REMOTE_ADDR'};
3288: }
1.168 albertel 3289: my $now=time;
3290: my %hash;
3291: my $path=$perlvar{'lonDaemons'}.'/tmp';
3292: if (tie(%hash,'GDBM_File',
3293: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3294: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3295: $hash{"version:$symb"}++;
3296: my $version=$hash{"version:$symb"};
3297: my $allkeys='';
3298: foreach my $key (keys(%$storehash)) {
3299: $allkeys.=$key.':';
1.591 albertel 3300: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3301: }
3302: $hash{"$version:$symb:timestamp"}=$now;
3303: $allkeys.='timestamp';
3304: $hash{"$version:keys:$symb"}=$allkeys;
3305: if (untie(%hash)) {
3306: return 'ok';
3307: } else {
3308: return "error:$!";
3309: }
3310: } else {
3311: return "error:$!";
3312: }
3313: }
1.167 albertel 3314:
1.168 albertel 3315: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3316:
1.168 albertel 3317: sub tmprestore {
3318: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3319:
1.168 albertel 3320: if (!$symb) {
3321: $symb=&symbread();
1.620 albertel 3322: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3323: }
3324: $symb=escape($symb);
3325:
1.620 albertel 3326: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3327:
1.620 albertel 3328: if (!$domain) { $domain=$env{'user.domain'}; }
3329: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3330: if ($domain eq 'public' && $stuname eq 'public') {
3331: $stuname=$ENV{'REMOTE_ADDR'};
3332: }
1.168 albertel 3333: my %returnhash;
3334: $namespace=~s/\//\_/g;
3335: $namespace=~s/\W//g;
3336: my %hash;
3337: my $path=$perlvar{'lonDaemons'}.'/tmp';
3338: if (tie(%hash,'GDBM_File',
3339: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3340: &GDBM_READER(),0640)) {
1.168 albertel 3341: my $version=$hash{"version:$symb"};
3342: $returnhash{'version'}=$version;
3343: my $scope;
3344: for ($scope=1;$scope<=$version;$scope++) {
3345: my $vkeys=$hash{"$scope:keys:$symb"};
3346: my @keys=split(/:/,$vkeys);
3347: my $key;
3348: $returnhash{"$scope:keys"}=$vkeys;
3349: foreach $key (@keys) {
1.591 albertel 3350: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3351: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3352: }
3353: }
1.168 albertel 3354: if (!(untie(%hash))) {
3355: return "error:$!";
3356: }
3357: } else {
3358: return "error:$!";
3359: }
3360: return %returnhash;
1.167 albertel 3361: }
3362:
1.9 www 3363: # ----------------------------------------------------------------------- Store
3364:
3365: sub store {
1.124 www 3366: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3367: my $home='';
3368:
1.168 albertel 3369: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3370:
1.213 www 3371: $symb=&symbclean($symb);
1.122 albertel 3372: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3373:
1.620 albertel 3374: if (!$domain) { $domain=$env{'user.domain'}; }
3375: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3376:
3377: &devalidate($symb,$stuname,$domain);
1.109 www 3378:
3379: $symb=escape($symb);
1.187 www 3380: if (!$namespace) {
1.620 albertel 3381: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3382: return '';
3383: }
3384: }
1.620 albertel 3385: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3386:
3387: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3388: $$storehash{'host'}=$perlvar{'lonHostID'};
3389:
1.12 www 3390: my $namevalue='';
1.800 albertel 3391: foreach my $key (keys(%$storehash)) {
3392: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3393: }
1.12 www 3394: $namevalue=~s/\&$//;
1.187 www 3395: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3396: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3397: }
3398:
1.47 www 3399: # -------------------------------------------------------------- Critical Store
3400:
3401: sub cstore {
1.124 www 3402: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3403: my $home='';
3404:
1.168 albertel 3405: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3406:
1.213 www 3407: $symb=&symbclean($symb);
1.122 albertel 3408: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3409:
1.620 albertel 3410: if (!$domain) { $domain=$env{'user.domain'}; }
3411: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3412:
3413: &devalidate($symb,$stuname,$domain);
1.109 www 3414:
3415: $symb=escape($symb);
1.187 www 3416: if (!$namespace) {
1.620 albertel 3417: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3418: return '';
3419: }
3420: }
1.620 albertel 3421: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3422:
3423: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3424: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3425:
1.47 www 3426: my $namevalue='';
1.800 albertel 3427: foreach my $key (keys(%$storehash)) {
3428: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3429: }
1.47 www 3430: $namevalue=~s/\&$//;
1.187 www 3431: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3432: return critical
3433: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3434: }
3435:
1.9 www 3436: # --------------------------------------------------------------------- Restore
3437:
3438: sub restore {
1.124 www 3439: my ($symb,$namespace,$domain,$stuname) = @_;
3440: my $home='';
3441:
1.168 albertel 3442: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3443:
1.122 albertel 3444: if (!$symb) {
3445: unless ($symb=escape(&symbread())) { return ''; }
3446: } else {
1.213 www 3447: $symb=&escape(&symbclean($symb));
1.122 albertel 3448: }
1.188 www 3449: if (!$namespace) {
1.620 albertel 3450: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3451: return '';
3452: }
3453: }
1.620 albertel 3454: if (!$domain) { $domain=$env{'user.domain'}; }
3455: if (!$stuname) { $stuname=$env{'user.name'}; }
3456: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3457: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3458:
1.12 www 3459: my %returnhash=();
1.800 albertel 3460: foreach my $line (split(/\&/,$answer)) {
3461: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3462: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3463: }
1.75 www 3464: my $version;
3465: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3466: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3467: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3468: }
1.75 www 3469: }
1.13 www 3470: return %returnhash;
1.34 www 3471: }
3472:
3473: # ---------------------------------------------------------- Course Description
3474:
3475: sub coursedescription {
1.731 albertel 3476: my ($courseid,$args)=@_;
1.34 www 3477: $courseid=~s/^\///;
1.49 www 3478: $courseid=~s/\_/\//g;
1.34 www 3479: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3480: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3481: my $normalid=$cdomain.'_'.$cnum;
3482: # need to always cache even if we get errors otherwise we keep
3483: # trying and trying and trying to get the course description.
3484: my %envhash=();
3485: my %returnhash=();
1.731 albertel 3486:
3487: my $expiretime=600;
3488: if ($env{'request.course.id'} eq $normalid) {
3489: $expiretime=120;
3490: }
3491:
3492: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3493: if (!$args->{'freshen_cache'}
3494: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3495: foreach my $key (keys(%env)) {
3496: next if ($key !~ /^\Q$prefix\E(.*)/);
3497: my ($setting) = $1;
3498: $returnhash{$setting} = $env{$key};
3499: }
3500: return %returnhash;
3501: }
3502:
3503: # get the data agin
3504: if (!$args->{'one_time'}) {
3505: $envhash{'course.'.$normalid.'.last_cache'}=time;
3506: }
1.811 albertel 3507:
1.34 www 3508: if ($chome ne 'no_host') {
1.302 albertel 3509: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3510: if (!exists($returnhash{'con_lost'})) {
3511: $returnhash{'home'}= $chome;
3512: $returnhash{'domain'} = $cdomain;
3513: $returnhash{'num'} = $cnum;
1.741 raeburn 3514: if (!defined($returnhash{'type'})) {
3515: $returnhash{'type'} = 'Course';
3516: }
1.130 albertel 3517: while (my ($name,$value) = each %returnhash) {
1.53 www 3518: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3519: }
1.270 www 3520: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3521: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3522: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3523: $envhash{'course.'.$normalid.'.home'}=$chome;
3524: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3525: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3526: }
3527: }
1.731 albertel 3528: if (!$args->{'one_time'}) {
1.949 raeburn 3529: &appenv(\%envhash);
1.731 albertel 3530: }
1.302 albertel 3531: return %returnhash;
1.461 www 3532: }
3533:
3534: # -------------------------------------------------See if a user is privileged
3535:
3536: sub privileged {
3537: my ($username,$domain)=@_;
3538: my $rolesdump=&reply("dump:$domain:$username:roles",
3539: &homeserver($username,$domain));
3540: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
3541: my $now=time;
3542: if ($rolesdump ne '') {
1.800 albertel 3543: foreach my $entry (split(/&/,$rolesdump)) {
3544: if ($entry!~/^rolesdef_/) {
3545: my ($area,$role)=split(/=/,$entry);
1.461 www 3546: $area=~s/\_\w\w$//;
3547: my ($trole,$tend,$tstart)=split(/_/,$role);
3548: if (($trole eq 'dc') || ($trole eq 'su')) {
3549: my $active=1;
3550: if ($tend) {
3551: if ($tend<$now) { $active=0; }
3552: }
3553: if ($tstart) {
3554: if ($tstart>$now) { $active=0; }
3555: }
3556: if ($active) { return 1; }
3557: }
3558: }
3559: }
3560: }
3561: return 0;
1.9 www 3562: }
1.1 albertel 3563:
1.103 harris41 3564: # -------------------------------------------------------- Get user privileges
1.11 www 3565:
3566: sub rolesinit {
3567: my ($domain,$username,$authhost)=@_;
1.966 raeburn 3568: my %userroles;
1.11 www 3569: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966 raeburn 3570: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11 www 3571: my %allroles=();
1.678 raeburn 3572: my %allgroups=();
1.11 www 3573: my $now=time;
1.966 raeburn 3574: %userroles = ('user.login.time' => $now);
1.678 raeburn 3575: my $group_privs;
1.11 www 3576:
3577: if ($rolesdump ne '') {
1.800 albertel 3578: foreach my $entry (split(/&/,$rolesdump)) {
3579: if ($entry!~/^rolesdef_/) {
3580: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3581: $area=~s/\_\w\w$//;
1.678 raeburn 3582: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3583: if ($role=~/^cr/) {
1.807 albertel 3584: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3585: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3586: ($tend,$tstart)=split('_',$trest);
3587: } else {
3588: $trole=$role;
3589: }
1.678 raeburn 3590: } elsif ($role =~ m|^gr/|) {
3591: ($trole,$tend,$tstart) = split(/_/,$role);
3592: ($trole,$group_privs) = split(/\//,$trole);
3593: $group_privs = &unescape($group_privs);
1.587 albertel 3594: } else {
3595: ($trole,$tend,$tstart)=split(/_/,$role);
3596: }
1.743 albertel 3597: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3598: $username);
3599: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3600: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3601: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3602: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3603: my $spec=$trole.'.'.$area;
3604: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3605: if ($trole =~ /^cr\//) {
1.567 raeburn 3606: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3607: } elsif ($trole eq 'gr') {
3608: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3609: } else {
1.567 raeburn 3610: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3611: }
1.12 www 3612: }
1.662 raeburn 3613: }
1.191 harris41 3614: }
1.743 albertel 3615: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3616: $userroles{'user.adv'} = $adv;
3617: $userroles{'user.author'} = $author;
1.620 albertel 3618: $env{'user.adv'}=$adv;
1.11 www 3619: }
1.743 albertel 3620: return \%userroles;
1.11 www 3621: }
3622:
1.567 raeburn 3623: sub set_arearole {
3624: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3625: # log the associated role with the area
3626: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3627: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3628: }
3629:
3630: sub custom_roleprivs {
3631: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3632: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3633: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3634: if (&hostname($homsvr) ne '') {
1.567 raeburn 3635: my ($rdummy,$roledef)=
3636: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3637: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3638: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3639: if (defined($syspriv)) {
3640: $$allroles{'cm./'}.=':'.$syspriv;
3641: $$allroles{$spec.'./'}.=':'.$syspriv;
3642: }
3643: if ($tdomain ne '') {
3644: if (defined($dompriv)) {
3645: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3646: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3647: }
3648: if (($trest ne '') && (defined($coursepriv))) {
3649: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3650: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3651: }
3652: }
3653: }
3654: }
3655: }
3656:
1.678 raeburn 3657: sub group_roleprivs {
3658: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3659: my $access = 1;
3660: my $now = time;
3661: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3662: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3663: if ($access) {
1.811 albertel 3664: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3665: $$allgroups{$course}{$group} .=':'.$group_privs;
3666: }
3667: }
1.567 raeburn 3668:
3669: sub standard_roleprivs {
3670: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3671: if (defined($pr{$trole.':s'})) {
3672: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3673: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3674: }
3675: if ($tdomain ne '') {
3676: if (defined($pr{$trole.':d'})) {
3677: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3678: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3679: }
3680: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3681: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3682: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3683: }
3684: }
3685: }
3686:
3687: sub set_userprivs {
1.678 raeburn 3688: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 3689: my $author=0;
3690: my $adv=0;
1.678 raeburn 3691: my %grouproles = ();
3692: if (keys(%{$allgroups}) > 0) {
3693: foreach my $role (keys %{$allroles}) {
1.681 raeburn 3694: my ($trole,$area,$sec,$extendedarea);
1.881 raeburn 3695: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678 raeburn 3696: $trole = $1;
3697: $area = $2;
1.681 raeburn 3698: $sec = $3;
3699: $extendedarea = $area.$sec;
3700: if (exists($$allgroups{$area})) {
3701: foreach my $group (keys(%{$$allgroups{$area}})) {
3702: my $spec = $trole.'.'.$extendedarea;
3703: $grouproles{$spec.'.'.$area.'/'.$group} =
3704: $$allgroups{$area}{$group};
1.678 raeburn 3705: }
3706: }
3707: }
3708: }
3709: }
1.800 albertel 3710: foreach my $group (keys(%grouproles)) {
3711: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3712: }
1.800 albertel 3713: foreach my $role (keys(%{$allroles})) {
3714: my %thesepriv;
1.941 raeburn 3715: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 3716: foreach my $item (split(/:/,$$allroles{$role})) {
3717: if ($item ne '') {
3718: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3719: if ($restrictions eq '') {
3720: $thesepriv{$privilege}='F';
3721: } elsif ($thesepriv{$privilege} ne 'F') {
3722: $thesepriv{$privilege}.=$restrictions;
3723: }
3724: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3725: }
3726: }
3727: my $thesestr='';
1.800 albertel 3728: foreach my $priv (keys(%thesepriv)) {
3729: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3730: }
3731: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3732: }
3733: return ($author,$adv);
3734: }
3735:
1.12 www 3736: # --------------------------------------------------------------- get interface
3737:
3738: sub get {
1.131 albertel 3739: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3740: my $items='';
1.800 albertel 3741: foreach my $item (@$storearr) {
3742: $items.=&escape($item).'&';
1.191 harris41 3743: }
1.12 www 3744: $items=~s/\&$//;
1.620 albertel 3745: if (!$udomain) { $udomain=$env{'user.domain'}; }
3746: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 3747: my $uhome=&homeserver($uname,$udomain);
3748:
1.133 albertel 3749: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3750: my @pairs=split(/\&/,$rep);
1.273 albertel 3751: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
3752: return @pairs;
3753: }
1.15 www 3754: my %returnhash=();
1.42 www 3755: my $i=0;
1.800 albertel 3756: foreach my $item (@$storearr) {
3757: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3758: $i++;
1.191 harris41 3759: }
1.15 www 3760: return %returnhash;
1.27 www 3761: }
3762:
3763: # --------------------------------------------------------------- del interface
3764:
3765: sub del {
1.133 albertel 3766: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 3767: my $items='';
1.800 albertel 3768: foreach my $item (@$storearr) {
3769: $items.=&escape($item).'&';
1.191 harris41 3770: }
1.27 www 3771: $items=~s/\&$//;
1.620 albertel 3772: if (!$udomain) { $udomain=$env{'user.domain'}; }
3773: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3774: my $uhome=&homeserver($uname,$udomain);
3775:
3776: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3777: }
3778:
3779: # -------------------------------------------------------------- dump interface
3780:
3781: sub dump {
1.755 albertel 3782: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3783: if (!$udomain) { $udomain=$env{'user.domain'}; }
3784: if (!$uname) { $uname=$env{'user.name'}; }
3785: my $uhome=&homeserver($uname,$udomain);
3786: if ($regexp) {
3787: $regexp=&escape($regexp);
3788: } else {
3789: $regexp='.';
3790: }
3791: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3792: my @pairs=split(/\&/,$rep);
3793: my %returnhash=();
3794: foreach my $item (@pairs) {
3795: my ($key,$value)=split(/=/,$item,2);
3796: $key = &unescape($key);
3797: next if ($key =~ /^error: 2 /);
3798: $returnhash{$key}=&thaw_unescape($value);
3799: }
3800: return %returnhash;
1.407 www 3801: }
3802:
1.717 albertel 3803: # --------------------------------------------------------- dumpstore interface
3804:
3805: sub dumpstore {
3806: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 3807: if (!$udomain) { $udomain=$env{'user.domain'}; }
3808: if (!$uname) { $uname=$env{'user.name'}; }
3809: my $uhome=&homeserver($uname,$udomain);
3810: if ($regexp) {
3811: $regexp=&escape($regexp);
3812: } else {
3813: $regexp='.';
3814: }
3815: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3816: my @pairs=split(/\&/,$rep);
3817: my %returnhash=();
3818: foreach my $item (@pairs) {
3819: my ($key,$value)=split(/=/,$item,2);
3820: next if ($key =~ /^error: 2 /);
3821: $returnhash{$key}=&thaw_unescape($value);
3822: }
3823: return %returnhash;
1.717 albertel 3824: }
3825:
1.407 www 3826: # -------------------------------------------------------------- keys interface
3827:
3828: sub getkeys {
3829: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 3830: if (!$udomain) { $udomain=$env{'user.domain'}; }
3831: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 3832: my $uhome=&homeserver($uname,$udomain);
3833: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3834: my @keyarray=();
1.800 albertel 3835: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 3836: next if ($key =~ /^error: 2 /);
1.800 albertel 3837: push(@keyarray,&unescape($key));
1.407 www 3838: }
3839: return @keyarray;
1.318 matthew 3840: }
3841:
1.319 matthew 3842: # --------------------------------------------------------------- currentdump
3843: sub currentdump {
1.328 matthew 3844: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 3845: $courseid = $env{'request.course.id'} if (! defined($courseid));
3846: $sdom = $env{'user.domain'} if (! defined($sdom));
3847: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 3848: my $uhome = &homeserver($sname,$sdom);
3849: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 3850: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 3851: #
1.318 matthew 3852: my %returnhash=();
1.319 matthew 3853: #
3854: if ($rep eq "unknown_cmd") {
3855: # an old lond will not know currentdump
3856: # Do a dump and make it look like a currentdump
1.822 albertel 3857: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 3858: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3859: my %hash = @tmp;
3860: @tmp=();
1.424 matthew 3861: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 3862: } else {
3863: my @pairs=split(/\&/,$rep);
1.800 albertel 3864: foreach my $pair (@pairs) {
3865: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 3866: my ($symb,$param) = split(/:/,$key);
3867: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 3868: &thaw_unescape($value);
1.319 matthew 3869: }
1.191 harris41 3870: }
1.12 www 3871: return %returnhash;
1.424 matthew 3872: }
3873:
3874: sub convert_dump_to_currentdump{
3875: my %hash = %{shift()};
3876: my %returnhash;
3877: # Code ripped from lond, essentially. The only difference
3878: # here is the unescaping done by lonnet::dump(). Conceivably
3879: # we might run in to problems with parameter names =~ /^v\./
3880: while (my ($key,$value) = each(%hash)) {
3881: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 3882: $symb = &unescape($symb);
3883: $param = &unescape($param);
1.424 matthew 3884: next if ($v eq 'version' || $symb eq 'keys');
3885: next if (exists($returnhash{$symb}) &&
3886: exists($returnhash{$symb}->{$param}) &&
3887: $returnhash{$symb}->{'v.'.$param} > $v);
3888: $returnhash{$symb}->{$param}=$value;
3889: $returnhash{$symb}->{'v.'.$param}=$v;
3890: }
3891: #
3892: # Remove all of the keys in the hashes which keep track of
3893: # the version of the parameter.
3894: while (my ($symb,$param_hash) = each(%returnhash)) {
3895: # use a foreach because we are going to delete from the hash.
3896: foreach my $key (keys(%$param_hash)) {
3897: delete($param_hash->{$key}) if ($key =~ /^v\./);
3898: }
3899: }
3900: return \%returnhash;
1.12 www 3901: }
3902:
1.627 albertel 3903: # ------------------------------------------------------ critical inc interface
3904:
3905: sub cinc {
3906: return &inc(@_,'critical');
3907: }
3908:
1.449 matthew 3909: # --------------------------------------------------------------- inc interface
3910:
3911: sub inc {
1.627 albertel 3912: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 3913: if (!$udomain) { $udomain=$env{'user.domain'}; }
3914: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 3915: my $uhome=&homeserver($uname,$udomain);
3916: my $items='';
3917: if (! ref($store)) {
3918: # got a single value, so use that instead
3919: $items = &escape($store).'=&';
3920: } elsif (ref($store) eq 'SCALAR') {
3921: $items = &escape($$store).'=&';
3922: } elsif (ref($store) eq 'ARRAY') {
3923: $items = join('=&',map {&escape($_);} @{$store});
3924: } elsif (ref($store) eq 'HASH') {
3925: while (my($key,$value) = each(%{$store})) {
3926: $items.= &escape($key).'='.&escape($value).'&';
3927: }
3928: }
3929: $items=~s/\&$//;
1.627 albertel 3930: if ($critical) {
3931: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
3932: } else {
3933: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
3934: }
1.449 matthew 3935: }
3936:
1.12 www 3937: # --------------------------------------------------------------- put interface
3938:
3939: sub put {
1.134 albertel 3940: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3941: if (!$udomain) { $udomain=$env{'user.domain'}; }
3942: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3943: my $uhome=&homeserver($uname,$udomain);
1.12 www 3944: my $items='';
1.800 albertel 3945: foreach my $item (keys(%$storehash)) {
3946: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3947: }
1.12 www 3948: $items=~s/\&$//;
1.134 albertel 3949: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 3950: }
3951:
1.631 albertel 3952: # ------------------------------------------------------------ newput interface
3953:
3954: sub newput {
3955: my ($namespace,$storehash,$udomain,$uname)=@_;
3956: if (!$udomain) { $udomain=$env{'user.domain'}; }
3957: if (!$uname) { $uname=$env{'user.name'}; }
3958: my $uhome=&homeserver($uname,$udomain);
3959: my $items='';
3960: foreach my $key (keys(%$storehash)) {
3961: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3962: }
3963: $items=~s/\&$//;
3964: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
3965: }
3966:
3967: # --------------------------------------------------------- putstore interface
3968:
1.524 raeburn 3969: sub putstore {
1.715 albertel 3970: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 3971: if (!$udomain) { $udomain=$env{'user.domain'}; }
3972: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 3973: my $uhome=&homeserver($uname,$udomain);
3974: my $items='';
1.715 albertel 3975: foreach my $key (keys(%$storehash)) {
3976: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 3977: }
1.715 albertel 3978: $items=~s/\&$//;
1.716 albertel 3979: my $esc_symb=&escape($symb);
3980: my $esc_v=&escape($version);
1.715 albertel 3981: my $reply =
1.716 albertel 3982: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 3983: $uhome);
3984: if ($reply eq 'unknown_cmd') {
1.716 albertel 3985: # gfall back to way things use to be done
1.715 albertel 3986: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
3987: $uname);
1.524 raeburn 3988: }
1.715 albertel 3989: return $reply;
3990: }
3991:
3992: sub old_putstore {
1.716 albertel 3993: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3994: if (!$udomain) { $udomain=$env{'user.domain'}; }
3995: if (!$uname) { $uname=$env{'user.name'}; }
3996: my $uhome=&homeserver($uname,$udomain);
3997: my %newstorehash;
1.800 albertel 3998: foreach my $item (keys(%$storehash)) {
3999: my $key = $version.':'.&escape($symb).':'.$item;
4000: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4001: }
4002: my $items='';
4003: my %allitems = ();
1.800 albertel 4004: foreach my $item (keys(%newstorehash)) {
4005: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4006: my $key = $1.':keys:'.$2;
4007: $allitems{$key} .= $3.':';
4008: }
1.800 albertel 4009: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4010: }
1.800 albertel 4011: foreach my $item (keys(%allitems)) {
4012: $allitems{$item} =~ s/\:$//;
4013: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4014: }
4015: $items=~s/\&$//;
4016: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4017: }
4018:
1.47 www 4019: # ------------------------------------------------------ critical put interface
4020:
4021: sub cput {
1.134 albertel 4022: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4023: if (!$udomain) { $udomain=$env{'user.domain'}; }
4024: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4025: my $uhome=&homeserver($uname,$udomain);
1.47 www 4026: my $items='';
1.800 albertel 4027: foreach my $item (keys(%$storehash)) {
4028: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4029: }
1.47 www 4030: $items=~s/\&$//;
1.134 albertel 4031: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4032: }
4033:
4034: # -------------------------------------------------------------- eget interface
4035:
4036: sub eget {
1.133 albertel 4037: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4038: my $items='';
1.800 albertel 4039: foreach my $item (@$storearr) {
4040: $items.=&escape($item).'&';
1.191 harris41 4041: }
1.12 www 4042: $items=~s/\&$//;
1.620 albertel 4043: if (!$udomain) { $udomain=$env{'user.domain'}; }
4044: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4045: my $uhome=&homeserver($uname,$udomain);
4046: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4047: my @pairs=split(/\&/,$rep);
4048: my %returnhash=();
1.42 www 4049: my $i=0;
1.800 albertel 4050: foreach my $item (@$storearr) {
4051: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4052: $i++;
1.191 harris41 4053: }
1.12 www 4054: return %returnhash;
4055: }
4056:
1.667 albertel 4057: # ------------------------------------------------------------ tmpput interface
4058: sub tmpput {
1.802 raeburn 4059: my ($storehash,$server,$context)=@_;
1.667 albertel 4060: my $items='';
1.800 albertel 4061: foreach my $item (keys(%$storehash)) {
4062: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4063: }
4064: $items=~s/\&$//;
1.802 raeburn 4065: if (defined($context)) {
4066: $items .= ':'.&escape($context);
4067: }
1.667 albertel 4068: return &reply("tmpput:$items",$server);
4069: }
4070:
4071: # ------------------------------------------------------------ tmpget interface
4072: sub tmpget {
1.688 albertel 4073: my ($token,$server)=@_;
4074: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4075: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4076: my %returnhash;
4077: foreach my $item (split(/\&/,$rep)) {
4078: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4079: next if ($key =~ /^error: 2 /);
1.667 albertel 4080: $returnhash{&unescape($key)}=&thaw_unescape($value);
4081: }
4082: return %returnhash;
4083: }
4084:
1.688 albertel 4085: # ------------------------------------------------------------ tmpget interface
4086: sub tmpdel {
4087: my ($token,$server)=@_;
4088: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4089: return &reply("tmpdel:$token",$server);
4090: }
4091:
1.765 albertel 4092: # -------------------------------------------------- portfolio access checking
4093:
4094: sub portfolio_access {
1.766 albertel 4095: my ($requrl) = @_;
1.765 albertel 4096: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4097: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4098: if ($result) {
4099: my %setters;
4100: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4101: my ($startblock,$endblock) =
4102: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4103: if ($startblock && $endblock) {
4104: return 'B';
4105: }
4106: } else {
4107: my ($startblock,$endblock) =
4108: &Apache::loncommon::blockcheck(\%setters,'port');
4109: if ($startblock && $endblock) {
4110: return 'B';
4111: }
4112: }
4113: }
1.765 albertel 4114: if ($result eq 'ok') {
1.766 albertel 4115: return 'F';
1.765 albertel 4116: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4117: return 'A';
1.765 albertel 4118: }
1.766 albertel 4119: return '';
1.765 albertel 4120: }
4121:
4122: sub get_portfolio_access {
1.767 albertel 4123: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4124:
4125: if (!ref($access_hash)) {
4126: my $current_perms = &get_portfile_permissions($udom,$unum);
4127: my %access_controls = &get_access_controls($current_perms,$group,
4128: $file_name);
4129: $access_hash = $access_controls{$file_name};
4130: }
4131:
1.765 albertel 4132: my ($public,$guest,@domains,@users,@courses,@groups);
4133: my $now = time;
4134: if (ref($access_hash) eq 'HASH') {
4135: foreach my $key (keys(%{$access_hash})) {
4136: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4137: if ($start > $now) {
4138: next;
4139: }
4140: if ($end && $end<$now) {
4141: next;
4142: }
4143: if ($scope eq 'public') {
4144: $public = $key;
4145: last;
4146: } elsif ($scope eq 'guest') {
4147: $guest = $key;
4148: } elsif ($scope eq 'domains') {
4149: push(@domains,$key);
4150: } elsif ($scope eq 'users') {
4151: push(@users,$key);
4152: } elsif ($scope eq 'course') {
4153: push(@courses,$key);
4154: } elsif ($scope eq 'group') {
4155: push(@groups,$key);
4156: }
4157: }
4158: if ($public) {
4159: return 'ok';
4160: }
4161: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4162: if ($guest) {
4163: return $guest;
4164: }
4165: } else {
4166: if (@domains > 0) {
4167: foreach my $domkey (@domains) {
4168: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4169: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4170: return 'ok';
4171: }
4172: }
4173: }
4174: }
4175: if (@users > 0) {
4176: foreach my $userkey (@users) {
1.865 raeburn 4177: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4178: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4179: if (ref($item) eq 'HASH') {
4180: if (($item->{'uname'} eq $env{'user.name'}) &&
4181: ($item->{'udom'} eq $env{'user.domain'})) {
4182: return 'ok';
4183: }
4184: }
4185: }
4186: }
1.765 albertel 4187: }
4188: }
4189: my %roleshash;
4190: my @courses_and_groups = @courses;
4191: push(@courses_and_groups,@groups);
4192: if (@courses_and_groups > 0) {
4193: my (%allgroups,%allroles);
4194: my ($start,$end,$role,$sec,$group);
4195: foreach my $envkey (%env) {
1.811 albertel 4196: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4197: my $cid = $2.'_'.$3;
4198: if ($1 eq 'gr') {
4199: $group = $4;
4200: $allgroups{$cid}{$group} = $env{$envkey};
4201: } else {
4202: if ($4 eq '') {
4203: $sec = 'none';
4204: } else {
4205: $sec = $4;
4206: }
4207: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4208: }
1.811 albertel 4209: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4210: my $cid = $2.'_'.$3;
4211: if ($4 eq '') {
4212: $sec = 'none';
4213: } else {
4214: $sec = $4;
4215: }
4216: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4217: }
4218: }
4219: if (keys(%allroles) == 0) {
4220: return;
4221: }
4222: foreach my $key (@courses_and_groups) {
4223: my %content = %{$$access_hash{$key}};
4224: my $cnum = $content{'number'};
4225: my $cdom = $content{'domain'};
4226: my $cid = $cdom.'_'.$cnum;
4227: if (!exists($allroles{$cid})) {
4228: next;
4229: }
4230: foreach my $role_id (keys(%{$content{'roles'}})) {
4231: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4232: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4233: my @status = @{$content{'roles'}{$role_id}{'access'}};
4234: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4235: foreach my $role (keys(%{$allroles{$cid}})) {
4236: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4237: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4238: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4239: if (grep/^all$/,@sections) {
4240: return 'ok';
4241: } else {
4242: if (grep/^$sec$/,@sections) {
4243: return 'ok';
4244: }
4245: }
4246: }
4247: }
4248: if (keys(%{$allgroups{$cid}}) == 0) {
4249: if (grep/^none$/,@groups) {
4250: return 'ok';
4251: }
4252: } else {
4253: if (grep/^all$/,@groups) {
4254: return 'ok';
4255: }
4256: foreach my $group (keys(%{$allgroups{$cid}})) {
4257: if (grep/^$group$/,@groups) {
4258: return 'ok';
4259: }
4260: }
4261: }
4262: }
4263: }
4264: }
4265: }
4266: }
4267: if ($guest) {
4268: return $guest;
4269: }
4270: }
4271: }
4272: return;
4273: }
4274:
4275: sub course_group_datechecker {
4276: my ($dates,$now,$status) = @_;
4277: my ($start,$end) = split(/\./,$dates);
4278: if (!$start && !$end) {
4279: return 'ok';
4280: }
4281: if (grep/^active$/,@{$status}) {
4282: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4283: return 'ok';
4284: }
4285: }
4286: if (grep/^previous$/,@{$status}) {
4287: if ($end > $now ) {
4288: return 'ok';
4289: }
4290: }
4291: if (grep/^future$/,@{$status}) {
4292: if ($start > $now) {
4293: return 'ok';
4294: }
4295: }
4296: return;
4297: }
4298:
4299: sub parse_portfolio_url {
4300: my ($url) = @_;
4301:
4302: my ($type,$udom,$unum,$group,$file_name);
4303:
1.823 albertel 4304: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4305: $type = 1;
4306: $udom = $1;
4307: $unum = $2;
4308: $file_name = $3;
1.823 albertel 4309: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4310: $type = 2;
4311: $udom = $1;
4312: $unum = $2;
4313: $group = $3;
4314: $file_name = $3.'/'.$4;
4315: }
4316: if (wantarray) {
4317: return ($type,$udom,$unum,$file_name,$group);
4318: }
4319: return $type;
4320: }
4321:
4322: sub is_portfolio_url {
4323: my ($url) = @_;
4324: return scalar(&parse_portfolio_url($url));
4325: }
4326:
1.798 raeburn 4327: sub is_portfolio_file {
4328: my ($file) = @_;
1.820 raeburn 4329: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4330: return 1;
4331: }
4332: return;
4333: }
4334:
4335:
1.341 www 4336: # ---------------------------------------------- Custom access rule evaluation
4337:
4338: sub customaccess {
4339: my ($priv,$uri)=@_;
1.807 albertel 4340: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 4341: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 4342: $udom = &LONCAPA::clean_domain($udom);
4343: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 4344: my $access=0;
1.800 albertel 4345: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 4346: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4347: if ($type eq 'user') {
4348: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 4349: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 4350: if ($tdom) {
4351: if ($tdom ne $env{'user.domain'}) { next; }
4352: }
1.896 albertel 4353: if ($tuname) {
4354: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 4355: }
4356: $access=($effect eq 'allow');
4357: last;
4358: }
4359: } else {
4360: if ($role) {
4361: if ($role ne $urole) { next; }
4362: }
4363: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4364: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4365: if ($tdom) {
4366: if ($tdom ne $udom) { next; }
4367: }
4368: if ($tcrs) {
4369: if ($tcrs ne $ucrs) { next; }
4370: }
4371: if ($tsec) {
4372: if ($tsec ne $usec) { next; }
4373: }
4374: $access=($effect eq 'allow');
4375: last;
4376: }
4377: if ($realm eq '' && $role eq '') {
4378: $access=($effect eq 'allow');
4379: }
1.402 bowersj2 4380: }
1.341 www 4381: }
4382: return $access;
4383: }
4384:
1.103 harris41 4385: # ------------------------------------------------- Check for a user privilege
1.12 www 4386:
4387: sub allowed {
1.810 raeburn 4388: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 4389: my $ver_orguri=$uri;
1.439 www 4390: $uri=&deversion($uri);
1.152 www 4391: my $orguri=$uri;
1.52 www 4392: $uri=&declutter($uri);
1.809 raeburn 4393:
1.810 raeburn 4394: if ($priv eq 'evb') {
4395: # Evade communication block restrictions for specified role in a course
4396: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4397: return $1;
4398: } else {
4399: return;
4400: }
4401: }
4402:
1.620 albertel 4403: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 4404: # Free bre access to adm and meta resources
1.775 albertel 4405: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 4406: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4407: && ($priv eq 'bre')) {
1.14 www 4408: return 'F';
1.159 www 4409: }
4410:
1.545 banghart 4411: # Free bre access to user's own portfolio contents
1.714 raeburn 4412: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 4413: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 4414: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 4415: my %setters;
4416: my ($startblock,$endblock) =
4417: &Apache::loncommon::blockcheck(\%setters,'port');
4418: if ($startblock && $endblock) {
4419: return 'B';
4420: } else {
4421: return 'F';
4422: }
1.545 banghart 4423: }
4424:
1.762 raeburn 4425: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 4426: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
4427: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
4428: if (exists($env{'request.course.id'})) {
4429: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4430: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4431: if (($domain eq $cdom) && ($name eq $cnum)) {
4432: my $courseprivid=$env{'request.course.id'};
4433: $courseprivid=~s/\_/\//;
4434: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
4435: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
4436: return $1;
1.762 raeburn 4437: } else {
4438: if ($env{'request.course.sec'}) {
4439: $courseprivid.='/'.$env{'request.course.sec'};
4440: }
4441: if ($env{'user.priv.'.$env{'request.role'}.'./'.
4442: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
4443: return $2;
4444: }
1.714 raeburn 4445: }
4446: }
4447: }
4448: }
4449:
1.159 www 4450: # Free bre to public access
4451:
4452: if ($priv eq 'bre') {
1.238 www 4453: my $copyright=&metadata($uri,'copyright');
1.620 albertel 4454: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 4455: return 'F';
4456: }
1.238 www 4457: if ($copyright eq 'priv') {
4458: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4459: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 4460: return '';
4461: }
4462: }
4463: if ($copyright eq 'domain') {
4464: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 4465: unless (($env{'user.domain'} eq $1) ||
4466: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 4467: return '';
4468: }
1.262 matthew 4469: }
1.620 albertel 4470: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 4471: # Library role, so allow browsing of resources in this domain.
4472: return 'F';
1.238 www 4473: }
1.341 www 4474: if ($copyright eq 'custom') {
4475: unless (&customaccess($priv,$uri)) { return ''; }
4476: }
1.14 www 4477: }
1.264 matthew 4478: # Domain coordinator is trying to create a course
1.620 albertel 4479: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 4480: # uri is the requested domain in this case.
4481: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 4482: # a role of dc for the domain in question.
1.620 albertel 4483: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 4484: }
1.29 www 4485:
1.52 www 4486: my $thisallowed='';
4487: my $statecond=0;
4488: my $courseprivid='';
4489:
4490: # Course
4491:
1.620 albertel 4492: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4493: $thisallowed.=$1;
4494: }
1.29 www 4495:
1.52 www 4496: # Domain
4497:
1.620 albertel 4498: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 4499: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4500: $thisallowed.=$1;
4501: }
1.52 www 4502:
4503: # Course: uri itself is a course
1.66 www 4504: my $courseuri=$uri;
4505: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 4506: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 4507:
1.620 albertel 4508: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 4509: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 4510: $thisallowed.=$1;
4511: }
1.29 www 4512:
1.665 albertel 4513: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 4514: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 4515: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 4516: $thisallowed='';
1.671 raeburn 4517: my ($match)=&is_on_map($uri);
4518: if ($match) {
4519: if ($env{'user.priv.'.$env{'request.role'}.'./'}
4520: =~/\Q$priv\E\&([^\:]*)/) {
4521: $thisallowed.=$1;
4522: }
4523: } else {
1.705 albertel 4524: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 4525: if ($refuri) {
4526: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 4527: $thisallowed='F';
1.671 raeburn 4528: } else {
4529: $refuri=&declutter($refuri);
4530: my ($match) = &is_on_map($refuri);
4531: if ($match) {
4532: $thisallowed='F';
4533: }
1.669 raeburn 4534: }
1.671 raeburn 4535: }
4536: }
1.314 www 4537: }
1.492 albertel 4538:
1.766 albertel 4539: if ($priv eq 'bre'
4540: && $thisallowed ne 'F'
4541: && $thisallowed ne '2'
4542: && &is_portfolio_url($uri)) {
4543: $thisallowed = &portfolio_access($uri);
4544: }
4545:
1.52 www 4546: # Full access at system, domain or course-wide level? Exit.
1.29 www 4547: if ($thisallowed=~/F/) {
4548: return 'F';
4549: }
4550:
1.52 www 4551: # If this is generating or modifying users, exit with special codes
1.29 www 4552:
1.643 www 4553: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
4554: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 4555: my ($audom,$auname)=split('/',$uri);
1.643 www 4556: # no author name given, so this just checks on the general right to make a co-author in this domain
4557: unless ($auname) { return $thisallowed; }
4558: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 4559: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
4560: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
4561: ($audom ne $env{'request.role.domain'}))) { return ''; }
4562: }
1.52 www 4563: return $thisallowed;
4564: }
4565: #
1.103 harris41 4566: # Gathered so far: system, domain and course wide privileges
1.52 www 4567: #
4568: # Course: See if uri or referer is an individual resource that is part of
4569: # the course
4570:
1.620 albertel 4571: if ($env{'request.course.id'}) {
1.232 www 4572:
1.620 albertel 4573: $courseprivid=$env{'request.course.id'};
4574: if ($env{'request.course.sec'}) {
4575: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 4576: }
4577: $courseprivid=~s/\_/\//;
4578: my $checkreferer=1;
1.232 www 4579: my ($match,$cond)=&is_on_map($uri);
4580: if ($match) {
4581: $statecond=$cond;
1.620 albertel 4582: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4583: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4584: $thisallowed.=$1;
4585: $checkreferer=0;
4586: }
1.29 www 4587: }
1.83 www 4588:
1.148 www 4589: if ($checkreferer) {
1.620 albertel 4590: my $refuri=$env{'httpref.'.$orguri};
1.148 www 4591: unless ($refuri) {
1.800 albertel 4592: foreach my $key (keys(%env)) {
4593: if ($key=~/^httpref\..*\*/) {
4594: my $pattern=$key;
1.156 www 4595: $pattern=~s/^httpref\.\/res\///;
1.148 www 4596: $pattern=~s/\*/\[\^\/\]\+/g;
4597: $pattern=~s/\//\\\//g;
1.152 www 4598: if ($orguri=~/$pattern/) {
1.800 albertel 4599: $refuri=$env{$key};
1.148 www 4600: }
4601: }
1.191 harris41 4602: }
1.148 www 4603: }
1.232 www 4604:
1.148 www 4605: if ($refuri) {
1.152 www 4606: $refuri=&declutter($refuri);
1.232 www 4607: my ($match,$cond)=&is_on_map($refuri);
4608: if ($match) {
4609: my $refstatecond=$cond;
1.620 albertel 4610: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4611: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4612: $thisallowed.=$1;
1.53 www 4613: $uri=$refuri;
4614: $statecond=$refstatecond;
1.52 www 4615: }
4616: }
1.148 www 4617: }
1.29 www 4618: }
1.52 www 4619: }
1.29 www 4620:
1.52 www 4621: #
1.103 harris41 4622: # Gathered now: all privileges that could apply, and condition number
1.52 www 4623: #
4624: #
4625: # Full or no access?
4626: #
1.29 www 4627:
1.52 www 4628: if ($thisallowed=~/F/) {
4629: return 'F';
4630: }
1.29 www 4631:
1.52 www 4632: unless ($thisallowed) {
4633: return '';
4634: }
1.29 www 4635:
1.52 www 4636: # Restrictions exist, deal with them
4637: #
4638: # C:according to course preferences
4639: # R:according to resource settings
4640: # L:unless locked
4641: # X:according to user session state
4642: #
4643:
4644: # Possibly locked functionality, check all courses
1.54 www 4645: # Locks might take effect only after 10 minutes cache expiration for other
4646: # courses, and 2 minutes for current course
1.52 www 4647:
4648: my $envkey;
4649: if ($thisallowed=~/L/) {
1.620 albertel 4650: foreach $envkey (keys %env) {
1.54 www 4651: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
4652: my $courseid=$2;
4653: my $roleid=$1.'.'.$2;
1.92 www 4654: $courseid=~s/^\///;
1.54 www 4655: my $expiretime=600;
1.620 albertel 4656: if ($env{'request.role'} eq $roleid) {
1.54 www 4657: $expiretime=120;
4658: }
4659: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
4660: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 4661: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 4662: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 4663: }
1.620 albertel 4664: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
4665: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
4666: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
4667: &log($env{'user.domain'},$env{'user.name'},
4668: $env{'user.home'},
1.57 www 4669: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 4670: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4671: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4672: return '';
4673: }
4674: }
1.620 albertel 4675: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
4676: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
4677: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
4678: &log($env{'user.domain'},$env{'user.name'},
4679: $env{'user.home'},
1.57 www 4680: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 4681: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4682: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4683: return '';
4684: }
4685: }
4686: }
1.29 www 4687: }
1.52 www 4688: }
4689:
4690: #
4691: # Rest of the restrictions depend on selected course
4692: #
4693:
1.620 albertel 4694: unless ($env{'request.course.id'}) {
1.766 albertel 4695: if ($thisallowed eq 'A') {
4696: return 'A';
1.814 raeburn 4697: } elsif ($thisallowed eq 'B') {
4698: return 'B';
1.766 albertel 4699: } else {
4700: return '1';
4701: }
1.52 www 4702: }
1.29 www 4703:
1.52 www 4704: #
4705: # Now user is definitely in a course
4706: #
1.53 www 4707:
4708:
4709: # Course preferences
4710:
4711: if ($thisallowed=~/C/) {
1.620 albertel 4712: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4713: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
4714: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 4715: =~/\Q$rolecode\E/) {
1.689 albertel 4716: if ($priv ne 'pch') {
4717: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4718: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
4719: $env{'request.course.id'});
4720: }
1.237 www 4721: return '';
4722: }
4723:
1.620 albertel 4724: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 4725: =~/\Q$unamedom\E/) {
1.689 albertel 4726: if ($priv ne 'pch') {
4727: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
4728: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
4729: $env{'request.course.id'});
4730: }
1.54 www 4731: return '';
4732: }
1.53 www 4733: }
4734:
4735: # Resource preferences
4736:
4737: if ($thisallowed=~/R/) {
1.620 albertel 4738: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 4739: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 4740: if ($priv ne 'pch') {
4741: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4742: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
4743: }
4744: return '';
1.54 www 4745: }
1.53 www 4746: }
1.30 www 4747:
1.246 www 4748: # Restricted by state or randomout?
1.30 www 4749:
1.52 www 4750: if ($thisallowed=~/X/) {
1.620 albertel 4751: if ($env{'acc.randomout'}) {
1.579 albertel 4752: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 4753: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 4754: return '';
4755: }
1.247 www 4756: }
4757: if (&condval($statecond)) {
1.52 www 4758: return '2';
4759: } else {
4760: return '';
4761: }
4762: }
1.30 www 4763:
1.766 albertel 4764: if ($thisallowed eq 'A') {
4765: return 'A';
1.814 raeburn 4766: } elsif ($thisallowed eq 'B') {
4767: return 'B';
1.766 albertel 4768: }
1.52 www 4769: return 'F';
1.232 www 4770: }
4771:
1.710 albertel 4772: sub split_uri_for_cond {
4773: my $uri=&deversion(&declutter(shift));
4774: my @uriparts=split(/\//,$uri);
4775: my $filename=pop(@uriparts);
4776: my $pathname=join('/',@uriparts);
4777: return ($pathname,$filename);
4778: }
1.232 www 4779: # --------------------------------------------------- Is a resource on the map?
4780:
4781: sub is_on_map {
1.710 albertel 4782: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 4783: #Trying to find the conditional for the file
1.620 albertel 4784: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 4785: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 4786: if ($match) {
1.289 bowersj2 4787: return (1,$1);
4788: } else {
1.434 www 4789: return (0,0);
1.289 bowersj2 4790: }
1.12 www 4791: }
4792:
1.427 www 4793: # --------------------------------------------------------- Get symb from alias
4794:
4795: sub get_symb_from_alias {
4796: my $symb=shift;
4797: my ($map,$resid,$url)=&decode_symb($symb);
4798: # Already is a symb
4799: if ($url) { return $symb; }
4800: # Must be an alias
4801: my $aliassymb='';
4802: my %bighash;
1.620 albertel 4803: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 4804: &GDBM_READER(),0640)) {
4805: my $rid=$bighash{'mapalias_'.$symb};
4806: if ($rid) {
4807: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 4808: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
4809: $resid,$bighash{'src_'.$rid});
1.427 www 4810: }
4811: untie %bighash;
4812: }
4813: return $aliassymb;
4814: }
4815:
1.12 www 4816: # ----------------------------------------------------------------- Define Role
4817:
4818: sub definerole {
4819: if (allowed('mcr','/')) {
4820: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 4821: foreach my $role (split(':',$sysrole)) {
4822: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4823: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
4824: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
4825: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4826: return "refused:s:$crole&$cqual";
4827: }
4828: }
1.191 harris41 4829: }
1.800 albertel 4830: foreach my $role (split(':',$domrole)) {
4831: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4832: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
4833: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
4834: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 4835: return "refused:d:$crole&$cqual";
4836: }
4837: }
1.191 harris41 4838: }
1.800 albertel 4839: foreach my $role (split(':',$courole)) {
4840: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4841: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
4842: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
4843: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4844: return "refused:c:$crole&$cqual";
4845: }
4846: }
1.191 harris41 4847: }
1.620 albertel 4848: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4849: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 4850: "rolesdef_$rolename=".
4851: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 4852: return reply($command,$env{'user.home'});
1.12 www 4853: } else {
4854: return 'refused';
4855: }
1.105 harris41 4856: }
4857:
4858: # ---------------- Make a metadata query against the network of library servers
4859:
4860: sub metadata_query {
1.244 matthew 4861: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 4862: my %rhash;
1.845 albertel 4863: my %libserv = &all_library();
1.244 matthew 4864: my @server_list = (defined($server_array) ? @$server_array
4865: : keys(%libserv) );
4866: for my $server (@server_list) {
1.118 harris41 4867: unless ($custom or $customshow) {
4868: my $reply=&reply("querysend:".&escape($query),$server);
4869: $rhash{$server}=$reply;
4870: }
4871: else {
4872: my $reply=&reply("querysend:".&escape($query).':'.
4873: &escape($custom).':'.&escape($customshow),
4874: $server);
4875: $rhash{$server}=$reply;
4876: }
1.112 harris41 4877: }
1.118 harris41 4878: return \%rhash;
1.240 www 4879: }
4880:
4881: # ----------------------------------------- Send log queries and wait for reply
4882:
4883: sub log_query {
4884: my ($uname,$udom,$query,%filters)=@_;
4885: my $uhome=&homeserver($uname,$udom);
4886: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 4887: my $uhost=&hostname($uhome);
1.800 albertel 4888: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 4889: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
4890: $uhome);
1.479 albertel 4891: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 4892: return get_query_reply($queryid);
4893: }
4894:
1.818 raeburn 4895: # -------------------------- Update MySQL table for portfolio file
4896:
4897: sub update_portfolio_table {
1.821 raeburn 4898: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 ! raeburn 4899: if ($group ne '') {
! 4900: $file_name =~s /^\Q$group\E//;
! 4901: }
1.818 raeburn 4902: my $homeserver = &homeserver($uname,$udom);
4903: my $queryid=
1.821 raeburn 4904: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
4905: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 4906: my $reply = &get_query_reply($queryid);
4907: return $reply;
4908: }
4909:
1.899 raeburn 4910: # -------------------------- Update MySQL allusers table
4911:
4912: sub update_allusers_table {
4913: my ($uname,$udom,$names) = @_;
4914: my $homeserver = &homeserver($uname,$udom);
4915: my $queryid=
4916: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
4917: 'lastname='.&escape($names->{'lastname'}).'%%'.
4918: 'firstname='.&escape($names->{'firstname'}).'%%'.
4919: 'middlename='.&escape($names->{'middlename'}).'%%'.
4920: 'generation='.&escape($names->{'generation'}).'%%'.
4921: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
4922: 'id='.&escape($names->{'id'}),$homeserver);
4923: my $reply = &get_query_reply($queryid);
4924: return $reply;
4925: }
4926:
1.508 raeburn 4927: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 4928:
4929: sub fetch_enrollment_query {
1.511 raeburn 4930: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 4931: my $homeserver;
1.547 raeburn 4932: my $maxtries = 1;
1.508 raeburn 4933: if ($context eq 'automated') {
4934: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 4935: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 4936: } else {
4937: $homeserver = &homeserver($cnum,$dom);
4938: }
1.838 albertel 4939: my $host=&hostname($homeserver);
1.506 raeburn 4940: my $cmd = '';
1.800 albertel 4941: foreach my $affiliate (keys %{$affiliatesref}) {
4942: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 4943: }
4944: $cmd =~ s/%%$//;
4945: $cmd = &escape($cmd);
4946: my $query = 'fetchenrollment';
1.620 albertel 4947: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 4948: unless ($queryid=~/^\Q$host\E\_/) {
4949: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
4950: return 'error: '.$queryid;
4951: }
1.506 raeburn 4952: my $reply = &get_query_reply($queryid);
1.547 raeburn 4953: my $tries = 1;
4954: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4955: $reply = &get_query_reply($queryid);
4956: $tries ++;
4957: }
1.526 raeburn 4958: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 4959: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 4960: } else {
1.901 albertel 4961: my @responses = split(/:/,$reply);
1.515 raeburn 4962: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 4963: foreach my $line (@responses) {
4964: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 4965: $$replyref{$key} = $value;
4966: }
4967: } else {
1.506 raeburn 4968: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 4969: foreach my $line (@responses) {
4970: my ($key,$value) = split(/=/,$line);
1.506 raeburn 4971: $$replyref{$key} = $value;
4972: if ($value > 0) {
1.800 albertel 4973: foreach my $item (@{$$affiliatesref{$key}}) {
4974: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 4975: my $destname = $pathname.'/'.$filename;
4976: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 4977: if ($xml_classlist =~ /^error/) {
4978: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
4979: } else {
1.506 raeburn 4980: if ( open(FILE,">$destname") ) {
4981: print FILE &unescape($xml_classlist);
4982: close(FILE);
1.526 raeburn 4983: } else {
4984: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 4985: }
4986: }
4987: }
4988: }
4989: }
4990: }
4991: return 'ok';
4992: }
4993: return 'error';
4994: }
4995:
1.242 www 4996: sub get_query_reply {
4997: my $queryid=shift;
1.240 www 4998: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
4999: my $reply='';
5000: for (1..100) {
5001: sleep 2;
5002: if (-e $replyfile.'.end') {
1.448 albertel 5003: if (open(my $fh,$replyfile)) {
1.904 albertel 5004: $reply = join('',<$fh>);
5005: close($fh);
1.240 www 5006: } else { return 'error: reply_file_error'; }
1.242 www 5007: return &unescape($reply);
5008: }
1.240 www 5009: }
1.242 www 5010: return 'timeout:'.$queryid;
1.240 www 5011: }
5012:
5013: sub courselog_query {
1.241 www 5014: #
5015: # possible filters:
5016: # url: url or symb
5017: # username
5018: # domain
5019: # action: view, submit, grade
5020: # start: timestamp
5021: # end: timestamp
5022: #
1.240 www 5023: my (%filters)=@_;
1.620 albertel 5024: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5025: if ($filters{'url'}) {
5026: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5027: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5028: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5029: }
1.620 albertel 5030: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5031: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5032: return &log_query($cname,$cdom,'courselog',%filters);
5033: }
5034:
5035: sub userlog_query {
1.858 raeburn 5036: #
5037: # possible filters:
5038: # action: log check role
5039: # start: timestamp
5040: # end: timestamp
5041: #
1.240 www 5042: my ($uname,$udom,%filters)=@_;
5043: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5044: }
5045:
1.506 raeburn 5046: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5047:
5048: sub auto_run {
1.508 raeburn 5049: my ($cnum,$cdom) = @_;
1.876 raeburn 5050: my $response = 0;
5051: my $settings;
5052: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5053: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5054: $settings = $domconfig{'autoenroll'};
5055: if ($settings->{'run'} eq '1') {
5056: $response = 1;
5057: }
5058: } else {
1.934 raeburn 5059: my $homeserver;
5060: if (&is_course($cdom,$cnum)) {
5061: $homeserver = &homeserver($cnum,$cdom);
5062: } else {
5063: $homeserver = &domain($cdom,'primary');
5064: }
5065: if ($homeserver ne 'no_host') {
5066: $response = &reply('autorun:'.$cdom,$homeserver);
5067: }
1.876 raeburn 5068: }
1.506 raeburn 5069: return $response;
5070: }
1.776 albertel 5071:
1.506 raeburn 5072: sub auto_get_sections {
1.508 raeburn 5073: my ($cnum,$cdom,$inst_coursecode) = @_;
5074: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 5075: my @secs = ();
1.511 raeburn 5076: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 5077: unless ($response eq 'refused') {
1.901 albertel 5078: @secs = split(/:/,$response);
1.506 raeburn 5079: }
5080: return @secs;
5081: }
1.776 albertel 5082:
1.506 raeburn 5083: sub auto_new_course {
1.508 raeburn 5084: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5085: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5086: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5087: return $response;
5088: }
1.776 albertel 5089:
1.506 raeburn 5090: sub auto_validate_courseID {
1.508 raeburn 5091: my ($cnum,$cdom,$inst_course_id) = @_;
5092: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5093: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5094: return $response;
5095: }
1.776 albertel 5096:
1.506 raeburn 5097: sub auto_create_password {
1.873 raeburn 5098: my ($cnum,$cdom,$authparam,$udom) = @_;
5099: my ($homeserver,$response);
1.506 raeburn 5100: my $create_passwd = 0;
5101: my $authchk = '';
1.873 raeburn 5102: if ($udom =~ /^$match_domain$/) {
5103: $homeserver = &domain($udom,'primary');
5104: }
5105: if ($homeserver eq '') {
5106: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5107: $homeserver = &homeserver($cnum,$cdom);
5108: }
5109: }
5110: if ($homeserver eq '') {
5111: $authchk = 'nodomain';
1.506 raeburn 5112: } else {
1.873 raeburn 5113: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5114: if ($response eq 'refused') {
5115: $authchk = 'refused';
5116: } else {
1.901 albertel 5117: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 5118: }
1.506 raeburn 5119: }
5120: return ($authparam,$create_passwd,$authchk);
5121: }
5122:
1.706 raeburn 5123: sub auto_photo_permission {
5124: my ($cnum,$cdom,$students) = @_;
5125: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 5126: my ($outcome,$perm_reqd,$conditions) =
5127: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 5128: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5129: return (undef,undef);
5130: }
1.706 raeburn 5131: return ($outcome,$perm_reqd,$conditions);
5132: }
5133:
5134: sub auto_checkphotos {
5135: my ($uname,$udom,$pid) = @_;
5136: my $homeserver = &homeserver($uname,$udom);
5137: my ($result,$resulttype);
5138: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 5139: &escape($uname).':'.&escape($pid),
5140: $homeserver));
1.709 albertel 5141: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5142: return (undef,undef);
5143: }
1.706 raeburn 5144: if ($outcome) {
5145: ($result,$resulttype) = split(/:/,$outcome);
5146: }
5147: return ($result,$resulttype);
5148: }
5149:
5150: sub auto_photochoice {
5151: my ($cnum,$cdom) = @_;
5152: my $homeserver = &homeserver($cnum,$cdom);
5153: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 5154: &escape($cdom),
5155: $homeserver)));
1.709 albertel 5156: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5157: return (undef,undef);
5158: }
1.706 raeburn 5159: return ($update,$comment);
5160: }
5161:
5162: sub auto_photoupdate {
5163: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5164: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 5165: my $host=&hostname($homeserver);
1.706 raeburn 5166: my $cmd = '';
5167: my $maxtries = 1;
1.800 albertel 5168: foreach my $affiliate (keys(%{$affiliatesref})) {
5169: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 5170: }
5171: $cmd =~ s/%%$//;
5172: $cmd = &escape($cmd);
5173: my $query = 'institutionalphotos';
5174: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5175: unless ($queryid=~/^\Q$host\E\_/) {
5176: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5177: return 'error: '.$queryid;
5178: }
5179: my $reply = &get_query_reply($queryid);
5180: my $tries = 1;
5181: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5182: $reply = &get_query_reply($queryid);
5183: $tries ++;
5184: }
5185: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5186: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5187: } else {
5188: my @responses = split(/:/,$reply);
5189: my $outcome = shift(@responses);
5190: foreach my $item (@responses) {
5191: my ($key,$value) = split(/=/,$item);
5192: $$photo{$key} = $value;
5193: }
5194: return $outcome;
5195: }
5196: return 'error';
5197: }
5198:
1.521 raeburn 5199: sub auto_instcode_format {
1.793 albertel 5200: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5201: $cat_order) = @_;
1.521 raeburn 5202: my $courses = '';
1.772 raeburn 5203: my @homeservers;
1.521 raeburn 5204: if ($caller eq 'global') {
1.841 albertel 5205: my %servers = &get_servers($codedom,'library');
5206: foreach my $tryserver (keys(%servers)) {
5207: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5208: push(@homeservers,$tryserver);
5209: }
1.584 raeburn 5210: }
1.521 raeburn 5211: } else {
1.772 raeburn 5212: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 5213: }
1.793 albertel 5214: foreach my $code (keys(%{$instcodes})) {
5215: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 5216: }
5217: chop($courses);
1.772 raeburn 5218: my $ok_response = 0;
5219: my $response;
5220: while (@homeservers > 0 && $ok_response == 0) {
5221: my $server = shift(@homeservers);
5222: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5223: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5224: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 5225: split(/:/,$response);
1.772 raeburn 5226: %{$codes} = (%{$codes},&str2hash($codes_str));
5227: push(@{$codetitles},&str2array($codetitles_str));
5228: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5229: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5230: $ok_response = 1;
5231: }
5232: }
5233: if ($ok_response) {
1.521 raeburn 5234: return 'ok';
1.772 raeburn 5235: } else {
5236: return $response;
1.521 raeburn 5237: }
5238: }
5239:
1.792 raeburn 5240: sub auto_instcode_defaults {
5241: my ($domain,$returnhash,$code_order) = @_;
5242: my @homeservers;
1.841 albertel 5243:
5244: my %servers = &get_servers($domain,'library');
5245: foreach my $tryserver (keys(%servers)) {
5246: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5247: push(@homeservers,$tryserver);
5248: }
1.792 raeburn 5249: }
1.841 albertel 5250:
1.792 raeburn 5251: my $response;
1.841 albertel 5252: foreach my $server (@homeservers) {
1.792 raeburn 5253: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 5254: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5255:
5256: foreach my $pair (split(/\&/,$response)) {
5257: my ($name,$value)=split(/\=/,$pair);
5258: if ($name eq 'code_order') {
5259: @{$code_order} = split(/\&/,&unescape($value));
5260: } else {
5261: $returnhash->{&unescape($name)}=&unescape($value);
5262: }
5263: }
5264: return 'ok';
1.792 raeburn 5265: }
1.841 albertel 5266:
5267: return $response;
1.792 raeburn 5268: }
5269:
1.777 albertel 5270: sub auto_validate_class_sec {
1.918 raeburn 5271: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 5272: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 5273: my $ownerlist;
5274: if (ref($owners) eq 'ARRAY') {
5275: $ownerlist = join(',',@{$owners});
5276: } else {
5277: $ownerlist = $owners;
5278: }
1.773 raeburn 5279: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 5280: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 5281: return $response;
5282: }
5283:
1.679 raeburn 5284: # ------------------------------------------------------- Course Group routines
5285:
5286: sub get_coursegroups {
1.809 raeburn 5287: my ($cdom,$cnum,$group,$namespace) = @_;
5288: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 5289: }
5290:
1.679 raeburn 5291: sub modify_coursegroup {
5292: my ($cdom,$cnum,$groupsettings) = @_;
5293: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
5294: }
5295:
1.809 raeburn 5296: sub toggle_coursegroup_status {
5297: my ($cdom,$cnum,$group,$action) = @_;
5298: my ($from_namespace,$to_namespace);
5299: if ($action eq 'delete') {
5300: $from_namespace = 'coursegroups';
5301: $to_namespace = 'deleted_groups';
5302: } else {
5303: $from_namespace = 'deleted_groups';
5304: $to_namespace = 'coursegroups';
5305: }
5306: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 5307: if (my $tmp = &error(%curr_group)) {
5308: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
5309: return ('read error',$tmp);
5310: } else {
5311: my %savedsettings = %curr_group;
1.809 raeburn 5312: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 5313: my $deloutcome;
5314: if ($result eq 'ok') {
1.809 raeburn 5315: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 5316: } else {
5317: return ('write error',$result);
5318: }
5319: if ($deloutcome eq 'ok') {
5320: return 'ok';
5321: } else {
5322: return ('delete error',$deloutcome);
5323: }
5324: }
5325: }
5326:
1.679 raeburn 5327: sub modify_group_roles {
1.957 raeburn 5328: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 5329: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
5330: my $role = 'gr/'.&escape($userprivs);
5331: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 5332: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 5333: if ($result eq 'ok') {
5334: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
5335: }
1.679 raeburn 5336: return $result;
5337: }
5338:
5339: sub modify_coursegroup_membership {
5340: my ($cdom,$cnum,$membership) = @_;
5341: my $result = &put('groupmembership',$membership,$cdom,$cnum);
5342: return $result;
5343: }
5344:
1.682 raeburn 5345: sub get_active_groups {
5346: my ($udom,$uname,$cdom,$cnum) = @_;
5347: my $now = time;
5348: my %groups = ();
5349: foreach my $key (keys(%env)) {
1.811 albertel 5350: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 5351: my ($start,$end) = split(/\./,$env{$key});
5352: if (($end!=0) && ($end<$now)) { next; }
5353: if (($start!=0) && ($start>$now)) { next; }
5354: if ($1 eq $cdom && $2 eq $cnum) {
5355: $groups{$3} = $env{$key} ;
5356: }
5357: }
5358: }
5359: return %groups;
5360: }
5361:
1.683 raeburn 5362: sub get_group_membership {
5363: my ($cdom,$cnum,$group) = @_;
5364: return(&dump('groupmembership',$cdom,$cnum,$group));
5365: }
5366:
5367: sub get_users_groups {
5368: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 5369: my @usersgroups;
1.683 raeburn 5370: my $cachetime=1800;
5371:
5372: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 5373: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
5374: if (defined($cached)) {
1.734 albertel 5375: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 5376: } else {
5377: $grouplist = '';
1.816 raeburn 5378: my $courseurl = &courseid_to_courseurl($courseid);
5379: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 5380: my $access_end = $env{'course.'.$courseid.
5381: '.default_enrollment_end_date'};
5382: my $now = time;
5383: foreach my $key (keys(%roleshash)) {
5384: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
5385: my $group = $1;
5386: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
5387: my $start = $2;
5388: my $end = $1;
5389: if ($start == -1) { next; } # deleted from group
5390: if (($start!=0) && ($start>$now)) { next; }
5391: if (($end!=0) && ($end<$now)) {
5392: if ($access_end && $access_end < $now) {
5393: if ($access_end - $end < 86400) {
5394: push(@usersgroups,$group);
1.733 raeburn 5395: }
5396: }
1.817 raeburn 5397: next;
1.733 raeburn 5398: }
1.817 raeburn 5399: push(@usersgroups,$group);
1.683 raeburn 5400: }
5401: }
5402: }
1.817 raeburn 5403: @usersgroups = &sort_course_groups($courseid,@usersgroups);
5404: $grouplist = join(':',@usersgroups);
5405: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 5406: }
1.733 raeburn 5407: return @usersgroups;
1.683 raeburn 5408: }
5409:
5410: sub devalidate_getgroups_cache {
5411: my ($udom,$uname,$cdom,$cnum)=@_;
5412: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 5413:
1.683 raeburn 5414: my $hashid="$udom:$uname:$courseid";
5415: &devalidate_cache_new('getgroups',$hashid);
5416: }
5417:
1.12 www 5418: # ------------------------------------------------------------------ Plain Text
5419:
5420: sub plaintext {
1.742 raeburn 5421: my ($short,$type,$cid) = @_;
1.758 albertel 5422: if ($short =~ /^cr/) {
5423: return (split('/',$short))[-1];
5424: }
1.742 raeburn 5425: if (!defined($cid)) {
5426: $cid = $env{'request.course.id'};
5427: }
5428: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
5429: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
5430: '.plaintext'});
5431: }
5432: my %rolenames = (
5433: Course => 'std',
5434: Group => 'alt1',
5435: );
5436: if (defined($type) &&
5437: defined($rolenames{$type}) &&
5438: defined($prp{$short}{$rolenames{$type}})) {
5439: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
5440: } else {
5441: return &Apache::lonlocal::mt($prp{$short}{'std'});
5442: }
1.12 www 5443: }
5444:
5445: # ----------------------------------------------------------------- Assign Role
5446:
5447: sub assignrole {
1.957 raeburn 5448: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
5449: $context)=@_;
1.21 www 5450: my $mrole;
5451: if ($role =~ /^cr\//) {
1.393 www 5452: my $cwosec=$url;
1.811 albertel 5453: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 5454: unless (&allowed('ccr',$cwosec)) {
1.104 www 5455: &logthis('Refused custom assignrole: '.
5456: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 5457: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 5458: return 'refused';
5459: }
1.21 www 5460: $mrole='cr';
1.678 raeburn 5461: } elsif ($role =~ /^gr\//) {
5462: my $cwogrp=$url;
1.811 albertel 5463: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 5464: unless (&allowed('mdg',$cwogrp)) {
5465: &logthis('Refused group assignrole: '.
5466: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
5467: $env{'user.name'}.' at '.$env{'user.domain'});
5468: return 'refused';
5469: }
5470: $mrole='gr';
1.21 www 5471: } else {
1.82 www 5472: my $cwosec=$url;
1.811 albertel 5473: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 5474: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
5475: my $refused;
5476: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
5477: if (!(&allowed('c'.$role,$url))) {
5478: $refused = 1;
5479: }
5480: } else {
5481: $refused = 1;
5482: }
1.947 raeburn 5483: if ($refused) {
5484: if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5485: $refused = '';
5486: } else {
5487: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
5488: ' '.$role.' '.$end.' '.$start.' by '.
5489: $env{'user.name'}.' at '.$env{'user.domain'});
5490: return 'refused';
5491: }
1.932 raeburn 5492: }
1.104 www 5493: }
1.21 www 5494: $mrole=$role;
5495: }
1.620 albertel 5496: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5497: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 5498: if ($end) { $command.='_'.$end; }
1.21 www 5499: if ($start) {
5500: if ($end) {
1.81 www 5501: $command.='_'.$start;
1.21 www 5502: } else {
1.81 www 5503: $command.='_0_'.$start;
1.21 www 5504: }
5505: }
1.739 raeburn 5506: my $origstart = $start;
5507: my $origend = $end;
1.957 raeburn 5508: my $delflag;
1.357 www 5509: # actually delete
5510: if ($deleteflag) {
1.373 www 5511: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 5512: # modify command to delete the role
1.620 albertel 5513: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 5514: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 5515: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 5516: # set start and finish to negative values for userrolelog
5517: $start=-1;
5518: $end=-1;
1.957 raeburn 5519: $delflag = 1;
1.357 www 5520: }
5521: }
5522: # send command
1.349 www 5523: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 5524: # log new user role if status is ok
1.349 www 5525: if ($answer eq 'ok') {
1.663 raeburn 5526: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 5527: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 5528: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 5529: unless ($role =~ /^gr/) {
5530: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 5531: $origstart,$selfenroll,$context);
1.739 raeburn 5532: }
1.349 www 5533: }
5534: return $answer;
1.169 harris41 5535: }
5536:
5537: # -------------------------------------------------- Modify user authentication
1.197 www 5538: # Overrides without validation
5539:
1.169 harris41 5540: sub modifyuserauth {
5541: my ($udom,$uname,$umode,$upass)=@_;
5542: my $uhome=&homeserver($uname,$udom);
1.197 www 5543: unless (&allowed('mau',$udom)) { return 'refused'; }
5544: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 5545: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5546: ' in domain '.$env{'request.role.domain'});
1.169 harris41 5547: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
5548: &escape($upass),$uhome);
1.620 albertel 5549: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 5550: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
5551: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
5552: &log($udom,,$uname,$uhome,
1.620 albertel 5553: 'Authentication changed by '.$env{'user.domain'}.', '.
5554: $env{'user.name'}.', '.$umode.
1.197 www 5555: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 5556: unless ($reply eq 'ok') {
1.197 www 5557: &logthis('Authentication mode error: '.$reply);
1.169 harris41 5558: return 'error: '.$reply;
5559: }
1.170 harris41 5560: return 'ok';
1.80 www 5561: }
5562:
1.81 www 5563: # --------------------------------------------------------------- Modify a user
1.80 www 5564:
1.81 www 5565: sub modifyuser {
1.206 matthew 5566: my ($udom, $uname, $uid,
5567: $umode, $upass, $first,
5568: $middle, $last, $gene,
1.963 raeburn 5569: $forceid, $desiredhome, $email, $inststatus)=@_;
1.807 albertel 5570: $udom= &LONCAPA::clean_domain($udom);
5571: $uname=&LONCAPA::clean_username($uname);
1.81 www 5572: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 5573: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 5574: $last.', '.$gene.'(forceid: '.$forceid.')'.
5575: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
5576: ' desiredhome not specified').
1.620 albertel 5577: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5578: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 5579: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 5580: # ----------------------------------------------------------------- Create User
1.406 albertel 5581: if (($uhome eq 'no_host') &&
5582: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 5583: my $unhome='';
1.844 albertel 5584: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 5585: $unhome = $desiredhome;
1.620 albertel 5586: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
5587: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 5588: } else { # load balancing routine for determining $unhome
1.81 www 5589: my $loadm=10000000;
1.841 albertel 5590: my %servers = &get_servers($udom,'library');
5591: foreach my $tryserver (keys(%servers)) {
5592: my $answer=reply('load',$tryserver);
5593: if (($answer=~/\d+/) && ($answer<$loadm)) {
5594: $loadm=$answer;
5595: $unhome=$tryserver;
5596: }
1.80 www 5597: }
5598: }
5599: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 5600: return 'error: unable to find a home server for '.$uname.
5601: ' in domain '.$udom;
1.80 www 5602: }
5603: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
5604: &escape($upass),$unhome);
5605: unless ($reply eq 'ok') {
5606: return 'error: '.$reply;
5607: }
1.230 stredwic 5608: $uhome=&homeserver($uname,$udom,'true');
1.80 www 5609: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 5610: return 'error: unable verify users home machine.';
1.80 www 5611: }
1.209 matthew 5612: } # End of creation of new user
1.80 www 5613: # ---------------------------------------------------------------------- Add ID
5614: if ($uid) {
5615: $uid=~tr/A-Z/a-z/;
5616: my %uidhash=&idrget($udom,$uname);
1.196 www 5617: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
5618: && (!$forceid)) {
1.80 www 5619: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 5620: return 'error: user id "'.$uid.'" does not match '.
5621: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 5622: }
5623: } else {
5624: &idput($udom,($uname => $uid));
5625: }
5626: }
5627: # -------------------------------------------------------------- Add names, etc
1.313 matthew 5628: my @tmp=&get('environment',
1.899 raeburn 5629: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 5630: 'permanentemail','inststatus'],
1.134 albertel 5631: $udom,$uname);
1.313 matthew 5632: my %names;
5633: if ($tmp[0] =~ m/^error:.*/) {
5634: %names=();
5635: } else {
5636: %names = @tmp;
5637: }
1.388 www 5638: #
5639: # Make sure to not trash student environment if instructor does not bother
5640: # to supply name and email information
5641: #
5642: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 5643: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 5644: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 5645: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 5646: if ($email) {
5647: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 5648: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 5649: }
1.899 raeburn 5650: if ($uid) { $names{'id'} = $uid; }
1.963 raeburn 5651: if (defined($inststatus)) { $names{'inststatus'} = $inststatus; }
1.134 albertel 5652: my $reply = &put('environment', \%names, $udom,$uname);
5653: if ($reply ne 'ok') { return 'error: '.$reply; }
1.899 raeburn 5654: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680 www 5655: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963 raeburn 5656: my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
5657: $umode.', '.$first.', '.$middle.', '.
5658: $last.', '.$gene.', '.$email.', '.$inststatus;
5659: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
5660: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
5661: } else {
5662: $logmsg .= ' during self creation';
5663: }
5664: &logthis($logmsg);
1.134 albertel 5665: return 'ok';
1.80 www 5666: }
5667:
1.81 www 5668: # -------------------------------------------------------------- Modify student
1.80 www 5669:
1.81 www 5670: sub modifystudent {
5671: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 5672: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
5673: $selfenroll,$context)=@_;
1.455 albertel 5674: if (!$cid) {
1.620 albertel 5675: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5676: return 'not_in_class';
5677: }
1.80 www 5678: }
5679: # --------------------------------------------------------------- Make the user
1.81 www 5680: my $reply=&modifyuser
1.209 matthew 5681: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 5682: $desiredhome,$email);
1.80 www 5683: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 5684: # This will cause &modify_student_enrollment to get the uid from the
5685: # students environment
5686: $uid = undef if (!$forceid);
1.455 albertel 5687: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 5688: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 5689: return $reply;
5690: }
5691:
5692: sub modify_student_enrollment {
1.957 raeburn 5693: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 5694: my ($cdom,$cnum,$chome);
5695: if (!$cid) {
1.620 albertel 5696: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5697: return 'not_in_class';
5698: }
1.620 albertel 5699: $cdom=$env{'course.'.$cid.'.domain'};
5700: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 5701: } else {
5702: ($cdom,$cnum)=split(/_/,$cid);
5703: }
1.620 albertel 5704: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 5705: if (!$chome) {
1.457 raeburn 5706: $chome=&homeserver($cnum,$cdom);
1.297 matthew 5707: }
1.455 albertel 5708: if (!$chome) { return 'unknown_course'; }
1.297 matthew 5709: # Make sure the user exists
1.81 www 5710: my $uhome=&homeserver($uname,$udom);
5711: if (($uhome eq '') || ($uhome eq 'no_host')) {
5712: return 'error: no such user';
5713: }
1.297 matthew 5714: # Get student data if we were not given enough information
5715: if (!defined($first) || $first eq '' ||
5716: !defined($last) || $last eq '' ||
5717: !defined($uid) || $uid eq '' ||
5718: !defined($middle) || $middle eq '' ||
5719: !defined($gene) || $gene eq '') {
1.294 matthew 5720: # They did not supply us with enough data to enroll the student, so
5721: # we need to pick up more information.
1.297 matthew 5722: my %tmp = &get('environment',
1.294 matthew 5723: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 5724: ,$udom,$uname);
5725:
1.800 albertel 5726: #foreach my $key (keys(%tmp)) {
5727: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 5728: #}
1.294 matthew 5729: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
5730: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
5731: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 5732: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 5733: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
5734: }
1.556 albertel 5735: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 5736: my $reply=cput('classlist',
5737: {"$uname:$udom" =>
1.515 raeburn 5738: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 5739: $cdom,$cnum);
1.81 www 5740: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
5741: return 'error: '.$reply;
1.652 albertel 5742: } else {
5743: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 5744: }
1.297 matthew 5745: # Add student role to user
1.83 www 5746: my $uurl='/'.$cid;
1.81 www 5747: $uurl=~s/\_/\//g;
5748: if ($usec) {
5749: $uurl.='/'.$usec;
5750: }
1.957 raeburn 5751: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 5752: }
5753:
1.556 albertel 5754: sub format_name {
5755: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
5756: my $name;
5757: if ($first ne 'lastname') {
5758: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
5759: } else {
5760: if ($lastname=~/\S/) {
5761: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
5762: $name=~s/\s+,/,/;
5763: } else {
5764: $name.= $firstname.' '.$middlename.' '.$generation;
5765: }
5766: }
5767: $name=~s/^\s+//;
5768: $name=~s/\s+$//;
5769: $name=~s/\s+/ /g;
5770: return $name;
5771: }
5772:
1.84 www 5773: # ------------------------------------------------- Write to course preferences
5774:
5775: sub writecoursepref {
5776: my ($courseid,%prefs)=@_;
5777: $courseid=~s/^\///;
5778: $courseid=~s/\_/\//g;
5779: my ($cdomain,$cnum)=split(/\//,$courseid);
5780: my $chome=homeserver($cnum,$cdomain);
5781: if (($chome eq '') || ($chome eq 'no_host')) {
5782: return 'error: no such course';
5783: }
5784: my $cstring='';
1.800 albertel 5785: foreach my $pref (keys(%prefs)) {
5786: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 5787: }
1.84 www 5788: $cstring=~s/\&$//;
5789: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
5790: }
5791:
5792: # ---------------------------------------------------------- Make/modify course
5793:
5794: sub createcourse {
1.741 raeburn 5795: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
5796: $course_owner,$crstype)=@_;
1.84 www 5797: $url=&declutter($url);
5798: my $cid='';
1.264 matthew 5799: unless (&allowed('ccc',$udom)) {
1.84 www 5800: return 'refused';
5801: }
5802: # ------------------------------------------------------------------- Create ID
1.674 www 5803: my $uname=int(1+rand(9)).
5804: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
5805: substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84 www 5806: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
5807: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 5808: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 5809: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5810: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
5811: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 5812: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5813: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5814: return 'error: unable to generate unique course-ID';
5815: }
5816: }
1.264 matthew 5817: # ------------------------------------------------ Check supplied server name
1.620 albertel 5818: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845 albertel 5819: if (! &is_library($course_server)) {
1.264 matthew 5820: return 'error:bad server name '.$course_server;
5821: }
1.84 www 5822: # ------------------------------------------------------------- Make the course
5823: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 5824: $course_server);
1.84 www 5825: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 5826: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5827: if (($uhome eq '') || ($uhome eq 'no_host')) {
5828: return 'error: no such course';
5829: }
1.271 www 5830: # ----------------------------------------------------------------- Course made
1.516 raeburn 5831: # log existence
1.918 raeburn 5832: my $newcourse = {
5833: $udom.'_'.$uname => {
1.921 raeburn 5834: description => $description,
5835: inst_code => $inst_code,
5836: owner => $course_owner,
5837: type => $crstype,
1.918 raeburn 5838: },
5839: };
1.921 raeburn 5840: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 5841: # set toplevel url
1.271 www 5842: my $topurl=$url;
5843: unless ($nonstandard) {
5844: # ------------------------------------------ For standard courses, make top url
5845: my $mapurl=&clutter($url);
1.278 www 5846: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 5847: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 5848: <map>
5849: <resource id="1" type="start"></resource>
5850: <resource id="2" src="$mapurl"></resource>
5851: <resource id="3" type="finish"></resource>
5852: <link index="1" from="1" to="2"></link>
5853: <link index="2" from="2" to="3"></link>
5854: </map>
5855: ENDINITMAP
5856: $topurl=&declutter(
1.638 albertel 5857: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 5858: );
5859: }
5860: # ----------------------------------------------------------- Write preferences
1.84 www 5861: &writecoursepref($udom.'_'.$uname,
5862: ('description' => $description,
1.271 www 5863: 'url' => $topurl));
1.84 www 5864: return '/'.$udom.'/'.$uname;
5865: }
5866:
1.813 albertel 5867: sub is_course {
5868: my ($cdom,$cnum) = @_;
5869: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 5870: undef,'.');
1.813 albertel 5871: if (exists($courses{$cdom.'_'.$cnum})) {
5872: return 1;
5873: }
5874: return 0;
5875: }
5876:
1.21 www 5877: # ---------------------------------------------------------- Assign Custom Role
5878:
5879: sub assigncustomrole {
1.957 raeburn 5880: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 5881: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 5882: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 5883: }
5884:
5885: # ----------------------------------------------------------------- Revoke Role
5886:
5887: sub revokerole {
1.957 raeburn 5888: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 5889: my $now=time;
1.965 raeburn 5890: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 5891: }
5892:
5893: # ---------------------------------------------------------- Revoke Custom Role
5894:
5895: sub revokecustomrole {
1.957 raeburn 5896: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 5897: my $now=time;
1.357 www 5898: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 5899: $deleteflag,$selfenroll,$context);
1.17 www 5900: }
5901:
1.533 banghart 5902: # ------------------------------------------------------------ Disk usage
1.535 albertel 5903: sub diskusage {
1.955 raeburn 5904: my ($udom,$uname,$directorypath,$getpropath)=@_;
5905: $directorypath =~ s/\/$//;
5906: my $listing=&reply('du2:'.&escape($directorypath).':'
5907: .&escape($getpropath).':'.&escape($uname).':'
5908: .&escape($udom),homeserver($uname,$udom));
5909: if ($listing eq 'unknown_cmd') {
5910: if ($getpropath) {
5911: $directorypath = &propath($udom,$uname).'/'.$directorypath;
5912: }
5913: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
5914: }
1.514 albertel 5915: return $listing;
1.512 banghart 5916: }
5917:
1.566 banghart 5918: sub is_locked {
5919: my ($file_name, $domain, $user) = @_;
5920: my @check;
5921: my $is_locked;
5922: push @check, $file_name;
1.613 albertel 5923: my %locked = &get('file_permissions',\@check,
1.620 albertel 5924: $env{'user.domain'},$env{'user.name'});
1.615 albertel 5925: my ($tmp)=keys(%locked);
5926: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 5927:
1.566 banghart 5928: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 5929: $is_locked = 'false';
5930: foreach my $entry (@{$locked{$file_name}}) {
5931: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 5932: $is_locked = 'true';
5933: last;
1.745 raeburn 5934: }
5935: }
1.566 banghart 5936: } else {
5937: $is_locked = 'false';
5938: }
5939: }
5940:
1.759 albertel 5941: sub declutter_portfile {
5942: my ($file) = @_;
1.833 albertel 5943: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 5944: return $file;
5945: }
5946:
1.559 banghart 5947: # ------------------------------------------------------------- Mark as Read Only
5948:
5949: sub mark_as_readonly {
5950: my ($domain,$user,$files,$what) = @_;
1.613 albertel 5951: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5952: my ($tmp)=keys(%current_permissions);
5953: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 5954: foreach my $file (@{$files}) {
1.759 albertel 5955: $file = &declutter_portfile($file);
1.561 banghart 5956: push(@{$current_permissions{$file}},$what);
1.559 banghart 5957: }
1.613 albertel 5958: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 5959: return;
5960: }
5961:
1.572 banghart 5962: # ------------------------------------------------------------Save Selected Files
5963:
5964: sub save_selected_files {
5965: my ($user, $path, @files) = @_;
5966: my $filename = $user."savedfiles";
1.573 banghart 5967: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 5968: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 5969: foreach my $file (@files) {
1.620 albertel 5970: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 5971: }
5972: foreach my $file (@other_files) {
1.574 banghart 5973: print (OUT $file."\n");
1.572 banghart 5974: }
1.574 banghart 5975: close (OUT);
1.572 banghart 5976: return 'ok';
5977: }
5978:
1.574 banghart 5979: sub clear_selected_files {
5980: my ($user) = @_;
5981: my $filename = $user."savedfiles";
5982: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5983: print (OUT undef);
5984: close (OUT);
5985: return ("ok");
5986: }
5987:
1.572 banghart 5988: sub files_in_path {
5989: my ($user, $path) = @_;
5990: my $filename = $user."savedfiles";
5991: my %return_files;
1.574 banghart 5992: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 5993: while (my $line_in = <IN>) {
1.574 banghart 5994: chomp ($line_in);
5995: my @paths_and_file = split (m!/!, $line_in);
5996: my $file_part = pop (@paths_and_file);
5997: my $path_part = join ('/', @paths_and_file);
1.573 banghart 5998: $path_part.='/';
5999: my $path_and_file = $path_part.$file_part;
6000: if ($path_part eq $path) {
6001: $return_files{$file_part}= 'selected';
6002: }
6003: }
1.574 banghart 6004: close (IN);
6005: return (\%return_files);
1.572 banghart 6006: }
6007:
6008: # called in portfolio select mode, to show files selected NOT in current directory
6009: sub files_not_in_path {
6010: my ($user, $path) = @_;
6011: my $filename = $user."savedfiles";
6012: my @return_files;
6013: my $path_part;
1.800 albertel 6014: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6015: while (my $line = <IN>) {
1.572 banghart 6016: #ok, I know it's clunky, but I want it to work
1.800 albertel 6017: my @paths_and_file = split(m|/|, $line);
6018: my $file_part = pop(@paths_and_file);
6019: chomp($file_part);
6020: my $path_part = join('/', @paths_and_file);
1.572 banghart 6021: $path_part .= '/';
6022: my $path_and_file = $path_part.$file_part;
6023: if ($path_part ne $path) {
1.800 albertel 6024: push(@return_files, ($path_and_file));
1.572 banghart 6025: }
6026: }
1.800 albertel 6027: close(OUT);
1.574 banghart 6028: return (@return_files);
1.572 banghart 6029: }
6030:
1.745 raeburn 6031: #----------------------------------------------Get portfolio file permissions
1.629 banghart 6032:
1.745 raeburn 6033: sub get_portfile_permissions {
6034: my ($domain,$user) = @_;
1.613 albertel 6035: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 6036: my ($tmp)=keys(%current_permissions);
6037: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6038: return \%current_permissions;
6039: }
6040:
6041: #---------------------------------------------Get portfolio file access controls
6042:
1.749 raeburn 6043: sub get_access_controls {
1.745 raeburn 6044: my ($current_permissions,$group,$file) = @_;
1.769 albertel 6045: my %access;
6046: my $real_file = $file;
6047: $file =~ s/\.meta$//;
1.745 raeburn 6048: if (defined($file)) {
1.749 raeburn 6049: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
6050: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 6051: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 6052: }
6053: }
1.745 raeburn 6054: } else {
1.749 raeburn 6055: foreach my $key (keys(%{$current_permissions})) {
6056: if ($key =~ /\0accesscontrol$/) {
6057: if (defined($group)) {
6058: if ($key !~ m-^\Q$group\E/-) {
6059: next;
6060: }
6061: }
6062: my ($fullpath) = split(/\0/,$key);
6063: if (ref($$current_permissions{$key}) eq 'HASH') {
6064: foreach my $control (keys(%{$$current_permissions{$key}})) {
6065: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
6066: }
6067: }
6068: }
6069: }
6070: }
6071: return %access;
6072: }
6073:
6074: sub modify_access_controls {
6075: my ($file_name,$changes,$domain,$user)=@_;
6076: my ($outcome,$deloutcome);
6077: my %store_permissions;
6078: my %new_values;
6079: my %new_control;
6080: my %translation;
6081: my @deletions = ();
6082: my $now = time;
6083: if (exists($$changes{'activate'})) {
6084: if (ref($$changes{'activate'}) eq 'HASH') {
6085: my @newitems = sort(keys(%{$$changes{'activate'}}));
6086: my $numnew = scalar(@newitems);
6087: for (my $i=0; $i<$numnew; $i++) {
6088: my $newkey = $newitems[$i];
6089: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 6090: if ($newkey =~ /^\d+:/) {
6091: $newkey =~ s/^(\d+)/$newid/;
6092: $translation{$1} = $newid;
6093: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
6094: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
6095: $translation{$1} = $newid;
6096: }
1.749 raeburn 6097: $new_values{$file_name."\0".$newkey} =
6098: $$changes{'activate'}{$newitems[$i]};
6099: $new_control{$newkey} = $now;
6100: }
6101: }
6102: }
6103: my %todelete;
6104: my %changed_items;
6105: foreach my $action ('delete','update') {
6106: if (exists($$changes{$action})) {
6107: if (ref($$changes{$action}) eq 'HASH') {
6108: foreach my $key (keys(%{$$changes{$action}})) {
6109: my ($itemnum) = ($key =~ /^([^:]+):/);
6110: if ($action eq 'delete') {
6111: $todelete{$itemnum} = 1;
6112: } else {
6113: $changed_items{$itemnum} = $key;
6114: }
6115: }
1.745 raeburn 6116: }
6117: }
1.749 raeburn 6118: }
6119: # get lock on access controls for file.
6120: my $lockhash = {
6121: $file_name."\0".'locked_access_records' => $env{'user.name'}.
6122: ':'.$env{'user.domain'},
6123: };
6124: my $tries = 0;
6125: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6126:
6127: while (($gotlock ne 'ok') && $tries <3) {
6128: $tries ++;
6129: sleep 1;
6130: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6131: }
6132: if ($gotlock eq 'ok') {
6133: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
6134: my ($tmp)=keys(%curr_permissions);
6135: if ($tmp=~/^error:/) { undef(%curr_permissions); }
6136: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
6137: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
6138: if (ref($curr_controls) eq 'HASH') {
6139: foreach my $control_item (keys(%{$curr_controls})) {
6140: my ($itemnum) = ($control_item =~ /^([^:]+):/);
6141: if (defined($todelete{$itemnum})) {
6142: push(@deletions,$file_name."\0".$control_item);
6143: } else {
6144: if (defined($changed_items{$itemnum})) {
6145: $new_control{$changed_items{$itemnum}} = $now;
6146: push(@deletions,$file_name."\0".$control_item);
6147: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
6148: } else {
6149: $new_control{$control_item} = $$curr_controls{$control_item};
6150: }
6151: }
1.745 raeburn 6152: }
6153: }
6154: }
1.970 ! raeburn 6155: my ($group);
! 6156: if (&is_course($domain,$user)) {
! 6157: ($group,my $file) = split(/\//,$file_name,2);
! 6158: }
1.749 raeburn 6159: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
6160: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
6161: $outcome = &put('file_permissions',\%new_values,$domain,$user);
6162: # remove lock
6163: my @del_lock = ($file_name."\0".'locked_access_records');
6164: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 6165: my $sqlresult =
1.970 ! raeburn 6166: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 6167: $group);
1.749 raeburn 6168: } else {
6169: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 6170: }
1.749 raeburn 6171: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 6172: }
6173:
1.827 raeburn 6174: sub make_public_indefinitely {
6175: my ($requrl) = @_;
6176: my $now = time;
6177: my $action = 'activate';
6178: my $aclnum = 0;
6179: if (&is_portfolio_url($requrl)) {
6180: my (undef,$udom,$unum,$file_name,$group) =
6181: &parse_portfolio_url($requrl);
6182: my $current_perms = &get_portfile_permissions($udom,$unum);
6183: my %access_controls = &get_access_controls($current_perms,
6184: $group,$file_name);
6185: foreach my $key (keys(%{$access_controls{$file_name}})) {
6186: my ($num,$scope,$end,$start) =
6187: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6188: if ($scope eq 'public') {
6189: if ($start <= $now && $end == 0) {
6190: $action = 'none';
6191: } else {
6192: $action = 'update';
6193: $aclnum = $num;
6194: }
6195: last;
6196: }
6197: }
6198: if ($action eq 'none') {
6199: return 'ok';
6200: } else {
6201: my %changes;
6202: my $newend = 0;
6203: my $newstart = $now;
6204: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
6205: $changes{$action}{$newkey} = {
6206: type => 'public',
6207: time => {
6208: start => $newstart,
6209: end => $newend,
6210: },
6211: };
6212: my ($outcome,$deloutcome,$new_values,$translation) =
6213: &modify_access_controls($file_name,\%changes,$udom,$unum);
6214: return $outcome;
6215: }
6216: } else {
6217: return 'invalid';
6218: }
6219: }
6220:
1.745 raeburn 6221: #------------------------------------------------------Get Marked as Read Only
6222:
6223: sub get_marked_as_readonly {
6224: my ($domain,$user,$what,$group) = @_;
6225: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 6226: my @readonly_files;
1.629 banghart 6227: my $cmp1=$what;
6228: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 6229: while (my ($file_name,$value) = each(%{$current_permissions})) {
6230: if (defined($group)) {
6231: if ($file_name !~ m-^\Q$group\E/-) {
6232: next;
6233: }
6234: }
1.561 banghart 6235: if (ref($value) eq "ARRAY"){
6236: foreach my $stored_what (@{$value}) {
1.629 banghart 6237: my $cmp2=$stored_what;
1.759 albertel 6238: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 6239: $cmp2=join('',@{$stored_what});
1.745 raeburn 6240: }
1.629 banghart 6241: if ($cmp1 eq $cmp2) {
1.561 banghart 6242: push(@readonly_files, $file_name);
1.745 raeburn 6243: last;
1.563 banghart 6244: } elsif (!defined($what)) {
6245: push(@readonly_files, $file_name);
1.745 raeburn 6246: last;
1.561 banghart 6247: }
6248: }
1.745 raeburn 6249: }
1.561 banghart 6250: }
6251: return @readonly_files;
6252: }
1.577 banghart 6253: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 6254:
1.577 banghart 6255: sub get_marked_as_readonly_hash {
1.745 raeburn 6256: my ($current_permissions,$group,$what) = @_;
1.577 banghart 6257: my %readonly_files;
1.745 raeburn 6258: while (my ($file_name,$value) = each(%{$current_permissions})) {
6259: if (defined($group)) {
6260: if ($file_name !~ m-^\Q$group\E/-) {
6261: next;
6262: }
6263: }
1.577 banghart 6264: if (ref($value) eq "ARRAY"){
6265: foreach my $stored_what (@{$value}) {
1.745 raeburn 6266: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 6267: foreach my $lock_descriptor(@{$stored_what}) {
6268: if ($lock_descriptor eq 'graded') {
6269: $readonly_files{$file_name} = 'graded';
6270: } elsif ($lock_descriptor eq 'handback') {
6271: $readonly_files{$file_name} = 'handback';
6272: } else {
6273: if (!exists($readonly_files{$file_name})) {
6274: $readonly_files{$file_name} = 'locked';
6275: }
6276: }
1.745 raeburn 6277: }
1.750 banghart 6278: }
1.577 banghart 6279: }
6280: }
6281: }
6282: return %readonly_files;
6283: }
1.559 banghart 6284: # ------------------------------------------------------------ Unmark as Read Only
6285:
6286: sub unmark_as_readonly {
1.629 banghart 6287: # unmarks $file_name (if $file_name is defined), or all files locked by $what
6288: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 6289: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 6290: $file_name = &declutter_portfile($file_name);
1.634 albertel 6291: my $symb_crs = $what;
6292: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 6293: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 6294: my ($tmp)=keys(%current_permissions);
6295: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 6296: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 6297: foreach my $file (@readonly_files) {
1.759 albertel 6298: my $clean_file = &declutter_portfile($file);
6299: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 6300: my $current_locks = $current_permissions{$file};
1.563 banghart 6301: my @new_locks;
6302: my @del_keys;
6303: if (ref($current_locks) eq "ARRAY"){
6304: foreach my $locker (@{$current_locks}) {
1.632 albertel 6305: my $compare=$locker;
1.749 raeburn 6306: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 6307: $compare=join('',@{$locker});
1.746 raeburn 6308: if ($compare ne $symb_crs) {
6309: push(@new_locks, $locker);
6310: }
1.563 banghart 6311: }
6312: }
1.650 albertel 6313: if (scalar(@new_locks) > 0) {
1.563 banghart 6314: $current_permissions{$file} = \@new_locks;
6315: } else {
6316: push(@del_keys, $file);
1.613 albertel 6317: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 6318: delete($current_permissions{$file});
1.563 banghart 6319: }
6320: }
1.561 banghart 6321: }
1.613 albertel 6322: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 6323: return;
6324: }
1.512 banghart 6325:
1.17 www 6326: # ------------------------------------------------------------ Directory lister
6327:
6328: sub dirlist {
1.955 raeburn 6329: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 6330: $uri=~s/^\///;
6331: $uri=~s/\/$//;
1.253 stredwic 6332: my ($udom, $uname);
1.955 raeburn 6333: if ($getuserdir) {
1.253 stredwic 6334: $udom = $userdomain;
6335: $uname = $username;
1.955 raeburn 6336: } else {
6337: (undef,$udom,$uname)=split(/\//,$uri);
6338: if(defined($userdomain)) {
6339: $udom = $userdomain;
6340: }
6341: if(defined($username)) {
6342: $uname = $username;
6343: }
1.253 stredwic 6344: }
1.955 raeburn 6345: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 6346:
1.955 raeburn 6347: $dirRoot = $perlvar{'lonDocRoot'};
6348: if (defined($getpropath)) {
6349: $dirRoot = &propath($udom,$uname);
1.253 stredwic 6350: $dirRoot =~ s/\/$//;
1.955 raeburn 6351: } elsif (defined($getuserdir)) {
6352: my $subdir=$uname.'__';
6353: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
6354: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
6355: ."/$udom/$subdir/$uname";
6356: } elsif (defined($alternateRoot)) {
6357: $dirRoot = $alternateRoot;
1.751 banghart 6358: }
1.253 stredwic 6359:
6360: if($udom) {
6361: if($uname) {
1.955 raeburn 6362: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 6363: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 6364: .':'.&escape($uname).':'.&escape($udom),
6365: &homeserver($uname,$udom));
6366: if ($listing eq 'unknown_cmd') {
6367: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
6368: &homeserver($uname,$udom));
6369: } else {
6370: @listing_results = map { &unescape($_); } split(/:/,$listing);
6371: }
1.605 matthew 6372: if ($listing eq 'unknown_cmd') {
1.800 albertel 6373: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
6374: &homeserver($uname,$udom));
1.605 matthew 6375: @listing_results = split(/:/,$listing);
6376: } else {
6377: @listing_results = map { &unescape($_); } split(/:/,$listing);
6378: }
6379: return @listing_results;
1.955 raeburn 6380: } elsif(!$alternateRoot) {
1.800 albertel 6381: my %allusers;
1.841 albertel 6382: my %servers = &get_servers($udom,'library');
1.955 raeburn 6383: foreach my $tryserver (keys(%servers)) {
6384: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
6385: &escape($udom),$tryserver);
6386: if ($listing eq 'unknown_cmd') {
6387: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
6388: $udom, $tryserver);
6389: } else {
6390: @listing_results = map { &unescape($_); } split(/:/,$listing);
6391: }
1.841 albertel 6392: if ($listing eq 'unknown_cmd') {
6393: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
6394: $udom, $tryserver);
6395: @listing_results = split(/:/,$listing);
6396: } else {
6397: @listing_results =
6398: map { &unescape($_); } split(/:/,$listing);
6399: }
6400: if ($listing_results[0] ne 'no_such_dir' &&
6401: $listing_results[0] ne 'empty' &&
6402: $listing_results[0] ne 'con_lost') {
6403: foreach my $line (@listing_results) {
6404: my ($entry) = split(/&/,$line,2);
6405: $allusers{$entry} = 1;
6406: }
6407: }
1.253 stredwic 6408: }
6409: my $alluserstr='';
1.800 albertel 6410: foreach my $user (sort(keys(%allusers))) {
6411: $alluserstr.=$user.'&user:';
1.253 stredwic 6412: }
6413: $alluserstr=~s/:$//;
6414: return split(/:/,$alluserstr);
6415: } else {
1.800 albertel 6416: return ('missing user name');
1.253 stredwic 6417: }
1.955 raeburn 6418: } elsif(!defined($getpropath)) {
1.841 albertel 6419: my @all_domains = sort(&all_domains());
1.955 raeburn 6420: foreach my $domain (@all_domains) {
6421: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
6422: }
6423: return @all_domains;
6424: } else {
1.800 albertel 6425: return ('missing domain');
1.275 stredwic 6426: }
6427: }
6428:
6429: # --------------------------------------------- GetFileTimestamp
6430: # This function utilizes dirlist and returns the date stamp for
6431: # when it was last modified. It will also return an error of -1
6432: # if an error occurs
6433:
6434: sub GetFileTimestamp {
1.955 raeburn 6435: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 6436: $studentDomain = &LONCAPA::clean_domain($studentDomain);
6437: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 6438: my ($fileStat) =
6439: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
6440: undef,$getuserdir);
1.275 stredwic 6441: my @stats = split('&', $fileStat);
6442: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 6443: # @stats contains first the filename, then the stat output
6444: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 6445: } else {
6446: return -1;
1.253 stredwic 6447: }
1.26 www 6448: }
6449:
1.712 albertel 6450: sub stat_file {
6451: my ($uri) = @_;
1.787 albertel 6452: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 6453:
1.955 raeburn 6454: my ($udom,$uname,$file);
1.712 albertel 6455: if ($uri =~ m-^/(uploaded|editupload)/-) {
6456: ($udom,$uname,$file) =
1.811 albertel 6457: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 6458: $file = 'userfiles/'.$file;
6459: }
6460: if ($uri =~ m-^/res/-) {
6461: ($udom,$uname) =
1.807 albertel 6462: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 6463: $file = $uri;
6464: }
6465:
6466: if (!$udom || !$uname || !$file) {
6467: # unable to handle the uri
6468: return ();
6469: }
1.956 raeburn 6470: my $getpropath;
6471: if ($file =~ /^userfiles\//) {
6472: $getpropath = 1;
6473: }
1.955 raeburn 6474: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 6475: my @stats = split('&', $result);
1.721 banghart 6476:
1.712 albertel 6477: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
6478: shift(@stats); #filename is first
6479: return @stats;
6480: }
6481: return ();
6482: }
6483:
1.26 www 6484: # -------------------------------------------------------- Value of a Condition
6485:
1.713 albertel 6486: # gets the value of a specific preevaluated condition
6487: # stored in the string $env{user.state.<cid>}
6488: # or looks up a condition reference in the bighash and if if hasn't
6489: # already been evaluated recurses into docondval to get the value of
6490: # the condition, then memoizing it to
6491: # $env{user.state.<cid>.<condition>}
1.40 www 6492: sub directcondval {
6493: my $number=shift;
1.620 albertel 6494: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 6495: &Apache::lonuserstate::evalstate();
6496: }
1.713 albertel 6497: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
6498: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
6499: } elsif ($number =~ /^_/) {
6500: my $sub_condition;
6501: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6502: &GDBM_READER(),0640)) {
6503: $sub_condition=$bighash{'conditions'.$number};
6504: untie(%bighash);
6505: }
6506: my $value = &docondval($sub_condition);
1.949 raeburn 6507: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 6508: return $value;
6509: }
1.620 albertel 6510: if ($env{'user.state.'.$env{'request.course.id'}}) {
6511: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 6512: } else {
6513: return 2;
6514: }
6515: }
6516:
1.713 albertel 6517: # get the collection of conditions for this resource
1.26 www 6518: sub condval {
6519: my $condidx=shift;
1.54 www 6520: my $allpathcond='';
1.713 albertel 6521: foreach my $cond (split(/\|/,$condidx)) {
6522: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
6523: $allpathcond.=
6524: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
6525: }
1.191 harris41 6526: }
1.54 www 6527: $allpathcond=~s/\|$//;
1.713 albertel 6528: return &docondval($allpathcond);
6529: }
6530:
6531: #evaluates an expression of conditions
6532: sub docondval {
6533: my ($allpathcond) = @_;
6534: my $result=0;
6535: if ($env{'request.course.id'}
6536: && defined($allpathcond)) {
6537: my $operand='|';
6538: my @stack;
6539: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
6540: if ($chunk eq '(') {
6541: push @stack,($operand,$result);
6542: } elsif ($chunk eq ')') {
6543: my $before=pop @stack;
6544: if (pop @stack eq '&') {
6545: $result=$result>$before?$before:$result;
6546: } else {
6547: $result=$result>$before?$result:$before;
6548: }
6549: } elsif (($chunk eq '&') || ($chunk eq '|')) {
6550: $operand=$chunk;
6551: } else {
6552: my $new=directcondval($chunk);
6553: if ($operand eq '&') {
6554: $result=$result>$new?$new:$result;
6555: } else {
6556: $result=$result>$new?$result:$new;
6557: }
6558: }
6559: }
1.26 www 6560: }
6561: return $result;
1.421 albertel 6562: }
6563:
6564: # ---------------------------------------------------- Devalidate courseresdata
6565:
6566: sub devalidatecourseresdata {
6567: my ($coursenum,$coursedomain)=@_;
6568: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6569: &devalidate_cache_new('courseres',$hashid);
1.28 www 6570: }
6571:
1.763 www 6572:
1.200 www 6573: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 6574: #
6575: # Parameters:
6576: # $coursenum - Number of the course.
6577: # $coursedomain - Domain at which the course was created.
6578: # Returns:
6579: # A hash of the course parameters along (I think) with timestamps
6580: # and version info.
1.877 foxr 6581:
1.624 albertel 6582: sub get_courseresdata {
6583: my ($coursenum,$coursedomain)=@_;
1.200 www 6584: my $coursehom=&homeserver($coursenum,$coursedomain);
6585: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 6586: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 6587: my %dumpreply;
1.417 albertel 6588: unless (defined($cached)) {
1.624 albertel 6589: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 6590: $result=\%dumpreply;
1.251 albertel 6591: my ($tmp) = keys(%dumpreply);
6592: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 6593: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 6594: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
6595: return $tmp;
1.416 albertel 6596: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 6597: $result=undef;
1.599 albertel 6598: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 6599: }
6600: }
1.624 albertel 6601: return $result;
6602: }
6603:
1.633 albertel 6604: sub devalidateuserresdata {
6605: my ($uname,$udom)=@_;
6606: my $hashid="$udom:$uname";
6607: &devalidate_cache_new('userres',$hashid);
6608: }
6609:
1.624 albertel 6610: sub get_userresdata {
6611: my ($uname,$udom)=@_;
6612: #most student don\'t have any data set, check if there is some data
6613: if (&EXT_cache_status($udom,$uname)) { return undef; }
6614:
6615: my $hashid="$udom:$uname";
6616: my ($result,$cached)=&is_cached_new('userres',$hashid);
6617: if (!defined($cached)) {
6618: my %resourcedata=&dump('resourcedata',$udom,$uname);
6619: $result=\%resourcedata;
6620: &do_cache_new('userres',$hashid,$result,600);
6621: }
6622: my ($tmp)=keys(%$result);
6623: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
6624: return $result;
6625: }
6626: #error 2 occurs when the .db doesn't exist
6627: if ($tmp!~/error: 2 /) {
1.672 albertel 6628: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 6629: " Trying to get resource data for ".
6630: $uname." at ".$udom.": ".
6631: $tmp."</font>");
6632: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 6633: #&EXT_cache_set($udom,$uname);
6634: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 6635: undef($tmp); # not really an error so don't send it back
1.624 albertel 6636: }
6637: return $tmp;
6638: }
1.879 foxr 6639: #----------------------------------------------- resdata - return resource data
6640: # Purpose:
6641: # Return resource data for either users or for a course.
6642: # Parameters:
6643: # $name - Course/user name.
6644: # $domain - Name of the domain the user/course is registered on.
6645: # $type - Type of thing $name is (must be 'course' or 'user'
6646: # @which - Array of names of resources desired.
6647: # Returns:
6648: # The value of the first reasource in @which that is found in the
6649: # resource hash.
6650: # Exceptional Conditions:
6651: # If the $type passed in is not valid (not the string 'course' or
6652: # 'user', an undefined reference is returned.
6653: # If none of the resources are found, an undef is returned
1.624 albertel 6654: sub resdata {
6655: my ($name,$domain,$type,@which)=@_;
6656: my $result;
6657: if ($type eq 'course') {
6658: $result=&get_courseresdata($name,$domain);
6659: } elsif ($type eq 'user') {
6660: $result=&get_userresdata($name,$domain);
6661: }
6662: if (!ref($result)) { return $result; }
1.251 albertel 6663: foreach my $item (@which) {
1.927 albertel 6664: if (defined($result->{$item->[0]})) {
6665: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 6666: }
1.250 albertel 6667: }
1.291 albertel 6668: return undef;
1.200 www 6669: }
6670:
1.379 matthew 6671: #
6672: # EXT resource caching routines
6673: #
6674:
6675: sub clear_EXT_cache_status {
1.383 albertel 6676: &delenv('cache.EXT.');
1.379 matthew 6677: }
6678:
6679: sub EXT_cache_status {
6680: my ($target_domain,$target_user) = @_;
1.383 albertel 6681: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 6682: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 6683: # We know already the user has no data
6684: return 1;
6685: } else {
6686: return 0;
6687: }
6688: }
6689:
6690: sub EXT_cache_set {
6691: my ($target_domain,$target_user) = @_;
1.383 albertel 6692: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 6693: #&appenv({$cachename => time});
1.379 matthew 6694: }
6695:
1.28 www 6696: # --------------------------------------------------------- Value of a Variable
1.58 www 6697: sub EXT {
1.715 albertel 6698:
1.395 albertel 6699: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 6700: unless ($varname) { return ''; }
1.218 albertel 6701: #get real user name/domain, courseid and symb
6702: my $courseid;
1.359 albertel 6703: my $publicuser;
1.427 www 6704: if ($symbparm) {
6705: $symbparm=&get_symb_from_alias($symbparm);
6706: }
1.218 albertel 6707: if (!($uname && $udom)) {
1.790 albertel 6708: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 6709: if (!$symbparm) { $symbparm=$cursymb; }
6710: } else {
1.620 albertel 6711: $courseid=$env{'request.course.id'};
1.218 albertel 6712: }
1.48 www 6713: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
6714: my $rest;
1.320 albertel 6715: if (defined($therest[0])) {
1.48 www 6716: $rest=join('.',@therest);
6717: } else {
6718: $rest='';
6719: }
1.320 albertel 6720:
1.57 www 6721: my $qualifierrest=$qualifier;
6722: if ($rest) { $qualifierrest.='.'.$rest; }
6723: my $spacequalifierrest=$space;
6724: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 6725: if ($realm eq 'user') {
1.48 www 6726: # --------------------------------------------------------------- user.resource
6727: if ($space eq 'resource') {
1.651 albertel 6728: if ( (defined($Apache::lonhomework::parsing_a_problem)
6729: || defined($Apache::lonhomework::parsing_a_task))
6730: &&
1.744 albertel 6731: ($symbparm eq &symbread()) ) {
6732: # if we are in the middle of processing the resource the
6733: # get the value we are planning on committing
6734: if (defined($Apache::lonhomework::results{$qualifierrest})) {
6735: return $Apache::lonhomework::results{$qualifierrest};
6736: } else {
6737: return $Apache::lonhomework::history{$qualifierrest};
6738: }
1.335 albertel 6739: } else {
1.359 albertel 6740: my %restored;
1.620 albertel 6741: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 6742: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
6743: } else {
6744: %restored=&restore($symbparm,$courseid,$udom,$uname);
6745: }
1.335 albertel 6746: return $restored{$qualifierrest};
6747: }
1.48 www 6748: # ----------------------------------------------------------------- user.access
6749: } elsif ($space eq 'access') {
1.218 albertel 6750: # FIXME - not supporting calls for a specific user
1.48 www 6751: return &allowed($qualifier,$rest);
6752: # ------------------------------------------ user.preferences, user.environment
6753: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 6754: if (($uname eq $env{'user.name'}) &&
6755: ($udom eq $env{'user.domain'})) {
6756: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 6757: } else {
1.359 albertel 6758: my %returnhash;
6759: if (!$publicuser) {
6760: %returnhash=&userenvironment($udom,$uname,
6761: $qualifierrest);
6762: }
1.218 albertel 6763: return $returnhash{$qualifierrest};
6764: }
1.48 www 6765: # ----------------------------------------------------------------- user.course
6766: } elsif ($space eq 'course') {
1.218 albertel 6767: # FIXME - not supporting calls for a specific user
1.620 albertel 6768: return $env{join('.',('request.course',$qualifier))};
1.48 www 6769: # ------------------------------------------------------------------- user.role
6770: } elsif ($space eq 'role') {
1.218 albertel 6771: # FIXME - not supporting calls for a specific user
1.620 albertel 6772: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 6773: if ($qualifier eq 'value') {
6774: return $role;
6775: } elsif ($qualifier eq 'extent') {
6776: return $where;
6777: }
6778: # ----------------------------------------------------------------- user.domain
6779: } elsif ($space eq 'domain') {
1.218 albertel 6780: return $udom;
1.48 www 6781: # ------------------------------------------------------------------- user.name
6782: } elsif ($space eq 'name') {
1.218 albertel 6783: return $uname;
1.48 www 6784: # ---------------------------------------------------- Any other user namespace
1.29 www 6785: } else {
1.359 albertel 6786: my %reply;
6787: if (!$publicuser) {
6788: %reply=&get($space,[$qualifierrest],$udom,$uname);
6789: }
6790: return $reply{$qualifierrest};
1.48 www 6791: }
1.236 www 6792: } elsif ($realm eq 'query') {
6793: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 6794: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
6795: [$spacequalifierrest]);
1.620 albertel 6796: return $env{'form.'.$spacequalifierrest};
1.236 www 6797: } elsif ($realm eq 'request') {
1.48 www 6798: # ------------------------------------------------------------- request.browser
6799: if ($space eq 'browser') {
1.430 www 6800: if ($qualifier eq 'textremote') {
1.676 albertel 6801: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 6802: return 1;
6803: } else {
6804: return 0;
6805: }
6806: } else {
1.620 albertel 6807: return $env{'browser.'.$qualifier};
1.430 www 6808: }
1.57 www 6809: # ------------------------------------------------------------ request.filename
6810: } else {
1.620 albertel 6811: return $env{'request.'.$spacequalifierrest};
1.29 www 6812: }
1.28 www 6813: } elsif ($realm eq 'course') {
1.48 www 6814: # ---------------------------------------------------------- course.description
1.620 albertel 6815: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 6816: } elsif ($realm eq 'resource') {
1.165 www 6817:
1.620 albertel 6818: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 6819: if (!$symbparm) { $symbparm=&symbread(); }
6820: }
1.693 albertel 6821:
6822: if ($space eq 'title') {
6823: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
6824: return &gettitle($symbparm);
6825: }
6826:
6827: if ($space eq 'map') {
6828: my ($map) = &decode_symb($symbparm);
6829: return &symbread($map);
6830: }
1.905 albertel 6831: if ($space eq 'filename') {
6832: if ($symbparm) {
6833: return &clutter((&decode_symb($symbparm))[2]);
6834: }
6835: return &hreflocation('',$env{'request.filename'});
6836: }
1.693 albertel 6837:
6838: my ($section, $group, @groups);
1.593 albertel 6839: my ($courselevelm,$courselevel);
1.539 albertel 6840: if ($symbparm && defined($courseid) &&
1.620 albertel 6841: $courseid eq $env{'request.course.id'}) {
1.165 www 6842:
1.218 albertel 6843: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 6844:
1.60 www 6845: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 6846: my $symbp=$symbparm;
1.735 albertel 6847: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 6848:
6849: my $symbparm=$symbp.'.'.$spacequalifierrest;
6850: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
6851:
1.620 albertel 6852: if (($env{'user.name'} eq $uname) &&
6853: ($env{'user.domain'} eq $udom)) {
6854: $section=$env{'request.course.sec'};
1.733 raeburn 6855: @groups = split(/:/,$env{'request.course.groups'});
6856: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 6857: } else {
1.539 albertel 6858: if (! defined($usection)) {
1.551 albertel 6859: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 6860: } else {
6861: $section = $usection;
6862: }
1.733 raeburn 6863: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 6864: }
6865:
6866: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
6867: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
6868: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
6869:
1.593 albertel 6870: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 6871: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 6872: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 6873:
1.60 www 6874: # ----------------------------------------------------------- first, check user
1.624 albertel 6875:
6876: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 6877: ([$courselevelr,'resource'],
6878: [$courselevelm,'map' ],
6879: [$courselevel, 'course' ]));
1.931 albertel 6880: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 6881:
1.594 albertel 6882: # ------------------------------------------------ second, check some of course
1.684 raeburn 6883: my $coursereply;
1.691 raeburn 6884: if (@groups > 0) {
6885: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
6886: $mapparm,$spacequalifierrest);
1.927 albertel 6887: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 6888: }
1.96 www 6889:
1.684 raeburn 6890: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 6891: $env{'course.'.$courseid.'.domain'},
6892: 'course',
6893: ([$seclevelr, 'resource'],
6894: [$seclevelm, 'map' ],
6895: [$seclevel, 'course' ],
6896: [$courselevelr,'resource']));
6897: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 6898:
1.60 www 6899: # ------------------------------------------------------ third, check map parms
1.218 albertel 6900: my %parmhash=();
6901: my $thisparm='';
6902: if (tie(%parmhash,'GDBM_File',
1.620 albertel 6903: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 6904: &GDBM_READER(),0640)) {
1.218 albertel 6905: $thisparm=$parmhash{$symbparm};
6906: untie(%parmhash);
6907: }
1.927 albertel 6908: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 6909: }
1.594 albertel 6910: # ------------------------------------------ fourth, look in resource metadata
1.71 www 6911:
1.218 albertel 6912: $spacequalifierrest=~s/\./\_/;
1.282 albertel 6913: my $filename;
6914: if (!$symbparm) { $symbparm=&symbread(); }
6915: if ($symbparm) {
1.409 www 6916: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 6917: } else {
1.620 albertel 6918: $filename=$env{'request.filename'};
1.282 albertel 6919: }
6920: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 6921: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 6922: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 6923: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 6924:
1.927 albertel 6925: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 6926: if ($symbparm && defined($courseid) &&
1.620 albertel 6927: $courseid eq $env{'request.course.id'}) {
1.624 albertel 6928: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
6929: $env{'course.'.$courseid.'.domain'},
6930: 'course',
1.927 albertel 6931: ([$courselevelm,'map' ],
6932: [$courselevel, 'course']));
6933: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 6934: }
1.145 www 6935: # ------------------------------------------------------------------ Cascade up
1.218 albertel 6936: unless ($space eq '0') {
1.336 albertel 6937: my @parts=split(/_/,$space);
6938: my $id=pop(@parts);
6939: my $part=join('_',@parts);
6940: if ($part eq '') { $part='0'; }
1.927 albertel 6941: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 6942: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 6943: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 6944: }
1.395 albertel 6945: if ($recurse) { return undef; }
6946: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 6947: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 6948: # ---------------------------------------------------- Any other user namespace
6949: } elsif ($realm eq 'environment') {
6950: # ----------------------------------------------------------------- environment
1.620 albertel 6951: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
6952: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 6953: } else {
1.770 albertel 6954: if ($uname eq 'anonymous' && $udom eq '') {
6955: return '';
6956: }
1.219 albertel 6957: my %returnhash=&userenvironment($udom,$uname,
6958: $spacequalifierrest);
6959: return $returnhash{$spacequalifierrest};
6960: }
1.28 www 6961: } elsif ($realm eq 'system') {
1.48 www 6962: # ----------------------------------------------------------------- system.time
6963: if ($space eq 'time') {
6964: return time;
6965: }
1.696 albertel 6966: } elsif ($realm eq 'server') {
6967: # ----------------------------------------------------------------- system.time
6968: if ($space eq 'name') {
6969: return $ENV{'SERVER_NAME'};
6970: }
1.28 www 6971: }
1.48 www 6972: return '';
1.61 www 6973: }
6974:
1.927 albertel 6975: sub get_reply {
6976: my ($reply_value) = @_;
1.940 raeburn 6977: if (ref($reply_value) eq 'ARRAY') {
6978: if (wantarray) {
6979: return @$reply_value;
6980: }
6981: return $reply_value->[0];
6982: } else {
6983: return $reply_value;
1.927 albertel 6984: }
6985: }
6986:
1.691 raeburn 6987: sub check_group_parms {
6988: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
6989: my @groupitems = ();
6990: my $resultitem;
1.927 albertel 6991: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 6992: foreach my $group (@{$groups}) {
6993: foreach my $level (@levels) {
1.927 albertel 6994: my $item = $courseid.'.['.$group.'].'.$level->[0];
6995: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 6996: }
6997: }
6998: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
6999: $env{'course.'.$courseid.'.domain'},
7000: 'course',@groupitems);
7001: return $coursereply;
7002: }
7003:
7004: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 7005: my ($courseid,@groups) = @_;
7006: @groups = sort(@groups);
1.691 raeburn 7007: return @groups;
7008: }
7009:
1.395 albertel 7010: sub packages_tab_default {
7011: my ($uri,$varname)=@_;
7012: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 7013:
7014: my (@extension,@specifics,$do_default);
7015: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 7016: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 7017: if ($pack_type eq 'default') {
7018: $do_default=1;
7019: } elsif ($pack_type eq 'extension') {
7020: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 7021: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 7022: # only look at packages defaults for packages that this id is
1.738 albertel 7023: push(@specifics,[$package,$pack_type,$pack_part]);
7024: }
7025: }
7026: # first look for a package that matches the requested part id
7027: foreach my $package (@specifics) {
7028: my (undef,$pack_type,$pack_part)=@{$package};
7029: next if ($pack_part ne $part);
7030: if (defined($packagetab{"$pack_type&$name&default"})) {
7031: return $packagetab{"$pack_type&$name&default"};
7032: }
7033: }
7034: # look for any possible matching non extension_ package
7035: foreach my $package (@specifics) {
7036: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 7037: if (defined($packagetab{"$pack_type&$name&default"})) {
7038: return $packagetab{"$pack_type&$name&default"};
7039: }
1.585 albertel 7040: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 7041: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
7042: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 7043: }
7044: }
1.738 albertel 7045: # look for any posible extension_ match
7046: foreach my $package (@extension) {
7047: my ($package,$pack_type)=@{$package};
7048: if (defined($packagetab{"$pack_type&$name&default"})) {
7049: return $packagetab{"$pack_type&$name&default"};
7050: }
7051: if (defined($packagetab{$package."&$name&default"})) {
7052: return $packagetab{$package."&$name&default"};
7053: }
7054: }
7055: # look for a global default setting
7056: if ($do_default && defined($packagetab{"default&$name&default"})) {
7057: return $packagetab{"default&$name&default"};
7058: }
1.395 albertel 7059: return undef;
7060: }
7061:
1.334 albertel 7062: sub add_prefix_and_part {
7063: my ($prefix,$part)=@_;
7064: my $keyroot;
7065: if (defined($prefix) && $prefix !~ /^__/) {
7066: # prefix that has a part already
7067: $keyroot=$prefix;
7068: } elsif (defined($prefix)) {
7069: # prefix that is missing a part
7070: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
7071: } else {
7072: # no prefix at all
7073: if (defined($part)) { $keyroot='_'.$part; }
7074: }
7075: return $keyroot;
7076: }
7077:
1.71 www 7078: # ---------------------------------------------------------------- Get metadata
7079:
1.599 albertel 7080: my %metaentry;
1.71 www 7081: sub metadata {
1.176 www 7082: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 7083: $uri=&declutter($uri);
1.288 albertel 7084: # if it is a non metadata possible uri return quickly
1.529 albertel 7085: if (($uri eq '') ||
7086: (($uri =~ m|^/*adm/|) &&
1.698 albertel 7087: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 7088: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
7089: return undef;
7090: }
7091: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
7092: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 7093: return undef;
1.288 albertel 7094: }
1.73 www 7095: my $filename=$uri;
7096: $uri=~s/\.meta$//;
1.172 www 7097: #
7098: # Is the metadata already cached?
1.177 www 7099: # Look at timestamp of caching
1.172 www 7100: # Everything is cached by the main uri, libraries are never directly cached
7101: #
1.428 albertel 7102: if (!defined($liburi)) {
1.599 albertel 7103: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 7104: if (defined($cached)) { return $result->{':'.$what}; }
7105: }
7106: {
1.172 www 7107: #
7108: # Is this a recursive call for a library?
7109: #
1.599 albertel 7110: # if (! exists($metacache{$uri})) {
7111: # $metacache{$uri}={};
7112: # }
1.924 albertel 7113: my $cachetime = 60*60;
1.171 www 7114: if ($liburi) {
7115: $liburi=&declutter($liburi);
7116: $filename=$liburi;
1.401 bowersj2 7117: } else {
1.599 albertel 7118: &devalidate_cache_new('meta',$uri);
7119: undef(%metaentry);
1.401 bowersj2 7120: }
1.140 www 7121: my %metathesekeys=();
1.73 www 7122: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 7123: my $metastring;
1.924 albertel 7124: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 7125: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 7126: $metastring =
1.929 albertel 7127: &Apache::lonnet::ssi_body($which,
1.924 albertel 7128: ('grade_target' => 'meta'));
7129: $cachetime = 1; # only want this cached in the child not long term
7130: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 7131: my $file=&filelocation('',&clutter($filename));
1.599 albertel 7132: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 7133: $metastring=&getfile($file);
1.489 albertel 7134: }
1.208 albertel 7135: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 7136: my $token;
1.140 www 7137: undef %metathesekeys;
1.71 www 7138: while ($token=$parser->get_token) {
1.339 albertel 7139: if ($token->[0] eq 'S') {
7140: if (defined($token->[2]->{'package'})) {
1.172 www 7141: #
7142: # This is a package - get package info
7143: #
1.339 albertel 7144: my $package=$token->[2]->{'package'};
7145: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7146: if (defined($token->[2]->{'id'})) {
7147: $keyroot.='_'.$token->[2]->{'id'};
7148: }
1.599 albertel 7149: if ($metaentry{':packages'}) {
7150: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 7151: } else {
1.599 albertel 7152: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 7153: }
1.736 albertel 7154: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 7155: my $part=$keyroot;
7156: $part=~s/^\_//;
1.736 albertel 7157: if ($pack_entry=~/^\Q$package\E\&/ ||
7158: $pack_entry=~/^\Q$package\E_0\&/) {
7159: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 7160: # ignore package.tab specified default values
7161: # here &package_tab_default() will fetch those
7162: if ($subp eq 'default') { next; }
1.736 albertel 7163: my $value=$packagetab{$pack_entry};
1.432 albertel 7164: my $unikey;
7165: if ($pack =~ /_0$/) {
7166: $unikey='parameter_0_'.$name;
7167: $part=0;
7168: } else {
7169: $unikey='parameter'.$keyroot.'_'.$name;
7170: }
1.339 albertel 7171: if ($subp eq 'display') {
7172: $value.=' [Part: '.$part.']';
7173: }
1.599 albertel 7174: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 7175: $metathesekeys{$unikey}=1;
1.599 albertel 7176: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7177: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 7178: }
1.599 albertel 7179: if (defined($metaentry{':'.$unikey.'.default'})) {
7180: $metaentry{':'.$unikey}=
7181: $metaentry{':'.$unikey.'.default'};
1.356 albertel 7182: }
1.339 albertel 7183: }
7184: }
7185: } else {
1.172 www 7186: #
7187: # This is not a package - some other kind of start tag
1.339 albertel 7188: #
7189: my $entry=$token->[1];
7190: my $unikey;
7191: if ($entry eq 'import') {
7192: $unikey='';
7193: } else {
7194: $unikey=$entry;
7195: }
7196: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7197:
7198: if (defined($token->[2]->{'id'})) {
7199: $unikey.='_'.$token->[2]->{'id'};
7200: }
1.175 www 7201:
1.339 albertel 7202: if ($entry eq 'import') {
1.175 www 7203: #
7204: # Importing a library here
1.339 albertel 7205: #
7206: if ($depthcount<20) {
7207: my $location=$parser->get_text('/import');
7208: my $dir=$filename;
7209: $dir=~s|[^/]*$||;
7210: $location=&filelocation($dir,$location);
1.736 albertel 7211: my $metadata =
7212: &metadata($uri,'keys', $location,$unikey,
7213: $depthcount+1);
7214: foreach my $meta (split(',',$metadata)) {
7215: $metaentry{':'.$meta}=$metaentry{':'.$meta};
7216: $metathesekeys{$meta}=1;
1.339 albertel 7217: }
7218: }
7219: } else {
7220:
7221: if (defined($token->[2]->{'name'})) {
7222: $unikey.='_'.$token->[2]->{'name'};
7223: }
7224: $metathesekeys{$unikey}=1;
1.736 albertel 7225: foreach my $param (@{$token->[3]}) {
7226: $metaentry{':'.$unikey.'.'.$param} =
7227: $token->[2]->{$param};
1.339 albertel 7228: }
7229: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 7230: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 7231: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
7232: # only ws inside the tag, and not in default, so use default
7233: # as value
1.599 albertel 7234: $metaentry{':'.$unikey}=$default;
1.908 albertel 7235: } elsif ( $internaltext =~ /\S/ ) {
7236: # something interesting inside the tag
7237: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 7238: } else {
1.908 albertel 7239: # no interesting values, don't set a default
1.339 albertel 7240: }
1.172 www 7241: # end of not-a-package not-a-library import
1.339 albertel 7242: }
1.172 www 7243: # end of not-a-package start tag
1.339 albertel 7244: }
1.172 www 7245: # the next is the end of "start tag"
1.339 albertel 7246: }
7247: }
1.483 albertel 7248: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 7249: $extension = lc($extension);
7250: if ($extension eq 'htm') { $extension='html'; }
7251:
1.737 albertel 7252: foreach my $key (keys(%packagetab)) {
1.483 albertel 7253: #no specific packages #how's our extension
7254: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 7255: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 7256: \%metathesekeys);
7257: }
1.883 albertel 7258:
7259: if (!exists($metaentry{':packages'})
7260: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 7261: foreach my $key (keys(%packagetab)) {
1.483 albertel 7262: #no specific packages well let's get default then
7263: if ($key!~/^default&/) { next; }
1.488 albertel 7264: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 7265: \%metathesekeys);
7266: }
7267: }
1.338 www 7268: # are there custom rights to evaluate
1.599 albertel 7269: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 7270:
1.338 www 7271: #
7272: # Importing a rights file here
1.339 albertel 7273: #
7274: unless ($depthcount) {
1.599 albertel 7275: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 7276: my $dir=$filename;
7277: $dir=~s|[^/]*$||;
7278: $location=&filelocation($dir,$location);
1.736 albertel 7279: my $rights_metadata =
7280: &metadata($uri,'keys',$location,'_rights',
7281: $depthcount+1);
7282: foreach my $rights (split(',',$rights_metadata)) {
7283: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
7284: $metathesekeys{$rights}=1;
1.339 albertel 7285: }
7286: }
7287: }
1.737 albertel 7288: # uniqifiy package listing
7289: my %seen;
7290: my @uniq_packages =
7291: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
7292: $metaentry{':packages'} = join(',',@uniq_packages);
7293:
7294: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 7295: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
7296: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 7297: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 7298: # this is the end of "was not already recently cached
1.71 www 7299: }
1.599 albertel 7300: return $metaentry{':'.$what};
1.261 albertel 7301: }
7302:
1.488 albertel 7303: sub metadata_create_package_def {
1.483 albertel 7304: my ($uri,$key,$package,$metathesekeys)=@_;
7305: my ($pack,$name,$subp)=split(/\&/,$key);
7306: if ($subp eq 'default') { next; }
7307:
1.599 albertel 7308: if (defined($metaentry{':packages'})) {
7309: $metaentry{':packages'}.=','.$package;
1.483 albertel 7310: } else {
1.599 albertel 7311: $metaentry{':packages'}=$package;
1.483 albertel 7312: }
7313: my $value=$packagetab{$key};
7314: my $unikey;
7315: $unikey='parameter_0_'.$name;
1.599 albertel 7316: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 7317: $$metathesekeys{$unikey}=1;
1.599 albertel 7318: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7319: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 7320: }
1.599 albertel 7321: if (defined($metaentry{':'.$unikey.'.default'})) {
7322: $metaentry{':'.$unikey}=
7323: $metaentry{':'.$unikey.'.default'};
1.483 albertel 7324: }
7325: }
7326:
1.261 albertel 7327: sub metadata_generate_part0 {
7328: my ($metadata,$metacache,$uri) = @_;
7329: my %allnames;
1.737 albertel 7330: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 7331: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 7332: my $part=$$metacache{':'.$metakey.'.part'};
7333: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 7334: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 7335: $allnames{$name}=$part;
7336: }
7337: }
7338: }
7339: foreach my $name (keys(%allnames)) {
7340: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 7341: my $key=":parameter_0_$name";
1.261 albertel 7342: $$metacache{"$key.part"}='0';
7343: $$metacache{"$key.name"}=$name;
1.428 albertel 7344: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 7345: $allnames{$name}.'_'.$name.
7346: '.type'};
1.428 albertel 7347: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 7348: '.display'};
1.644 www 7349: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 7350: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 7351: $$metacache{"$key.display"}=$olddis;
7352: }
1.71 www 7353: }
7354:
1.764 albertel 7355: # ------------------------------------------------------ Devalidate title cache
7356:
7357: sub devalidate_title_cache {
7358: my ($url)=@_;
7359: if (!$env{'request.course.id'}) { return; }
7360: my $symb=&symbread($url);
7361: if (!$symb) { return; }
7362: my $key=$env{'request.course.id'}."\0".$symb;
7363: &devalidate_cache_new('title',$key);
7364: }
7365:
1.301 www 7366: # ------------------------------------------------- Get the title of a resource
7367:
7368: sub gettitle {
7369: my $urlsymb=shift;
7370: my $symb=&symbread($urlsymb);
1.534 albertel 7371: if ($symb) {
1.620 albertel 7372: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 7373: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 7374: if (defined($cached)) {
7375: return $result;
7376: }
1.534 albertel 7377: my ($map,$resid,$url)=&decode_symb($symb);
7378: my $title='';
1.907 albertel 7379: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
7380: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
7381: } else {
7382: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7383: &GDBM_READER(),0640)) {
7384: my $mapid=$bighash{'map_pc_'.&clutter($map)};
7385: $title=$bighash{'title_'.$mapid.'.'.$resid};
7386: untie(%bighash);
7387: }
1.534 albertel 7388: }
7389: $title=~s/\&colon\;/\:/gs;
7390: if ($title) {
1.599 albertel 7391: return &do_cache_new('title',$key,$title,600);
1.534 albertel 7392: }
7393: $urlsymb=$url;
7394: }
7395: my $title=&metadata($urlsymb,'title');
7396: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
7397: return $title;
1.301 www 7398: }
1.613 albertel 7399:
1.614 albertel 7400: sub get_slot {
7401: my ($which,$cnum,$cdom)=@_;
7402: if (!$cnum || !$cdom) {
1.790 albertel 7403: (undef,my $courseid)=&whichuser();
1.620 albertel 7404: $cdom=$env{'course.'.$courseid.'.domain'};
7405: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 7406: }
1.703 albertel 7407: my $key=join("\0",'slots',$cdom,$cnum,$which);
7408: my %slotinfo;
7409: if (exists($remembered{$key})) {
7410: $slotinfo{$which} = $remembered{$key};
7411: } else {
7412: %slotinfo=&get('slots',[$which],$cdom,$cnum);
7413: &Apache::lonhomework::showhash(%slotinfo);
7414: my ($tmp)=keys(%slotinfo);
7415: if ($tmp=~/^error:/) { return (); }
7416: $remembered{$key} = $slotinfo{$which};
7417: }
1.616 albertel 7418: if (ref($slotinfo{$which}) eq 'HASH') {
7419: return %{$slotinfo{$which}};
7420: }
7421: return $slotinfo{$which};
1.614 albertel 7422: }
1.31 www 7423: # ------------------------------------------------- Update symbolic store links
7424:
7425: sub symblist {
7426: my ($mapname,%newhash)=@_;
1.438 www 7427: $mapname=&deversion(&declutter($mapname));
1.31 www 7428: my %hash;
1.620 albertel 7429: if (($env{'request.course.fn'}) && (%newhash)) {
7430: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7431: &GDBM_WRCREAT(),0640)) {
1.711 albertel 7432: foreach my $url (keys %newhash) {
7433: next if ($url eq 'last_known'
7434: && $env{'form.no_update_last_known'});
7435: $hash{declutter($url)}=&encode_symb($mapname,
7436: $newhash{$url}->[1],
7437: $newhash{$url}->[0]);
1.191 harris41 7438: }
1.31 www 7439: if (untie(%hash)) {
7440: return 'ok';
7441: }
7442: }
7443: }
7444: return 'error';
1.212 www 7445: }
7446:
7447: # --------------------------------------------------------------- Verify a symb
7448:
7449: sub symbverify {
1.510 www 7450: my ($symb,$thisurl)=@_;
7451: my $thisfn=$thisurl;
1.439 www 7452: $thisfn=&declutter($thisfn);
1.215 www 7453: # direct jump to resource in page or to a sequence - will construct own symbs
7454: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
7455: # check URL part
1.409 www 7456: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 7457:
1.431 www 7458: unless ($url eq $thisfn) { return 0; }
1.213 www 7459:
1.216 www 7460: $symb=&symbclean($symb);
1.510 www 7461: $thisurl=&deversion($thisurl);
1.439 www 7462: $thisfn=&deversion($thisfn);
1.213 www 7463:
7464: my %bighash;
7465: my $okay=0;
1.431 www 7466:
1.620 albertel 7467: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7468: &GDBM_READER(),0640)) {
1.510 www 7469: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 7470: unless ($ids) {
1.510 www 7471: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 7472: }
7473: if ($ids) {
7474: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 7475: foreach my $id (split(/\,/,$ids)) {
7476: my ($mapid,$resid)=split(/\./,$id);
1.216 www 7477: if (
7478: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
7479: eq $symb) {
1.620 albertel 7480: if (($env{'request.role.adv'}) ||
1.800 albertel 7481: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 7482: $okay=1;
7483: }
7484: }
1.216 www 7485: }
7486: }
1.213 www 7487: untie(%bighash);
7488: }
7489: return $okay;
1.31 www 7490: }
7491:
1.210 www 7492: # --------------------------------------------------------------- Clean-up symb
7493:
7494: sub symbclean {
7495: my $symb=shift;
1.568 albertel 7496: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 7497: # remove version from map
7498: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 7499:
1.210 www 7500: # remove version from URL
7501: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 7502:
1.507 www 7503: # remove wrapper
7504:
1.510 www 7505: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 7506: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 7507: return $symb;
1.409 www 7508: }
7509:
7510: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 7511:
7512: sub encode_symb {
7513: my ($map,$resid,$url)=@_;
7514: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
7515: }
1.409 www 7516:
7517: sub decode_symb {
1.568 albertel 7518: my $symb=shift;
7519: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
7520: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 7521: return (&fixversion($map),$resid,&fixversion($url));
7522: }
7523:
7524: sub fixversion {
7525: my $fn=shift;
1.609 banghart 7526: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 7527: my %bighash;
7528: my $uri=&clutter($fn);
1.620 albertel 7529: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 7530: # is this cached?
1.599 albertel 7531: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 7532: if (defined($cached)) { return $result; }
7533: # unfortunately not cached, or expired
1.620 albertel 7534: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 7535: &GDBM_READER(),0640)) {
7536: if ($bighash{'version_'.$uri}) {
7537: my $version=$bighash{'version_'.$uri};
1.444 www 7538: unless (($version eq 'mostrecent') ||
7539: ($version==&getversion($uri))) {
1.440 www 7540: $uri=~s/\.(\w+)$/\.$version\.$1/;
7541: }
7542: }
7543: untie %bighash;
1.413 www 7544: }
1.599 albertel 7545: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 7546: }
7547:
7548: sub deversion {
7549: my $url=shift;
7550: $url=~s/\.\d+\.(\w+)$/\.$1/;
7551: return $url;
1.210 www 7552: }
7553:
1.31 www 7554: # ------------------------------------------------------ Return symb list entry
7555:
7556: sub symbread {
1.249 www 7557: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 7558: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 7559: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 7560: # no filename provided? try from environment
1.44 www 7561: unless ($thisfn) {
1.620 albertel 7562: if ($env{'request.symb'}) {
7563: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 7564: }
1.620 albertel 7565: $thisfn=$env{'request.filename'};
1.44 www 7566: }
1.569 albertel 7567: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 7568: # is that filename actually a symb? Verify, clean, and return
7569: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 7570: if (&symbverify($thisfn,$1)) {
1.620 albertel 7571: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 7572: }
1.242 www 7573: }
1.44 www 7574: $thisfn=declutter($thisfn);
1.31 www 7575: my %hash;
1.37 www 7576: my %bighash;
7577: my $syval='';
1.620 albertel 7578: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 7579: my $targetfn = $thisfn;
1.609 banghart 7580: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 7581: $targetfn = 'adm/wrapper/'.$thisfn;
7582: }
1.687 albertel 7583: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
7584: $targetfn=$1;
7585: }
1.620 albertel 7586: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 7587: &GDBM_READER(),0640)) {
1.481 raeburn 7588: $syval=$hash{$targetfn};
1.37 www 7589: untie(%hash);
7590: }
7591: # ---------------------------------------------------------- There was an entry
7592: if ($syval) {
1.601 albertel 7593: #unless ($syval=~/\_\d+$/) {
1.620 albertel 7594: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 7595: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 7596: #return $env{$cache_str}='';
1.601 albertel 7597: #}
7598: #$syval.=$1;
7599: #}
1.37 www 7600: } else {
7601: # ------------------------------------------------------- Was not in symb table
1.620 albertel 7602: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 7603: &GDBM_READER(),0640)) {
1.37 www 7604: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 7605: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 7606: unless ($ids) {
7607: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 7608: }
7609: unless ($ids) {
7610: # alias?
7611: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 7612: }
1.37 www 7613: if ($ids) {
7614: # ------------------------------------------------------------------- Has ID(s)
7615: my @possibilities=split(/\,/,$ids);
1.39 www 7616: if ($#possibilities==0) {
7617: # ----------------------------------------------- There is only one possibility
1.37 www 7618: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 7619: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7620: $resid,$thisfn);
1.249 www 7621: } elsif (!$donotrecurse) {
1.39 www 7622: # ------------------------------------------ There is more than one possibility
7623: my $realpossible=0;
1.800 albertel 7624: foreach my $id (@possibilities) {
7625: my $file=$bighash{'src_'.$id};
1.39 www 7626: if (&allowed('bre',$file)) {
1.800 albertel 7627: my ($mapid,$resid)=split(/\./,$id);
1.39 www 7628: if ($bighash{'map_type_'.$mapid} ne 'page') {
7629: $realpossible++;
1.626 albertel 7630: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7631: $resid,$thisfn);
1.39 www 7632: }
7633: }
1.191 harris41 7634: }
1.39 www 7635: if ($realpossible!=1) { $syval=''; }
1.249 www 7636: } else {
7637: $syval='';
1.37 www 7638: }
7639: }
7640: untie(%bighash)
1.481 raeburn 7641: }
1.31 www 7642: }
1.62 www 7643: if ($syval) {
1.620 albertel 7644: return $env{$cache_str}=$syval;
1.62 www 7645: }
1.31 www 7646: }
1.949 raeburn 7647: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 7648: return $env{$cache_str}='';
1.31 www 7649: }
7650:
7651: # ---------------------------------------------------------- Return random seed
7652:
1.32 www 7653: sub numval {
7654: my $txt=shift;
7655: $txt=~tr/A-J/0-9/;
7656: $txt=~tr/a-j/0-9/;
7657: $txt=~tr/K-T/0-9/;
7658: $txt=~tr/k-t/0-9/;
7659: $txt=~tr/U-Z/0-5/;
7660: $txt=~tr/u-z/0-5/;
7661: $txt=~s/\D//g;
1.564 albertel 7662: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 7663: return int($txt);
1.368 albertel 7664: }
7665:
1.484 albertel 7666: sub numval2 {
7667: my $txt=shift;
7668: $txt=~tr/A-J/0-9/;
7669: $txt=~tr/a-j/0-9/;
7670: $txt=~tr/K-T/0-9/;
7671: $txt=~tr/k-t/0-9/;
7672: $txt=~tr/U-Z/0-5/;
7673: $txt=~tr/u-z/0-5/;
7674: $txt=~s/\D//g;
7675: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7676: my $total;
7677: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 7678: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 7679: return int($total);
7680: }
7681:
1.575 albertel 7682: sub numval3 {
7683: use integer;
7684: my $txt=shift;
7685: $txt=~tr/A-J/0-9/;
7686: $txt=~tr/a-j/0-9/;
7687: $txt=~tr/K-T/0-9/;
7688: $txt=~tr/k-t/0-9/;
7689: $txt=~tr/U-Z/0-5/;
7690: $txt=~tr/u-z/0-5/;
7691: $txt=~s/\D//g;
7692: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7693: my $total;
7694: foreach my $val (@txts) { $total+=$val; }
7695: if ($_64bit) { $total=(($total<<32)>>32); }
7696: return $total;
7697: }
7698:
1.675 albertel 7699: sub digest {
7700: my ($data)=@_;
7701: my $digest=&Digest::MD5::md5($data);
7702: my ($a,$b,$c,$d)=unpack("iiii",$digest);
7703: my ($e,$f);
7704: {
7705: use integer;
7706: $e=($a+$b);
7707: $f=($c+$d);
7708: if ($_64bit) {
7709: $e=(($e<<32)>>32);
7710: $f=(($f<<32)>>32);
7711: }
7712: }
7713: if (wantarray) {
7714: return ($e,$f);
7715: } else {
7716: my $g;
7717: {
7718: use integer;
7719: $g=($e+$f);
7720: if ($_64bit) {
7721: $g=(($g<<32)>>32);
7722: }
7723: }
7724: return $g;
7725: }
7726: }
7727:
1.368 albertel 7728: sub latest_rnd_algorithm_id {
1.675 albertel 7729: return '64bit5';
1.366 albertel 7730: }
1.32 www 7731:
1.503 albertel 7732: sub get_rand_alg {
7733: my ($courseid)=@_;
1.790 albertel 7734: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 7735: if ($courseid) {
1.620 albertel 7736: return $env{"course.$courseid.rndseed"};
1.503 albertel 7737: }
7738: return &latest_rnd_algorithm_id();
7739: }
7740:
1.562 albertel 7741: sub validCODE {
7742: my ($CODE)=@_;
7743: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
7744: return 0;
7745: }
7746:
1.491 albertel 7747: sub getCODE {
1.620 albertel 7748: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 7749: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
7750: defined($Apache::lonhomework::parsing_a_task) ) &&
7751: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 7752: return $Apache::lonhomework::history{'resource.CODE'};
7753: }
7754: return undef;
7755: }
7756:
1.31 www 7757: sub rndseed {
1.155 albertel 7758: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 7759: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 7760: if (!defined($symb)) {
1.366 albertel 7761: unless ($symb=$wsymb) { return time; }
7762: }
7763: if (!$courseid) { $courseid=$wcourseid; }
7764: if (!$domain) { $domain=$wdomain; }
7765: if (!$username) { $username=$wusername }
1.503 albertel 7766: my $which=&get_rand_alg();
1.803 albertel 7767:
1.491 albertel 7768: if (defined(&getCODE())) {
1.675 albertel 7769: if ($which eq '64bit5') {
7770: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
7771: } elsif ($which eq '64bit4') {
1.575 albertel 7772: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
7773: } else {
7774: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
7775: }
1.675 albertel 7776: } elsif ($which eq '64bit5') {
7777: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 7778: } elsif ($which eq '64bit4') {
7779: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 7780: } elsif ($which eq '64bit3') {
7781: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 7782: } elsif ($which eq '64bit2') {
7783: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 7784: } elsif ($which eq '64bit') {
7785: return &rndseed_64bit($symb,$courseid,$domain,$username);
7786: }
7787: return &rndseed_32bit($symb,$courseid,$domain,$username);
7788: }
7789:
7790: sub rndseed_32bit {
7791: my ($symb,$courseid,$domain,$username)=@_;
7792: {
7793: use integer;
7794: my $symbchck=unpack("%32C*",$symb) << 27;
7795: my $symbseed=numval($symb) << 22;
7796: my $namechck=unpack("%32C*",$username) << 17;
7797: my $nameseed=numval($username) << 12;
7798: my $domainseed=unpack("%32C*",$domain) << 7;
7799: my $courseseed=unpack("%32C*",$courseid);
7800: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 7801: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7802: #&logthis("rndseed :$num:$symb");
1.564 albertel 7803: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 7804: return $num;
7805: }
7806: }
7807:
7808: sub rndseed_64bit {
7809: my ($symb,$courseid,$domain,$username)=@_;
7810: {
7811: use integer;
7812: my $symbchck=unpack("%32S*",$symb) << 21;
7813: my $symbseed=numval($symb) << 10;
7814: my $namechck=unpack("%32S*",$username);
7815:
7816: my $nameseed=numval($username) << 21;
7817: my $domainseed=unpack("%32S*",$domain) << 10;
7818: my $courseseed=unpack("%32S*",$courseid);
7819:
7820: my $num1=$symbchck+$symbseed+$namechck;
7821: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7822: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7823: #&logthis("rndseed :$num:$symb");
1.564 albertel 7824: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 7825: return "$num1,$num2";
1.155 albertel 7826: }
1.366 albertel 7827: }
7828:
1.443 albertel 7829: sub rndseed_64bit2 {
7830: my ($symb,$courseid,$domain,$username)=@_;
7831: {
7832: use integer;
7833: # strings need to be an even # of cahracters long, it it is odd the
7834: # last characters gets thrown away
7835: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7836: my $symbseed=numval($symb) << 10;
7837: my $namechck=unpack("%32S*",$username.' ');
7838:
7839: my $nameseed=numval($username) << 21;
1.501 albertel 7840: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7841: my $courseseed=unpack("%32S*",$courseid.' ');
7842:
7843: my $num1=$symbchck+$symbseed+$namechck;
7844: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7845: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7846: #&logthis("rndseed :$num:$symb");
1.803 albertel 7847: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 7848: return "$num1,$num2";
7849: }
7850: }
7851:
7852: sub rndseed_64bit3 {
7853: my ($symb,$courseid,$domain,$username)=@_;
7854: {
7855: use integer;
7856: # strings need to be an even # of cahracters long, it it is odd the
7857: # last characters gets thrown away
7858: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7859: my $symbseed=numval2($symb) << 10;
7860: my $namechck=unpack("%32S*",$username.' ');
7861:
7862: my $nameseed=numval2($username) << 21;
1.443 albertel 7863: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7864: my $courseseed=unpack("%32S*",$courseid.' ');
7865:
7866: my $num1=$symbchck+$symbseed+$namechck;
7867: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7868: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7869: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 7870: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7871:
1.503 albertel 7872: return "$num1:$num2";
1.443 albertel 7873: }
7874: }
7875:
1.575 albertel 7876: sub rndseed_64bit4 {
7877: my ($symb,$courseid,$domain,$username)=@_;
7878: {
7879: use integer;
7880: # strings need to be an even # of cahracters long, it it is odd the
7881: # last characters gets thrown away
7882: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7883: my $symbseed=numval3($symb) << 10;
7884: my $namechck=unpack("%32S*",$username.' ');
7885:
7886: my $nameseed=numval3($username) << 21;
7887: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7888: my $courseseed=unpack("%32S*",$courseid.' ');
7889:
7890: my $num1=$symbchck+$symbseed+$namechck;
7891: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7892: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7893: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 7894: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7895:
7896: return "$num1:$num2";
7897: }
7898: }
7899:
1.675 albertel 7900: sub rndseed_64bit5 {
7901: my ($symb,$courseid,$domain,$username)=@_;
7902: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
7903: return "$num1:$num2";
7904: }
7905:
1.366 albertel 7906: sub rndseed_CODE_64bit {
7907: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 7908: {
1.366 albertel 7909: use integer;
1.443 albertel 7910: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 7911: my $symbseed=numval2($symb);
1.491 albertel 7912: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7913: my $CODEseed=numval(&getCODE());
1.443 albertel 7914: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 7915: my $num1=$symbseed+$CODEchck;
7916: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7917: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7918: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 7919: if ($_64bit) { $num1=(($num1<<32)>>32); }
7920: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 7921: return "$num1:$num2";
1.366 albertel 7922: }
7923: }
7924:
1.575 albertel 7925: sub rndseed_CODE_64bit4 {
7926: my ($symb,$courseid,$domain,$username)=@_;
7927: {
7928: use integer;
7929: my $symbchck=unpack("%32S*",$symb.' ') << 16;
7930: my $symbseed=numval3($symb);
7931: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7932: my $CODEseed=numval3(&getCODE());
7933: my $courseseed=unpack("%32S*",$courseid.' ');
7934: my $num1=$symbseed+$CODEchck;
7935: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7936: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7937: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 7938: if ($_64bit) { $num1=(($num1<<32)>>32); }
7939: if ($_64bit) { $num2=(($num2<<32)>>32); }
7940: return "$num1:$num2";
7941: }
7942: }
7943:
1.675 albertel 7944: sub rndseed_CODE_64bit5 {
7945: my ($symb,$courseid,$domain,$username)=@_;
7946: my $code = &getCODE();
7947: my ($num1,$num2)=&digest("$symb,$courseid,$code");
7948: return "$num1:$num2";
7949: }
7950:
1.366 albertel 7951: sub setup_random_from_rndseed {
7952: my ($rndseed)=@_;
1.503 albertel 7953: if ($rndseed =~/([,:])/) {
7954: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 7955: &Math::Random::random_set_seed(abs($num1),abs($num2));
7956: } else {
7957: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 7958: }
1.36 albertel 7959: }
7960:
1.474 albertel 7961: sub latest_receipt_algorithm_id {
1.835 albertel 7962: return 'receipt3';
1.474 albertel 7963: }
7964:
1.480 www 7965: sub recunique {
7966: my $fucourseid=shift;
7967: my $unique;
1.835 albertel 7968: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
7969: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7970: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 7971: } else {
7972: $unique=$perlvar{'lonReceipt'};
7973: }
7974: return unpack("%32C*",$unique);
7975: }
7976:
7977: sub recprefix {
7978: my $fucourseid=shift;
7979: my $prefix;
1.835 albertel 7980: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
7981: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7982: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 7983: } else {
7984: $prefix=$perlvar{'lonHostID'};
7985: }
7986: return unpack("%32C*",$prefix);
7987: }
7988:
1.76 www 7989: sub ireceipt {
1.474 albertel 7990: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 7991:
7992: my $return =&recprefix($fucourseid).'-';
7993:
7994: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
7995: $env{'request.state'} eq 'construct') {
7996: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
7997: return $return;
7998: }
7999:
1.76 www 8000: my $cuname=unpack("%32C*",$funame);
8001: my $cudom=unpack("%32C*",$fudom);
8002: my $cucourseid=unpack("%32C*",$fucourseid);
8003: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 8004: my $cunique=&recunique($fucourseid);
1.474 albertel 8005: my $cpart=unpack("%32S*",$part);
1.835 albertel 8006: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
8007:
1.790 albertel 8008: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 8009:
8010: $return.= ($cunique%$cuname+
8011: $cunique%$cudom+
8012: $cusymb%$cuname+
8013: $cusymb%$cudom+
8014: $cucourseid%$cuname+
8015: $cucourseid%$cudom+
8016: $cpart%$cuname+
8017: $cpart%$cudom);
8018: } else {
8019: $return.= ($cunique%$cuname+
8020: $cunique%$cudom+
8021: $cusymb%$cuname+
8022: $cusymb%$cudom+
8023: $cucourseid%$cuname+
8024: $cucourseid%$cudom);
8025: }
8026: return $return;
1.76 www 8027: }
8028:
8029: sub receipt {
1.474 albertel 8030: my ($part)=@_;
1.790 albertel 8031: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 8032: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 8033: }
1.260 ng 8034:
1.790 albertel 8035: sub whichuser {
8036: my ($passedsymb)=@_;
8037: my ($symb,$courseid,$domain,$name,$publicuser);
8038: if (defined($env{'form.grade_symb'})) {
8039: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
8040: my $allowed=&allowed('vgr',$tmp_courseid);
8041: if (!$allowed &&
8042: exists($env{'request.course.sec'}) &&
8043: $env{'request.course.sec'} !~ /^\s*$/) {
8044: $allowed=&allowed('vgr',$tmp_courseid.
8045: '/'.$env{'request.course.sec'});
8046: }
8047: if ($allowed) {
8048: ($symb)=&get_env_multiple('form.grade_symb');
8049: $courseid=$tmp_courseid;
8050: ($domain)=&get_env_multiple('form.grade_domain');
8051: ($name)=&get_env_multiple('form.grade_username');
8052: return ($symb,$courseid,$domain,$name,$publicuser);
8053: }
8054: }
8055: if (!$passedsymb) {
8056: $symb=&symbread();
8057: } else {
8058: $symb=$passedsymb;
8059: }
8060: $courseid=$env{'request.course.id'};
8061: $domain=$env{'user.domain'};
8062: $name=$env{'user.name'};
8063: if ($name eq 'public' && $domain eq 'public') {
8064: if (!defined($env{'form.username'})) {
8065: $env{'form.username'}.=time.rand(10000000);
8066: }
8067: $name.=$env{'form.username'};
8068: }
8069: return ($symb,$courseid,$domain,$name,$publicuser);
8070:
8071: }
8072:
1.36 albertel 8073: # ------------------------------------------------------------ Serves up a file
1.472 albertel 8074: # returns either the contents of the file or
8075: # -1 if the file doesn't exist
1.481 raeburn 8076: #
8077: # if the target is a file that was uploaded via DOCS,
8078: # a check will be made to see if a current copy exists on the local server,
8079: # if it does this will be served, otherwise a copy will be retrieved from
8080: # the home server for the course and stored in /home/httpd/html/userfiles on
8081: # the local server.
1.472 albertel 8082:
1.36 albertel 8083: sub getfile {
1.538 albertel 8084: my ($file) = @_;
1.609 banghart 8085: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 8086: &repcopy($file);
8087: return &readfile($file);
8088: }
8089:
8090: sub repcopy_userfile {
8091: my ($file)=@_;
1.609 banghart 8092: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 8093: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 8094: my ($cdom,$cnum,$filename) =
1.811 albertel 8095: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 8096: my $uri="/uploaded/$cdom/$cnum/$filename";
8097: if (-e "$file") {
1.828 www 8098: # we already have a local copy, check it out
1.538 albertel 8099: my @fileinfo = stat($file);
1.828 www 8100: my $rtncode;
8101: my $info;
1.538 albertel 8102: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 8103: if ($lwpresp ne 'ok') {
1.828 www 8104: # there is no such file anymore, even though we had a local copy
1.482 albertel 8105: if ($rtncode eq '404') {
1.538 albertel 8106: unlink($file);
1.482 albertel 8107: }
8108: return -1;
8109: }
8110: if ($info < $fileinfo[9]) {
1.828 www 8111: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 8112: return 'ok';
1.828 www 8113: } else {
8114: # the file is outdated, get rid of it
8115: unlink($file);
1.482 albertel 8116: }
1.828 www 8117: }
8118: # one way or the other, at this point, we don't have the file
8119: # construct the correct path for the file
8120: my @parts = ($cdom,$cnum);
8121: if ($filename =~ m|^(.+)/[^/]+$|) {
8122: push @parts, split(/\//,$1);
8123: }
8124: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
8125: foreach my $part (@parts) {
8126: $path .= '/'.$part;
8127: if (!-e $path) {
8128: mkdir($path,0770);
1.482 albertel 8129: }
8130: }
1.828 www 8131: # now the path exists for sure
8132: # get a user agent
8133: my $ua=new LWP::UserAgent;
8134: my $transferfile=$file.'.in.transfer';
8135: # FIXME: this should flock
8136: if (-e $transferfile) { return 'ok'; }
8137: my $request;
8138: $uri=~s/^\///;
1.838 albertel 8139: $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828 www 8140: my $response=$ua->request($request,$transferfile);
8141: # did it work?
8142: if ($response->is_error()) {
8143: unlink($transferfile);
8144: &logthis("Userfile repcopy failed for $uri");
8145: return -1;
8146: }
8147: # worked, rename the transfer file
8148: rename($transferfile,$file);
1.607 raeburn 8149: return 'ok';
1.481 raeburn 8150: }
8151:
1.517 albertel 8152: sub tokenwrapper {
8153: my $uri=shift;
1.552 albertel 8154: $uri=~s|^http\://([^/]+)||;
8155: $uri=~s|^/||;
1.620 albertel 8156: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 8157: my $token=$1;
1.552 albertel 8158: my (undef,$udom,$uname,$file)=split('/',$uri,4);
8159: if ($udom && $uname && $file) {
8160: $file=~s|(\?\.*)*$||;
1.949 raeburn 8161: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.838 albertel 8162: return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517 albertel 8163: (($uri=~/\?/)?'&':'?').'token='.$token.
8164: '&tokenissued='.$perlvar{'lonHostID'};
8165: } else {
8166: return '/adm/notfound.html';
8167: }
8168: }
8169:
1.828 www 8170: # call with reqtype HEAD: get last modification time
8171: # call with reqtype GET: get the file contents
8172: # Do not call this with reqtype GET for large files! It loads everything into memory
8173: #
1.481 raeburn 8174: sub getuploaded {
8175: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
8176: $uri=~s/^\///;
1.838 albertel 8177: $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481 raeburn 8178: my $ua=new LWP::UserAgent;
8179: my $request=new HTTP::Request($reqtype,$uri);
8180: my $response=$ua->request($request);
8181: $$rtncode = $response->code;
1.482 albertel 8182: if (! $response->is_success()) {
8183: return 'failed';
8184: }
8185: if ($reqtype eq 'HEAD') {
1.486 www 8186: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 8187: } elsif ($reqtype eq 'GET') {
8188: $$info = $response->content;
1.472 albertel 8189: }
1.482 albertel 8190: return 'ok';
1.36 albertel 8191: }
8192:
1.481 raeburn 8193: sub readfile {
8194: my $file = shift;
8195: if ( (! -e $file ) || ($file eq '') ) { return -1; };
8196: my $fh;
8197: open($fh,"<$file");
8198: my $a='';
1.800 albertel 8199: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 8200: return $a;
8201: }
8202:
1.36 albertel 8203: sub filelocation {
1.590 banghart 8204: my ($dir,$file) = @_;
8205: my $location;
8206: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 8207:
8208: if ($file =~ m-^/adm/-) {
8209: $file=~s-^/adm/wrapper/-/-;
8210: $file=~s-^/adm/coursedocs/showdoc/-/-;
8211: }
1.882 albertel 8212:
1.590 banghart 8213: if ($file=~m:^/~:) { # is a contruction space reference
8214: $location = $file;
8215: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 8216: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 8217: # is a correct contruction space reference
8218: $location = $file;
1.956 raeburn 8219: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
8220: $location = $file;
1.609 banghart 8221: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 8222: my ($udom,$uname,$filename)=
1.811 albertel 8223: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 8224: my $home=&homeserver($uname,$udom);
8225: my $is_me=0;
8226: my @ids=¤t_machine_ids();
8227: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
8228: if ($is_me) {
1.955 raeburn 8229: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 8230: } else {
8231: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
8232: $udom.'/'.$uname.'/'.$filename;
8233: }
1.882 albertel 8234: } elsif ($file =~ m-^/adm/-) {
8235: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 8236: } else {
8237: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
8238: $file=~s:^/res/:/:;
8239: if ( !( $file =~ m:^/:) ) {
8240: $location = $dir. '/'.$file;
8241: } else {
8242: $location = '/home/httpd/html/res'.$file;
8243: }
1.59 albertel 8244: }
1.590 banghart 8245: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 8246: while ($location=~m{/\.\./}) {
8247: if ($location =~ m{/[^/]+/\.\./}) {
8248: $location=~ s{/[^/]+/\.\./}{/}g;
8249: } else {
8250: $location=~ s{/\.\./}{/}g;
8251: }
8252: } #remove dir/..
1.590 banghart 8253: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
8254: return $location;
1.46 www 8255: }
1.36 albertel 8256:
1.46 www 8257: sub hreflocation {
8258: my ($dir,$file)=@_;
1.460 albertel 8259: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666 albertel 8260: $file=filelocation($dir,$file);
1.700 albertel 8261: } elsif ($file=~m-^/adm/-) {
8262: $file=~s-^/adm/wrapper/-/-;
8263: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 8264: }
8265: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
8266: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 8267: } elsif ($file=~m-/home/($match_username)/public_html/-) {
8268: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 8269: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 8270: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 8271: -/uploaded/$1/$2/-x;
1.46 www 8272: }
1.913 albertel 8273: if ($file=~ m{^/userfiles/}) {
8274: $file =~ s{^/userfiles/}{/uploaded/};
8275: }
1.462 albertel 8276: return $file;
1.465 albertel 8277: }
8278:
8279: sub current_machine_domains {
1.853 albertel 8280: return &machine_domains(&hostname($perlvar{'lonHostID'}));
8281: }
8282:
8283: sub machine_domains {
8284: my ($hostname) = @_;
1.465 albertel 8285: my @domains;
1.838 albertel 8286: my %hostname = &all_hostnames();
1.465 albertel 8287: while( my($id, $name) = each(%hostname)) {
1.467 matthew 8288: # &logthis("-$id-$name-$hostname-");
1.465 albertel 8289: if ($hostname eq $name) {
1.844 albertel 8290: push(@domains,&host_domain($id));
1.465 albertel 8291: }
8292: }
8293: return @domains;
8294: }
8295:
8296: sub current_machine_ids {
1.853 albertel 8297: return &machine_ids(&hostname($perlvar{'lonHostID'}));
8298: }
8299:
8300: sub machine_ids {
8301: my ($hostname) = @_;
8302: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 8303: my @ids;
1.888 albertel 8304: my %name_to_host = &all_names();
1.889 albertel 8305: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
8306: return @{ $name_to_host{$hostname} };
8307: }
8308: return;
1.31 www 8309: }
8310:
1.824 raeburn 8311: sub additional_machine_domains {
8312: my @domains;
8313: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
8314: while( my $line = <$fh>) {
8315: $line =~ s/\s//g;
8316: push(@domains,$line);
8317: }
8318: return @domains;
8319: }
8320:
8321: sub default_login_domain {
8322: my $domain = $perlvar{'lonDefDomain'};
8323: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
8324: foreach my $posdom (¤t_machine_domains(),
8325: &additional_machine_domains()) {
8326: if (lc($posdom) eq lc($testdomain)) {
8327: $domain=$posdom;
8328: last;
8329: }
8330: }
8331: return $domain;
8332: }
8333:
1.31 www 8334: # ------------------------------------------------------------- Declutters URLs
8335:
8336: sub declutter {
8337: my $thisfn=shift;
1.569 albertel 8338: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 8339: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 8340: $thisfn=~s/^\///;
1.697 albertel 8341: $thisfn=~s|^adm/wrapper/||;
8342: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 8343: $thisfn=~s/^res\///;
1.235 www 8344: $thisfn=~s/\?.+$//;
1.268 www 8345: return $thisfn;
8346: }
8347:
8348: # ------------------------------------------------------------- Clutter up URLs
8349:
8350: sub clutter {
8351: my $thisfn='/'.&declutter(shift);
1.887 albertel 8352: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 8353: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 8354: $thisfn='/res'.$thisfn;
8355: }
1.694 albertel 8356: if ($thisfn !~m|/adm|) {
1.695 albertel 8357: if ($thisfn =~ m|/ext/|) {
1.694 albertel 8358: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 8359: } else {
8360: my ($ext) = ($thisfn =~ /\.(\w+)$/);
8361: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 8362: if ($embstyle eq 'ssi'
8363: || ($embstyle eq 'hdn')
8364: || ($embstyle eq 'rat')
8365: || ($embstyle eq 'prv')
8366: || ($embstyle eq 'ign')) {
8367: #do nothing with these
8368: } elsif (($embstyle eq 'img')
1.695 albertel 8369: || ($embstyle eq 'emb')
8370: || ($embstyle eq 'wrp')) {
8371: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 8372: } elsif ($embstyle eq 'unk'
8373: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 8374: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 8375: } else {
1.718 www 8376: # &logthis("Got a blank emb style");
1.695 albertel 8377: }
1.694 albertel 8378: }
8379: }
1.31 www 8380: return $thisfn;
1.12 www 8381: }
8382:
1.787 albertel 8383: sub clutter_with_no_wrapper {
8384: my $uri = &clutter(shift);
8385: if ($uri =~ m-^/adm/-) {
8386: $uri =~ s-^/adm/wrapper/-/-;
8387: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
8388: }
8389: return $uri;
8390: }
8391:
1.557 albertel 8392: sub freeze_escape {
8393: my ($value)=@_;
8394: if (ref($value)) {
8395: $value=&nfreeze($value);
8396: return '__FROZEN__'.&escape($value);
8397: }
8398: return &escape($value);
8399: }
8400:
1.11 www 8401:
1.557 albertel 8402: sub thaw_unescape {
8403: my ($value)=@_;
8404: if ($value =~ /^__FROZEN__/) {
8405: substr($value,0,10,undef);
8406: $value=&unescape($value);
8407: return &thaw($value);
8408: }
8409: return &unescape($value);
8410: }
8411:
1.436 albertel 8412: sub correct_line_ends {
8413: my ($result)=@_;
8414: $$result =~s/\r\n/\n/mg;
8415: $$result =~s/\r/\n/mg;
1.415 albertel 8416: }
1.1 albertel 8417: # ================================================================ Main Program
8418:
1.184 www 8419: sub goodbye {
1.204 albertel 8420: &logthis("Starting Shut down");
1.443 albertel 8421: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 8422: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 8423: #converted
1.599 albertel 8424: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 8425: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
8426: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
8427: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 8428: #1.1 only
1.870 albertel 8429: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
8430: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
8431: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
8432: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
8433: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 8434: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
8435: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 8436: &flushcourselogs();
8437: &logthis("Shutting down");
8438: }
8439:
1.852 albertel 8440: sub get_dns {
1.869 albertel 8441: my ($url,$func,$ignore_cache) = @_;
8442: if (!$ignore_cache) {
8443: my ($content,$cached)=
8444: &Apache::lonnet::is_cached_new('dns',$url);
8445: if ($cached) {
8446: &$func($content);
8447: return;
8448: }
8449: }
8450:
8451: my %alldns;
1.852 albertel 8452: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8453: foreach my $dns (<$config>) {
8454: next if ($dns !~ /^\^(\S*)/x);
1.869 albertel 8455: $alldns{$1} = 1;
8456: }
8457: while (%alldns) {
8458: my ($dns) = keys(%alldns);
8459: delete($alldns{$dns});
1.852 albertel 8460: my $ua=new LWP::UserAgent;
8461: my $request=new HTTP::Request('GET',"http://$dns$url");
8462: my $response=$ua->request($request);
8463: next if ($response->is_error());
8464: my @content = split("\n",$response->content);
1.869 albertel 8465: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 8466: &$func(\@content);
1.869 albertel 8467: return;
1.852 albertel 8468: }
8469: close($config);
1.871 albertel 8470: my $which = (split('/',$url))[3];
8471: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
8472: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 8473: my @content = <$config>;
8474: &$func(\@content);
8475: return;
1.852 albertel 8476: }
1.327 albertel 8477: # ------------------------------------------------------------ Read domain file
8478: {
1.852 albertel 8479: my $loaded;
1.846 albertel 8480: my %domain;
8481:
1.852 albertel 8482: sub parse_domain_tab {
8483: my ($lines) = @_;
8484: foreach my $line (@$lines) {
8485: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 8486:
1.846 albertel 8487: chomp($line);
1.852 albertel 8488: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 8489: my %this_domain;
8490: foreach my $field ('description', 'auth_def', 'auth_arg_def',
8491: 'lang_def', 'city', 'longi', 'lati',
8492: 'primary') {
8493: $this_domain{$field} = shift(@elements);
8494: }
8495: $domain{$name} = \%this_domain;
1.852 albertel 8496: }
8497: }
1.864 albertel 8498:
8499: sub reset_domain_info {
8500: undef($loaded);
8501: undef(%domain);
8502: }
8503:
1.852 albertel 8504: sub load_domain_tab {
1.869 albertel 8505: my ($ignore_cache) = @_;
8506: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 8507: my $fh;
8508: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
8509: my @lines = <$fh>;
8510: &parse_domain_tab(\@lines);
1.448 albertel 8511: }
1.852 albertel 8512: close($fh);
8513: $loaded = 1;
1.327 albertel 8514: }
1.846 albertel 8515:
8516: sub domain {
1.852 albertel 8517: &load_domain_tab() if (!$loaded);
8518:
1.846 albertel 8519: my ($name,$what) = @_;
8520: return if ( !exists($domain{$name}) );
8521:
8522: if (!$what) {
8523: return $domain{$name}{'description'};
8524: }
8525: return $domain{$name}{$what};
8526: }
1.327 albertel 8527: }
8528:
8529:
1.1 albertel 8530: # ------------------------------------------------------------- Read hosts file
8531: {
1.838 albertel 8532: my %hostname;
1.844 albertel 8533: my %hostdom;
1.845 albertel 8534: my %libserv;
1.852 albertel 8535: my $loaded;
1.888 albertel 8536: my %name_to_host;
1.852 albertel 8537:
8538: sub parse_hosts_tab {
8539: my ($file) = @_;
8540: foreach my $configline (@$file) {
8541: next if ($configline =~ /^(\#|\s*$ )/x);
8542: next if ($configline =~ /^\^/);
8543: chomp($configline);
1.968 raeburn 8544: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852 albertel 8545: $name=~s/\s//g;
8546: if ($id && $domain && $role && $name) {
8547: $hostname{$id}=$name;
1.888 albertel 8548: push(@{$name_to_host{$name}}, $id);
1.852 albertel 8549: $hostdom{$id}=$domain;
8550: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 8551: if (defined($protocol)) {
8552: if ($protocol eq 'https') {
8553: $protocol{$id} = $protocol;
8554: } else {
8555: $protocol{$id} = 'http';
8556: }
1.968 raeburn 8557: } else {
1.969 raeburn 8558: $protocol{$id} = 'http';
1.968 raeburn 8559: }
1.852 albertel 8560: }
8561: }
8562: }
1.864 albertel 8563:
8564: sub reset_hosts_info {
1.897 albertel 8565: &purge_remembered();
1.864 albertel 8566: &reset_domain_info();
8567: &reset_hosts_ip_info();
1.892 albertel 8568: undef(%name_to_host);
1.864 albertel 8569: undef(%hostname);
8570: undef(%hostdom);
8571: undef(%libserv);
8572: undef($loaded);
8573: }
1.1 albertel 8574:
1.852 albertel 8575: sub load_hosts_tab {
1.869 albertel 8576: my ($ignore_cache) = @_;
8577: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 8578: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8579: my @config = <$config>;
8580: &parse_hosts_tab(\@config);
8581: close($config);
8582: $loaded=1;
1.1 albertel 8583: }
1.852 albertel 8584:
1.838 albertel 8585: sub hostname {
1.852 albertel 8586: &load_hosts_tab() if (!$loaded);
8587:
1.838 albertel 8588: my ($lonid) = @_;
8589: return $hostname{$lonid};
8590: }
1.845 albertel 8591:
1.838 albertel 8592: sub all_hostnames {
1.852 albertel 8593: &load_hosts_tab() if (!$loaded);
8594:
1.838 albertel 8595: return %hostname;
8596: }
1.845 albertel 8597:
1.888 albertel 8598: sub all_names {
8599: &load_hosts_tab() if (!$loaded);
8600:
8601: return %name_to_host;
8602: }
8603:
1.845 albertel 8604: sub is_library {
1.852 albertel 8605: &load_hosts_tab() if (!$loaded);
8606:
1.845 albertel 8607: return exists($libserv{$_[0]});
8608: }
8609:
8610: sub all_library {
1.852 albertel 8611: &load_hosts_tab() if (!$loaded);
8612:
1.845 albertel 8613: return %libserv;
8614: }
8615:
1.841 albertel 8616: sub get_servers {
1.852 albertel 8617: &load_hosts_tab() if (!$loaded);
8618:
1.841 albertel 8619: my ($domain,$type) = @_;
8620: my %possible_hosts = ($type eq 'library') ? %libserv
8621: : %hostname;
8622: my %result;
1.842 albertel 8623: if (ref($domain) eq 'ARRAY') {
8624: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 8625: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 8626: $result{$host} = $hostname;
8627: }
8628: }
8629: } else {
8630: while ( my ($host,$hostname) = each(%possible_hosts)) {
8631: if ($hostdom{$host} eq $domain) {
8632: $result{$host} = $hostname;
8633: }
1.841 albertel 8634: }
8635: }
8636: return %result;
8637: }
1.845 albertel 8638:
1.844 albertel 8639: sub host_domain {
1.852 albertel 8640: &load_hosts_tab() if (!$loaded);
8641:
1.844 albertel 8642: my ($lonid) = @_;
8643: return $hostdom{$lonid};
8644: }
8645:
1.841 albertel 8646: sub all_domains {
1.852 albertel 8647: &load_hosts_tab() if (!$loaded);
8648:
1.841 albertel 8649: my %seen;
8650: my @uniq = grep(!$seen{$_}++, values(%hostdom));
8651: return @uniq;
8652: }
1.1 albertel 8653: }
8654:
1.847 albertel 8655: {
8656: my %iphost;
1.856 albertel 8657: my %name_to_ip;
8658: my %lonid_to_ip;
1.869 albertel 8659:
1.847 albertel 8660: sub get_hosts_from_ip {
8661: my ($ip) = @_;
8662: my %iphosts = &get_iphost();
8663: if (ref($iphosts{$ip})) {
8664: return @{$iphosts{$ip}};
8665: }
8666: return;
1.839 albertel 8667: }
1.864 albertel 8668:
8669: sub reset_hosts_ip_info {
8670: undef(%iphost);
8671: undef(%name_to_ip);
8672: undef(%lonid_to_ip);
8673: }
1.856 albertel 8674:
8675: sub get_host_ip {
8676: my ($lonid) = @_;
8677: if (exists($lonid_to_ip{$lonid})) {
8678: return $lonid_to_ip{$lonid};
8679: }
8680: my $name=&hostname($lonid);
8681: my $ip = gethostbyname($name);
8682: return if (!$ip || length($ip) ne 4);
8683: $ip=inet_ntoa($ip);
8684: $name_to_ip{$name} = $ip;
8685: $lonid_to_ip{$lonid} = $ip;
8686: return $ip;
8687: }
1.847 albertel 8688:
8689: sub get_iphost {
1.869 albertel 8690: my ($ignore_cache) = @_;
1.894 albertel 8691:
1.869 albertel 8692: if (!$ignore_cache) {
8693: if (%iphost) {
8694: return %iphost;
8695: }
8696: my ($ip_info,$cached)=
8697: &Apache::lonnet::is_cached_new('iphost','iphost');
8698: if ($cached) {
8699: %iphost = %{$ip_info->[0]};
8700: %name_to_ip = %{$ip_info->[1]};
8701: %lonid_to_ip = %{$ip_info->[2]};
8702: return %iphost;
8703: }
8704: }
1.894 albertel 8705:
8706: # get yesterday's info for fallback
8707: my %old_name_to_ip;
8708: my ($ip_info,$cached)=
8709: &Apache::lonnet::is_cached_new('iphost','iphost');
8710: if ($cached) {
8711: %old_name_to_ip = %{$ip_info->[1]};
8712: }
8713:
1.888 albertel 8714: my %name_to_host = &all_names();
8715: foreach my $name (keys(%name_to_host)) {
1.847 albertel 8716: my $ip;
8717: if (!exists($name_to_ip{$name})) {
8718: $ip = gethostbyname($name);
8719: if (!$ip || length($ip) ne 4) {
1.894 albertel 8720: if (defined($old_name_to_ip{$name})) {
8721: $ip = $old_name_to_ip{$name};
8722: &logthis("Can't find $name defaulting to old $ip");
8723: } else {
8724: &logthis("Name $name no IP found");
8725: next;
8726: }
8727: } else {
8728: $ip=inet_ntoa($ip);
1.847 albertel 8729: }
8730: $name_to_ip{$name} = $ip;
8731: } else {
8732: $ip = $name_to_ip{$name};
1.653 albertel 8733: }
1.888 albertel 8734: foreach my $id (@{ $name_to_host{$name} }) {
8735: $lonid_to_ip{$id} = $ip;
8736: }
8737: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 8738: }
1.869 albertel 8739: &Apache::lonnet::do_cache_new('iphost','iphost',
8740: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 8741: 48*60*60);
1.869 albertel 8742:
1.847 albertel 8743: return %iphost;
1.598 albertel 8744: }
8745: }
8746:
1.862 albertel 8747: BEGIN {
8748:
8749: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
8750: unless ($readit) {
8751: {
8752: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
8753: %perlvar = (%perlvar,%{$configvars});
8754: }
8755:
8756:
1.1 albertel 8757: # ------------------------------------------------------ Read spare server file
8758: {
1.448 albertel 8759: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 8760:
8761: while (my $configline=<$config>) {
8762: chomp($configline);
1.284 matthew 8763: if ($configline) {
1.784 albertel 8764: my ($host,$type) = split(':',$configline,2);
1.785 albertel 8765: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 8766: push(@{ $spareid{$type} }, $host);
1.1 albertel 8767: }
8768: }
1.448 albertel 8769: close($config);
1.1 albertel 8770: }
1.11 www 8771: # ------------------------------------------------------------ Read permissions
8772: {
1.448 albertel 8773: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 8774:
8775: while (my $configline=<$config>) {
1.448 albertel 8776: chomp($configline);
8777: if ($configline) {
8778: my ($role,$perm)=split(/ /,$configline);
8779: if ($perm ne '') { $pr{$role}=$perm; }
8780: }
1.11 www 8781: }
1.448 albertel 8782: close($config);
1.11 www 8783: }
8784:
8785: # -------------------------------------------- Read plain texts for permissions
8786: {
1.448 albertel 8787: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 8788:
8789: while (my $configline=<$config>) {
1.448 albertel 8790: chomp($configline);
8791: if ($configline) {
1.742 raeburn 8792: my ($short,@plain)=split(/:/,$configline);
8793: %{$prp{$short}} = ();
8794: if (@plain > 0) {
8795: $prp{$short}{'std'} = $plain[0];
8796: for (my $i=1; $i<@plain; $i++) {
8797: $prp{$short}{'alt'.$i} = $plain[$i];
8798: }
8799: }
1.448 albertel 8800: }
1.135 www 8801: }
1.448 albertel 8802: close($config);
1.135 www 8803: }
8804:
8805: # ---------------------------------------------------------- Read package table
8806: {
1.448 albertel 8807: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 8808:
8809: while (my $configline=<$config>) {
1.483 albertel 8810: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 8811: chomp($configline);
8812: my ($short,$plain)=split(/:/,$configline);
8813: my ($pack,$name)=split(/\&/,$short);
8814: if ($plain ne '') {
8815: $packagetab{$pack.'&'.$name.'&name'}=$name;
8816: $packagetab{$short}=$plain;
8817: }
1.11 www 8818: }
1.448 albertel 8819: close($config);
1.329 matthew 8820: }
8821:
8822: # ------------- set up temporary directory
8823: {
8824: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
8825:
1.11 www 8826: }
8827:
1.794 albertel 8828: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
8829: 'compress_threshold'=> 20_000,
8830: });
1.185 www 8831:
1.281 www 8832: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 8833: $dumpcount=0;
1.958 www 8834: $locknum=0;
1.22 www 8835:
1.163 harris41 8836: &logtouch();
1.672 albertel 8837: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 8838: $readit=1;
1.564 albertel 8839: {
8840: use integer;
8841: my $test=(2**32)+1;
1.568 albertel 8842: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 8843: &logthis(" Detected 64bit platform ($_64bit)");
8844: }
1.195 www 8845: }
1.1 albertel 8846: }
1.179 www 8847:
1.1 albertel 8848: 1;
1.191 harris41 8849: __END__
8850:
1.243 albertel 8851: =pod
8852:
1.191 harris41 8853: =head1 NAME
8854:
1.243 albertel 8855: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 8856:
8857: =head1 SYNOPSIS
8858:
1.243 albertel 8859: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 8860:
8861: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
8862:
1.243 albertel 8863: Common parameters:
8864:
8865: =over 4
8866:
8867: =item *
8868:
8869: $uname : an internal username (if $cname expecting a course Id specifically)
8870:
8871: =item *
8872:
8873: $udom : a domain (if $cdom expecting a course's domain specifically)
8874:
8875: =item *
8876:
8877: $symb : a resource instance identifier
8878:
8879: =item *
8880:
8881: $namespace : the name of a .db file that contains the data needed or
8882: being set.
8883:
8884: =back
8885:
1.394 bowersj2 8886: =head1 OVERVIEW
1.191 harris41 8887:
1.394 bowersj2 8888: lonnet provides subroutines which interact with the
8889: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
8890: about classes, users, and resources.
1.243 albertel 8891:
8892: For many of these objects you can also use this to store data about
8893: them or modify them in various ways.
1.191 harris41 8894:
1.394 bowersj2 8895: =head2 Symbs
1.191 harris41 8896:
1.394 bowersj2 8897: To identify a specific instance of a resource, LON-CAPA uses symbols
8898: or "symbs"X<symb>. These identifiers are built from the URL of the
8899: map, the resource number of the resource in the map, and the URL of
8900: the resource itself. The latter is somewhat redundant, but might help
8901: if maps change.
8902:
8903: An example is
8904:
8905: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
8906:
8907: The respective map entry is
8908:
8909: <resource id="19" src="/res/msu/korte/tests/part12.problem"
8910: title="Problem 2">
8911: </resource>
8912:
8913: Symbs are used by the random number generator, as well as to store and
8914: restore data specific to a certain instance of for example a problem.
8915:
8916: =head2 Storing And Retrieving Data
8917:
8918: X<store()>X<cstore()>X<restore()>Three of the most important functions
8919: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
8920: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
8921: is is the non-critical message twin of cstore. These functions are for
8922: handlers to store a perl hash to a user's permanent data space in an
8923: easy manner, and to retrieve it again on another call. It is expected
8924: that a handler would use this once at the beginning to retrieve data,
8925: and then again once at the end to send only the new data back.
8926:
8927: The data is stored in the user's data directory on the user's
8928: homeserver under the ID of the course.
8929:
8930: The hash that is returned by restore will have all of the previous
8931: value for all of the elements of the hash.
8932:
8933: Example:
8934:
8935: #creating a hash
8936: my %hash;
8937: $hash{'foo'}='bar';
8938:
8939: #storing it
8940: &Apache::lonnet::cstore(\%hash);
8941:
8942: #changing a value
8943: $hash{'foo'}='notbar';
8944:
8945: #adding a new value
8946: $hash{'bar'}='foo';
8947: &Apache::lonnet::cstore(\%hash);
8948:
8949: #retrieving the hash
8950: my %history=&Apache::lonnet::restore();
8951:
8952: #print the hash
8953: foreach my $key (sort(keys(%history))) {
8954: print("\%history{$key} = $history{$key}");
8955: }
8956:
8957: Will print out:
1.191 harris41 8958:
1.394 bowersj2 8959: %history{1:foo} = bar
8960: %history{1:keys} = foo:timestamp
8961: %history{1:timestamp} = 990455579
8962: %history{2:bar} = foo
8963: %history{2:foo} = notbar
8964: %history{2:keys} = foo:bar:timestamp
8965: %history{2:timestamp} = 990455580
8966: %history{bar} = foo
8967: %history{foo} = notbar
8968: %history{timestamp} = 990455580
8969: %history{version} = 2
8970:
8971: Note that the special hash entries C<keys>, C<version> and
8972: C<timestamp> were added to the hash. C<version> will be equal to the
8973: total number of versions of the data that have been stored. The
8974: C<timestamp> attribute will be the UNIX time the hash was
8975: stored. C<keys> is available in every historical section to list which
8976: keys were added or changed at a specific historical revision of a
8977: hash.
8978:
8979: B<Warning>: do not store the hash that restore returns directly. This
8980: will cause a mess since it will restore the historical keys as if the
8981: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 8982:
1.394 bowersj2 8983: Calling convention:
1.191 harris41 8984:
1.394 bowersj2 8985: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
8986: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 8987:
1.394 bowersj2 8988: For more detailed information, see lonnet specific documentation.
1.191 harris41 8989:
1.394 bowersj2 8990: =head1 RETURN MESSAGES
1.191 harris41 8991:
1.394 bowersj2 8992: =over 4
1.191 harris41 8993:
1.394 bowersj2 8994: =item * B<con_lost>: unable to contact remote host
1.191 harris41 8995:
1.394 bowersj2 8996: =item * B<con_delayed>: unable to contact remote host, message will be delivered
8997: when the connection is brought back up
1.191 harris41 8998:
1.394 bowersj2 8999: =item * B<con_failed>: unable to contact remote host and unable to save message
9000: for later delivery
1.191 harris41 9001:
1.967 bisitz 9002: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 9003:
1.394 bowersj2 9004: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 9005: that was requested
1.191 harris41 9006:
1.243 albertel 9007: =back
1.191 harris41 9008:
1.243 albertel 9009: =head1 PUBLIC SUBROUTINES
1.191 harris41 9010:
1.243 albertel 9011: =head2 Session Environment Functions
1.191 harris41 9012:
1.243 albertel 9013: =over 4
1.191 harris41 9014:
1.394 bowersj2 9015: =item *
9016: X<appenv()>
1.949 raeburn 9017: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 9018: the user envirnoment file, and will be restored for each access this
1.620 albertel 9019: user makes during this session, also modifies the %env for the current
1.949 raeburn 9020: process. Optional rolesarrayref - if defined contains a reference to an array
9021: of roles which are exempt from the restriction on modifying user.role entries
9022: in the user's environment.db and in %env.
1.191 harris41 9023:
9024: =item *
1.394 bowersj2 9025: X<delenv()>
9026: B<delenv($regexp)>: removes all items from the session
9027: environment file that matches the regular expression in $regexp. The
1.620 albertel 9028: values are also delted from the current processes %env.
1.191 harris41 9029:
1.795 albertel 9030: =item * get_env_multiple($name)
9031:
9032: gets $name from the %env hash, it seemlessly handles the cases where multiple
9033: values may be defined and end up as an array ref.
9034:
9035: returns an array of values
9036:
1.243 albertel 9037: =back
9038:
9039: =head2 User Information
1.191 harris41 9040:
1.243 albertel 9041: =over 4
1.191 harris41 9042:
9043: =item *
1.394 bowersj2 9044: X<queryauthenticate()>
9045: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 9046: authentication scheme
9047:
9048: =item *
1.394 bowersj2 9049: X<authenticate()>
9050: B<authenticate($uname,$upass,$udom)>: try to
9051: authenticate user from domain's lib servers (first use the current
9052: one). C<$upass> should be the users password.
1.191 harris41 9053:
9054: =item *
1.394 bowersj2 9055: X<homeserver()>
9056: B<homeserver($uname,$udom)>: find the server which has
9057: the user's directory and files (there must be only one), this caches
9058: the answer, and also caches if there is a borken connection.
1.191 harris41 9059:
9060: =item *
1.394 bowersj2 9061: X<idget()>
9062: B<idget($udom,@ids)>: find the usernames behind a list of IDs
9063: (IDs are a unique resource in a domain, there must be only 1 ID per
9064: username, and only 1 username per ID in a specific domain) (returns
9065: hash: id=>name,id=>name)
1.191 harris41 9066:
9067: =item *
1.394 bowersj2 9068: X<idrget()>
9069: B<idrget($udom,@unames)>: find the IDs behind a list of
9070: usernames (returns hash: name=>id,name=>id)
1.191 harris41 9071:
9072: =item *
1.394 bowersj2 9073: X<idput()>
9074: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 9075:
9076: =item *
1.394 bowersj2 9077: X<rolesinit()>
9078: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 9079:
9080: =item *
1.551 albertel 9081: X<getsection()>
9082: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 9083: course $cname, return section name/number or '' for "not in course"
9084: and '-1' for "no section"
9085:
9086: =item *
1.394 bowersj2 9087: X<userenvironment()>
9088: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 9089: passed in @what from the requested user's environment, returns a hash
9090:
1.858 raeburn 9091: =item *
9092: X<userlog_query()>
1.859 albertel 9093: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
9094: activity.log file. %filters defines filters applied when parsing the
9095: log file. These can be start or end timestamps, or the type of action
9096: - log to look for Login or Logout events, check for Checkin or
9097: Checkout, role for role selection. The response is in the form
9098: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
9099: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 9100:
1.243 albertel 9101: =back
9102:
9103: =head2 User Roles
9104:
9105: =over 4
9106:
9107: =item *
9108:
1.810 raeburn 9109: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 9110: F: full access
9111: U,I,K: authentication modes (cxx only)
9112: '': forbidden
9113: 1: user needs to choose course
9114: 2: browse allowed
1.766 albertel 9115: A: passphrase authentication needed
1.243 albertel 9116:
9117: =item *
9118:
9119: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
9120: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
9121: and course level
9122:
9123: =item *
9124:
9125: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
9126: explanation of a user role term
9127:
1.832 raeburn 9128: =item *
9129:
1.935 raeburn 9130: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 9131: All arguments are optional. Returns a hash of a roles, either for
9132: co-author/assistant author roles for a user's Construction Space
1.906 albertel 9133: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 9134: In the hash, keys are set to colon-separated $uname,$udom,$role, and
9135: (optionally) if $withsec is true, a fourth colon-separated item - $section.
9136: For each key, value is set to colon-separated start and end times for
9137: the role. If no username and domain are specified, will default to
1.934 raeburn 9138: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 9139: of role statuses (active, future or previous), roles
9140: (e.g., cc,in, st etc.) and domains of the roles which can be used
9141: to restrict the list of roles reported. If no array ref is
9142: provided for types, will default to return only active roles.
1.834 albertel 9143:
1.243 albertel 9144: =back
9145:
9146: =head2 User Modification
9147:
9148: =over 4
9149:
9150: =item *
9151:
1.957 raeburn 9152: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 9153: user for the level given by URL. Optional start and end dates (leave empty
9154: string or zero for "no date")
1.191 harris41 9155:
9156: =item *
9157:
1.243 albertel 9158: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
9159: change a users, password, possible return values are: ok,
9160: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
9161: refused
1.191 harris41 9162:
9163: =item *
9164:
1.243 albertel 9165: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 9166:
9167: =item *
9168:
1.963 raeburn 9169: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
9170: $forceid,$desiredhome,$email,$inststatus) :
1.243 albertel 9171: modify user
1.191 harris41 9172:
9173: =item *
9174:
1.286 matthew 9175: modifystudent
9176:
1.957 raeburn 9177: modify a student's enrollment and identification information.
1.286 matthew 9178: The course id is resolved based on the current users environment.
9179: This means the envoking user must be a course coordinator or otherwise
9180: associated with a course.
9181:
1.297 matthew 9182: This call is essentially a wrapper for lonnet::modifyuser and
9183: lonnet::modify_student_enrollment
1.286 matthew 9184:
9185: Inputs:
9186:
9187: =over 4
9188:
1.957 raeburn 9189: =item B<$udom> Student's loncapa domain
1.286 matthew 9190:
1.957 raeburn 9191: =item B<$uname> Student's loncapa login name
1.286 matthew 9192:
1.964 bisitz 9193: =item B<$uid> Student/Employee ID
1.286 matthew 9194:
1.957 raeburn 9195: =item B<$umode> Student's authentication mode
1.286 matthew 9196:
1.957 raeburn 9197: =item B<$upass> Student's password
1.286 matthew 9198:
1.957 raeburn 9199: =item B<$first> Student's first name
1.286 matthew 9200:
1.957 raeburn 9201: =item B<$middle> Student's middle name
1.286 matthew 9202:
1.957 raeburn 9203: =item B<$last> Student's last name
1.286 matthew 9204:
1.957 raeburn 9205: =item B<$gene> Student's generation
1.286 matthew 9206:
1.957 raeburn 9207: =item B<$usec> Student's section in course
1.286 matthew 9208:
9209: =item B<$end> Unix time of the roles expiration
9210:
9211: =item B<$start> Unix time of the roles start date
9212:
9213: =item B<$forceid> If defined, allow $uid to be changed
9214:
9215: =item B<$desiredhome> server to use as home server for student
9216:
1.957 raeburn 9217: =item B<$email> Student's permanent e-mail address
9218:
9219: =item B<$type> Type of enrollment (auto or manual)
9220:
1.963 raeburn 9221: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
9222:
9223: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 9224:
1.963 raeburn 9225: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 9226:
1.963 raeburn 9227: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 9228:
1.963 raeburn 9229: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 9230:
1.286 matthew 9231: =back
1.297 matthew 9232:
9233: =item *
9234:
9235: modify_student_enrollment
9236:
9237: Change a students enrollment status in a class. The environment variable
9238: 'role.request.course' must be defined for this function to proceed.
9239:
9240: Inputs:
9241:
9242: =over 4
9243:
9244: =item $udom, students domain
9245:
9246: =item $uname, students name
9247:
9248: =item $uid, students user id
9249:
9250: =item $first, students first name
9251:
9252: =item $middle
9253:
9254: =item $last
9255:
9256: =item $gene
9257:
9258: =item $usec
9259:
9260: =item $end
9261:
9262: =item $start
9263:
1.957 raeburn 9264: =item $type
9265:
9266: =item $locktype
9267:
9268: =item $cid
9269:
9270: =item $selfenroll
9271:
9272: =item $context
9273:
1.297 matthew 9274: =back
9275:
1.191 harris41 9276:
9277: =item *
9278:
1.243 albertel 9279: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
9280: custom role; give a custom role to a user for the level given by URL. Specify
9281: name and domain of role author, and role name
1.191 harris41 9282:
9283: =item *
9284:
1.243 albertel 9285: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 9286:
9287: =item *
9288:
1.243 albertel 9289: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
9290:
9291: =back
9292:
9293: =head2 Course Infomation
9294:
9295: =over 4
1.191 harris41 9296:
9297: =item *
9298:
1.631 albertel 9299: coursedescription($courseid) : returns a hash of information about the
9300: specified course id, including all environment settings for the
9301: course, the description of the course will be in the hash under the
9302: key 'description'
1.191 harris41 9303:
9304: =item *
9305:
1.624 albertel 9306: resdata($name,$domain,$type,@which) : request for current parameter
9307: setting for a specific $type, where $type is either 'course' or 'user',
9308: @what should be a list of parameters to ask about. This routine caches
9309: answers for 5 minutes.
1.243 albertel 9310:
1.877 foxr 9311: =item *
9312:
9313: get_courseresdata($courseid, $domain) : dump the entire course resource
9314: data base, returning a hash that is keyed by the resource name and has
9315: values that are the resource value. I believe that the timestamps and
9316: versions are also returned.
9317:
9318:
1.243 albertel 9319: =back
9320:
9321: =head2 Course Modification
9322:
9323: =over 4
1.191 harris41 9324:
9325: =item *
9326:
1.243 albertel 9327: writecoursepref($courseid,%prefs) : write preferences (environment
9328: database) for a course
1.191 harris41 9329:
9330: =item *
9331:
1.243 albertel 9332: createcourse($udom,$description,$url) : make/modify course
9333:
9334: =back
9335:
9336: =head2 Resource Subroutines
9337:
9338: =over 4
1.191 harris41 9339:
9340: =item *
9341:
1.243 albertel 9342: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 9343:
9344: =item *
9345:
1.243 albertel 9346: repcopy($filename) : subscribes to the requested file, and attempts to
9347: replicate from the owning library server, Might return
1.607 raeburn 9348: 'unavailable', 'not_found', 'forbidden', 'ok', or
9349: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 9350: resource. Expects the local filesystem pathname
9351: (/home/httpd/html/res/....)
9352:
9353: =back
9354:
9355: =head2 Resource Information
9356:
9357: =over 4
1.191 harris41 9358:
9359: =item *
9360:
1.243 albertel 9361: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
9362: a vairety of different possible values, $varname should be a request
9363: string, and the other parameters can be used to specify who and what
9364: one is asking about.
9365:
9366: Possible values for $varname are environment.lastname (or other item
9367: from the envirnment hash), user.name (or someother aspect about the
9368: user), resource.0.maxtries (or some other part and parameter of a
9369: resource)
1.204 albertel 9370:
9371: =item *
9372:
1.243 albertel 9373: directcondval($number) : get current value of a condition; reads from a state
9374: string
1.204 albertel 9375:
9376: =item *
9377:
1.243 albertel 9378: condval($condidx) : value of condition index based on state
1.204 albertel 9379:
9380: =item *
9381:
1.243 albertel 9382: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
9383: resource's metadata, $what should be either a specific key, or either
9384: 'keys' (to get a list of possible keys) or 'packages' to get a list of
9385: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
9386:
9387: this function automatically caches all requests
1.191 harris41 9388:
9389: =item *
9390:
1.243 albertel 9391: metadata_query($query,$custom,$customshow) : make a metadata query against the
9392: network of library servers; returns file handle of where SQL and regex results
9393: will be stored for query
1.191 harris41 9394:
9395: =item *
9396:
1.243 albertel 9397: symbread($filename) : return symbolic list entry (filename argument optional);
9398: returns the data handle
1.191 harris41 9399:
9400: =item *
9401:
1.243 albertel 9402: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 9403: a possible symb for the URL in $thisfn, and if is an encryypted
9404: resource that the user accessed using /enc/ returns a 1 on success, 0
9405: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 9406: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 9407:
1.191 harris41 9408:
9409: =item *
9410:
1.243 albertel 9411: symbclean($symb) : removes versions numbers from a symb, returns the
9412: cleaned symb
1.191 harris41 9413:
9414: =item *
9415:
1.243 albertel 9416: is_on_map($uri) : checks if the $uri is somewhere on the current
9417: course map, user must be in a course for it to work.
1.191 harris41 9418:
9419: =item *
9420:
1.243 albertel 9421: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 9422:
9423: =item *
9424:
1.243 albertel 9425: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
9426: a random seed, all arguments are optional, if they aren't sent it uses the
9427: environment to derive them. Note: if symb isn't sent and it can't get one
9428: from &symbread it will use the current time as its return value
1.191 harris41 9429:
9430: =item *
9431:
1.243 albertel 9432: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
9433: unfakeable, receipt
1.191 harris41 9434:
9435: =item *
9436:
1.620 albertel 9437: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 9438:
9439: =item *
9440:
1.243 albertel 9441: countacc($url) : count the number of accesses to a given URL
1.191 harris41 9442:
9443: =item *
9444:
1.243 albertel 9445: 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 9446:
9447: =item *
9448:
1.243 albertel 9449: 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 9450:
9451: =item *
9452:
1.243 albertel 9453: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 9454:
9455: =item *
9456:
1.243 albertel 9457: devalidate($symb) : devalidate temporary spreadsheet calculations,
9458: forcing spreadsheet to reevaluate the resource scores next time.
9459:
9460: =back
9461:
9462: =head2 Storing/Retreiving Data
9463:
9464: =over 4
1.191 harris41 9465:
9466: =item *
9467:
1.243 albertel 9468: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
9469: for this url; hashref needs to be given and should be a \%hashname; the
9470: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 9471: be derived from the env
1.191 harris41 9472:
9473: =item *
9474:
1.243 albertel 9475: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
9476: uses critical subroutine
1.191 harris41 9477:
9478: =item *
9479:
1.243 albertel 9480: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
9481: all args are optional
1.191 harris41 9482:
9483: =item *
9484:
1.717 albertel 9485: dumpstore($namespace,$udom,$uname,$regexp,$range) :
9486: dumps the complete (or key matching regexp) namespace into a hash
9487: ($udom, $uname, $regexp, $range are optional) for a namespace that is
9488: normally &store()ed into
9489:
9490: $range should be either an integer '100' (give me the first 100
9491: matching records)
9492: or be two integers sperated by a - with no spaces
9493: '30-50' (give me the 30th through the 50th matching
9494: records)
9495:
9496:
9497: =item *
9498:
9499: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
9500: replaces a &store() version of data with a replacement set of data
9501: for a particular resource in a namespace passed in the $storehash hash
9502: reference
9503:
9504: =item *
9505:
1.243 albertel 9506: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
9507: works very similar to store/cstore, but all data is stored in a
9508: temporary location and can be reset using tmpreset, $storehash should
9509: be a hash reference, returns nothing on success
1.191 harris41 9510:
9511: =item *
9512:
1.243 albertel 9513: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
9514: similar to restore, but all data is stored in a temporary location and
9515: can be reset using tmpreset. Returns a hash of values on success,
9516: error string otherwise.
1.191 harris41 9517:
9518: =item *
9519:
1.243 albertel 9520: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
9521: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 9522:
9523: =item *
9524:
1.243 albertel 9525: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9526: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 9527:
9528: =item *
9529:
1.243 albertel 9530: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
9531: namesp ($udom and $uname are optional)
1.191 harris41 9532:
9533: =item *
9534:
1.702 albertel 9535: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 9536: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 9537: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 9538:
1.702 albertel 9539: $range should be either an integer '100' (give me the first 100
9540: matching records)
9541: or be two integers sperated by a - with no spaces
9542: '30-50' (give me the 30th through the 50th matching
9543: records)
1.449 matthew 9544: =item *
9545:
9546: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
9547: $store can be a scalar, an array reference, or if the amount to be
9548: incremented is > 1, a hash reference.
9549:
9550: ($udom and $uname are optional)
1.191 harris41 9551:
9552: =item *
9553:
1.243 albertel 9554: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
9555: ($udom and $uname are optional)
1.191 harris41 9556:
9557: =item *
9558:
1.243 albertel 9559: cput($namespace,$storehash,$udom,$uname) : critical put
9560: ($udom and $uname are optional)
1.191 harris41 9561:
9562: =item *
9563:
1.748 albertel 9564: newput($namespace,$storehash,$udom,$uname) :
9565:
9566: Attempts to store the items in the $storehash, but only if they don't
9567: currently exist, if this succeeds you can be certain that you have
9568: successfully created a new key value pair in the $namespace db.
9569:
9570:
9571: Args:
9572: $namespace: name of database to store values to
9573: $storehash: hashref to store to the db
9574: $udom: (optional) domain of user containing the db
9575: $uname: (optional) name of user caontaining the db
9576:
9577: Returns:
9578: 'ok' -> succeeded in storing all keys of $storehash
9579: 'key_exists: <key>' -> failed to anything out of $storehash, as at
9580: least <key> already existed in the db (other
9581: requested keys may also already exist)
1.967 bisitz 9582: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 9583: 'con_lost' -> unable to contact request server
9584: 'refused' -> action was not allowed by remote machine
9585:
9586:
9587: =item *
9588:
1.243 albertel 9589: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9590: reference filled in from namesp (encrypts the return communication)
9591: ($udom and $uname are optional)
1.191 harris41 9592:
9593: =item *
9594:
1.243 albertel 9595: log($udom,$name,$home,$message) : write to permanent log for user; use
9596: critical subroutine
9597:
1.806 raeburn 9598: =item *
9599:
1.860 raeburn 9600: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
9601: array reference filled in from namespace found in domain level on either
9602: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 9603:
9604: =item *
9605:
1.860 raeburn 9606: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
9607: domain level either on specified domain server ($uhome) or primary domain
9608: server ($udom and $uhome are optional)
1.806 raeburn 9609:
1.943 raeburn 9610: =item *
9611:
9612: get_domain_defaults($target_domain) : returns hash with defaults for
9613: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
9614: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
9615: or localauth), initial password or a kerberos realm, language (e.g., en-us).
9616: Values are retrieved from cache (if current), or from domain's configuration.db
9617: (if available), or lastly from values in lonTabs/dns_domain,tab,
9618: or lonTabs/domain.tab.
9619:
9620: %domdefaults = &get_auth_defaults($target_domain);
9621:
1.243 albertel 9622: =back
9623:
9624: =head2 Network Status Functions
9625:
9626: =over 4
1.191 harris41 9627:
9628: =item *
9629:
9630: dirlist($uri) : return directory list based on URI
9631:
9632: =item *
9633:
1.243 albertel 9634: spareserver() : find server with least workload from spare.tab
9635:
9636: =back
9637:
9638: =head2 Apache Request
9639:
9640: =over 4
1.191 harris41 9641:
9642: =item *
9643:
1.243 albertel 9644: ssi($url,%hash) : server side include, does a complete request cycle on url to
9645: localhost, posts hash
9646:
9647: =back
9648:
9649: =head2 Data to String to Data
9650:
9651: =over 4
1.191 harris41 9652:
9653: =item *
9654:
1.243 albertel 9655: hash2str(%hash) : convert a hash into a string complete with escaping and '='
9656: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 9657:
9658: =item *
9659:
1.243 albertel 9660: hashref2str($hashref) : convert a hashref into a string complete with
9661: escaping and '=' and '&' separators, supports elements that are
9662: arrayrefs and hashrefs
1.191 harris41 9663:
9664: =item *
9665:
1.243 albertel 9666: arrayref2str($arrayref) : convert an arrayref into a string complete
9667: with escaping and '&' separators, supports elements that are arrayrefs
9668: and hashrefs
1.191 harris41 9669:
9670: =item *
9671:
1.243 albertel 9672: str2hash($string) : convert string to hash using unescaping and
9673: splitting on '=' and '&', supports elements that are arrayrefs and
9674: hashrefs
1.191 harris41 9675:
9676: =item *
9677:
1.243 albertel 9678: str2array($string) : convert string to hash using unescaping and
9679: splitting on '&', supports elements that are arrayrefs and hashrefs
9680:
9681: =back
9682:
9683: =head2 Logging Routines
9684:
9685: =over 4
9686:
9687: These routines allow one to make log messages in the lonnet.log and
9688: lonnet.perm logfiles.
1.191 harris41 9689:
9690: =item *
9691:
1.243 albertel 9692: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 9693:
9694: =item *
9695:
1.243 albertel 9696: logthis() : append message to the normal lonnet.log file, it gets
9697: preiodically rolled over and deleted.
1.191 harris41 9698:
9699: =item *
9700:
1.243 albertel 9701: logperm() : append a permanent message to lonnet.perm.log, this log
9702: file never gets deleted by any automated portion of the system, only
9703: messages of critical importance should go in here.
9704:
9705: =back
9706:
9707: =head2 General File Helper Routines
9708:
9709: =over 4
1.191 harris41 9710:
9711: =item *
9712:
1.481 raeburn 9713: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
9714: (a) files in /uploaded
9715: (i) If a local copy of the file exists -
9716: compares modification date of local copy with last-modified date for
9717: definitive version stored on home server for course. If local copy is
9718: stale, requests a new version from the home server and stores it.
9719: If the original has been removed from the home server, then local copy
9720: is unlinked.
9721: (ii) If local copy does not exist -
9722: requests the file from the home server and stores it.
9723:
9724: If $caller is 'uploadrep':
9725: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
9726: for request for files originally uploaded via DOCS.
9727: - returns 'ok' if fresh local copy now available, -1 otherwise.
9728:
9729: Otherwise:
9730: This indicates a call from the content generation phase of the request.
9731: - returns the entire contents of the file or -1.
9732:
9733: (b) files in /res
9734: - returns the entire contents of a file or -1;
9735: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 9736:
1.712 albertel 9737:
9738: =item *
9739:
9740: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
9741: reference
9742:
9743: returns either a stat() list of data about the file or an empty list
9744: if the file doesn't exist or couldn't find out about it (connection
9745: problems or user unknown)
9746:
1.191 harris41 9747: =item *
9748:
1.243 albertel 9749: filelocation($dir,$file) : returns file system location of a file
9750: based on URI; meant to be "fairly clean" absolute reference, $dir is a
9751: directory that relative $file lookups are to looked in ($dir of /a/dir
9752: and a file of ../bob will become /a/bob)
1.191 harris41 9753:
9754: =item *
9755:
9756: hreflocation($dir,$file) : returns file system location or a URL; same as
9757: filelocation except for hrefs
9758:
9759: =item *
9760:
9761: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
9762:
1.243 albertel 9763: =back
9764:
1.608 albertel 9765: =head2 Usererfile file routines (/uploaded*)
9766:
9767: =over 4
9768:
9769: =item *
9770:
9771: userfileupload(): main rotine for putting a file in a user or course's
9772: filespace, arguments are,
9773:
1.620 albertel 9774: formname - required - this is the name of the element in $env where the
1.608 albertel 9775: filename, and the contents of the file to create/modifed exist
1.620 albertel 9776: the filename is in $env{'form.'.$formname.'.filename'} and the
9777: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 9778: coursedoc - if true, store the file in the course of the active role
9779: of the current user
9780: subdir - required - subdirectory to put the file in under ../userfiles/
9781: if undefined, it will be placed in "unknown"
9782:
9783: (This routine calls clean_filename() to remove any dangerous
9784: characters from the filename, and then calls finuserfileupload() to
9785: complete the transaction)
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: clean_filename(): routine for cleaing a filename up for storage in
9793: userfile space, argument is:
9794:
9795: filename - proposed filename
9796:
9797: returns: the new clean filename
9798:
9799: =item *
9800:
9801: finishuserfileupload(): routine that creaes and sends the file to
9802: userspace, probably shouldn't be called directly
9803:
9804: docuname: username or courseid of destination for the file
9805: docudom: domain of user/course of destination for the file
9806: formname: same as for userfileupload()
9807: fname: filename (inculding subdirectories) for the file
9808:
9809: returns either the url of the uploaded file (/uploaded/....) if successful
9810: and /adm/notfound.html if unsuccessful
9811:
9812: =item *
9813:
9814: renameuserfile(): renames an existing userfile to a new name
9815:
9816: Args:
9817: docuname: username or courseid of destination for the file
9818: docudom: domain of user/course of destination for the file
9819: old: current file name (including any subdirs under userfiles)
9820: new: desired file name (including any subdirs under userfiles)
9821:
9822: =item *
9823:
9824: mkdiruserfile(): creates a directory is a userfiles dir
9825:
9826: Args:
9827: docuname: username or courseid of destination for the file
9828: docudom: domain of user/course of destination for the file
9829: dir: dir to create (including any subdirs under userfiles)
9830:
9831: =item *
9832:
9833: removeuserfile(): removes a file that exists in userfiles
9834:
9835: Args:
9836: docuname: username or courseid of destination for the file
9837: docudom: domain of user/course of destination for the file
9838: fname: filname to delete (including any subdirs under userfiles)
9839:
9840: =item *
9841:
9842: removeuploadedurl(): convience function for removeuserfile()
9843:
9844: Args:
9845: url: a full /uploaded/... url to delete
9846:
1.747 albertel 9847: =item *
9848:
9849: get_portfile_permissions():
9850: Args:
9851: domain: domain of user or course contain the portfolio files
9852: user: name of user or num of course contain the portfolio files
9853: Returns:
9854: hashref of a dump of the proper file_permissions.db
9855:
9856:
9857: =item *
9858:
9859: get_access_controls():
9860:
9861: Args:
9862: current_permissions: the hash ref returned from get_portfile_permissions()
9863: group: (optional) the group you want the files associated with
9864: file: (optional) the file you want access info on
9865:
9866: Returns:
1.749 raeburn 9867: a hash (keys are file names) of hashes containing
9868: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
9869: values are XML containing access control settings (see below)
1.747 albertel 9870:
9871: Internal notes:
9872:
1.749 raeburn 9873: access controls are stored in file_permissions.db as key=value pairs.
9874: key -> path to file/file_name\0uniqueID:scope_end_start
9875: where scope -> public,guest,course,group,domains or users.
9876: end -> UNIX time for end of access (0 -> no end date)
9877: start -> UNIX time for start of access
9878:
9879: value -> XML description of access control
9880: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
9881: <start></start>
9882: <end></end>
9883:
9884: <password></password> for scope type = guest
9885:
9886: <domain></domain> for scope type = course or group
9887: <number></number>
9888: <roles id="">
9889: <role></role>
9890: <access></access>
9891: <section></section>
9892: <group></group>
9893: </roles>
9894:
9895: <dom></dom> for scope type = domains
9896:
9897: <users> for scope type = users
9898: <user>
9899: <uname></uname>
9900: <udom></udom>
9901: </user>
9902: </users>
9903: </scope>
9904:
9905: Access data is also aggregated for each file in an additional key=value pair:
9906: key -> path to file/file_name\0accesscontrol
9907: value -> reference to hash
9908: hash contains key = value pairs
9909: where key = uniqueID:scope_end_start
9910: value = UNIX time record was last updated
9911:
9912: Used to improve speed of look-ups of access controls for each file.
9913:
9914: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
9915:
9916: modify_access_controls():
9917:
9918: Modifies access controls for a portfolio file
9919: Args
9920: 1. file name
9921: 2. reference to hash of required changes,
9922: 3. domain
9923: 4. username
9924: where domain,username are the domain of the portfolio owner
9925: (either a user or a course)
9926:
9927: Returns:
9928: 1. result of additions or updates ('ok' or 'error', with error message).
9929: 2. result of deletions ('ok' or 'error', with error message).
9930: 3. reference to hash of any new or updated access controls.
9931: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
9932: key = integer (inbound ID)
9933: value = uniqueID
1.747 albertel 9934:
1.608 albertel 9935: =back
9936:
1.243 albertel 9937: =head2 HTTP Helper Routines
9938:
9939: =over 4
9940:
1.191 harris41 9941: =item *
9942:
9943: escape() : unpack non-word characters into CGI-compatible hex codes
9944:
9945: =item *
9946:
9947: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
9948:
1.243 albertel 9949: =back
9950:
9951: =head1 PRIVATE SUBROUTINES
9952:
9953: =head2 Underlying communication routines (Shouldn't call)
9954:
9955: =over 4
9956:
9957: =item *
9958:
9959: subreply() : tries to pass a message to lonc, returns con_lost if incapable
9960:
9961: =item *
9962:
9963: reply() : uses subreply to send a message to remote machine, logs all failures
9964:
9965: =item *
9966:
9967: critical() : passes a critical message to another server; if cannot
9968: get through then place message in connection buffer directory and
9969: returns con_delayed, if incapable of saving message, returns
9970: con_failed
9971:
9972: =item *
9973:
9974: reconlonc() : tries to reconnect lonc client processes.
9975:
9976: =back
9977:
9978: =head2 Resource Access Logging
9979:
9980: =over 4
9981:
9982: =item *
9983:
9984: flushcourselogs() : flush (save) buffer logs and access logs
9985:
9986: =item *
9987:
9988: courselog($what) : save message for course in hash
9989:
9990: =item *
9991:
9992: courseacclog($what) : save message for course using &courselog(). Perform
9993: special processing for specific resource types (problems, exams, quizzes, etc).
9994:
1.191 harris41 9995: =item *
9996:
9997: goodbye() : flush course logs and log shutting down; it is called in srm.conf
9998: as a PerlChildExitHandler
1.243 albertel 9999:
10000: =back
10001:
10002: =head2 Other
10003:
10004: =over 4
10005:
10006: =item *
10007:
10008: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 10009:
10010: =back
10011:
10012: =cut
1.877 foxr 10013:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>